Category: 10. Nodemailer

https://static.vecteezy.com/system/resources/previews/044/178/327/non_2x/incoming-message-email-cloud-electronic-mail-storage-server-3d-icon-realistic-illustration-vector.jpg

  • Using HTML Templates

    If you need to send dynamic HTML emails, consider using templating engines like Handlebars or EJS. Here’s how you might use Handlebars with Nodemailer:

    Install the required packages:

    npm install handlebars nodemailer-express-handlebars
    

    Set up Nodemailer with Handlebars:

    const nodemailer = require('nodemailer');
    const path = require('path');
    const hbs = require('nodemailer-express-handlebars');
    
    // Create a transporter object
    let transporter = nodemailer.createTransport({
    
    service: 'gmail',
    auth: {
        user: process.env.EMAIL_USER,
        pass: process.env.EMAIL_PASS
    }
    }); // Set up Handlebars transporter.use('compile', hbs({
    viewEngine: {
        extName: '.hbs',
        partialsDir: path.resolve('./views/'),
        layoutsDir: path.resolve('./views/'),
        defaultLayout: 'email'
    },
    viewPath: path.resolve('./views/'),
    extName: '.hbs'
    })); // Email options let mailOptions = {
    from: '"Your Name" <[email protected]>',
    to: '[email protected]',
    subject: 'Hello with Handlebars',
    template: 'email', // Name of the template file (email.hbs)
    context: { // Data to pass to the template
        name: 'Recipient',
        message: 'This is a test email using Handlebars!'
    }
    }; // Send email transporter.sendMail(mailOptions, (error, info) => {
    if (error) {
        return console.error('Error sending email:', error);
    }
    console.log('Email sent successfully:', info.response);
    });

    Template file (views/email.hbs):

    <!DOCTYPE html>
    <html>
    <head>
    
    &lt;title>{{subject}}&lt;/title>
    </head> <body>
    &lt;h1>Hello, {{name}}!&lt;/h1>
    &lt;p>{{message}}&lt;/p>
    </body> </html>
  • Sending to Multiple Recipients

    You can send emails to multiple recipients by separating email addresses with commas:

    to: '[email protected], [email protected]'
    
  • Handling Errors

    Always handle errors gracefully:

    transporter.sendMail(mailOptions, (error, info) => {
    
    if (error) {
        return console.error('Error sending email:', error);
    }
    console.log('Email sent successfully:', info.response);
    });
  • Using Environment Variables

    For security, store sensitive information like email credentials in environment variables:

    let transporter = nodemailer.createTransport({
    
    service: 'gmail',
    auth: {
        user: process.env.EMAIL_USER,
        pass: process.env.EMAIL_PASS
    }
    });

    In your .env file:

    [email protected]
    EMAIL_PASS=your-email-password
    
  • HTML Email with Inline Images

    For inline images, use the cid (Content-ID) in your HTML:

    <img src="cid:[email protected]" />
    
  • Attachments

    To send attachments, modify the mailOptions like so:

    let mailOptions = {
    
    from: '"Your Name" &lt;[email protected]>',
    to: '[email protected]',
    subject: 'Hello ✔',
    text: 'Hello world?',
    html: '&lt;b>Hello world?&lt;/b>',
    attachments: &#91;
        {
            filename: 'file.txt',
            path: '/path/to/file.txt'
        },
        {
            filename: 'image.png',
            path: '/path/to/image.png',
            cid: '[email protected]' // for inline images
        }
    ]
    };
  • Using SMTP

    If you need to use a custom SMTP server, configure it like this:

    let transporter = nodemailer.createTransport({
    
    host: 'smtp.example.com',
    port: 587, // or 465 for SSL
    secure: false, // true for 465, false for other ports
    auth: {
        user: 'your-username',
        pass: 'your-password'
    }
    });
  • Using Other Email Services

    You can configure Nodemailer to use other email services by adjusting the transport configuration. For example, to use SendGrid:

    let transporter = nodemailer.createTransport({
    
    service: 'SendGrid',
    auth: {
        user: 'apikey', // This is the default SendGrid username
        pass: 'your-sendgrid-api-key'
    }
    });
  • Basic Usage

    Here’s a simple example of sending an email:

    const nodemailer = require('nodemailer');
    
    // Create a transporter object using SMTP transport
    let transporter = nodemailer.createTransport({
    
    service: 'gmail', // You can use other services like 'hotmail', 'yahoo', etc.
    auth: {
        user: '[email protected]',
        pass: 'your-email-password'
    }
    }); // Set up email data let mailOptions = {
    from: '"Your Name" &lt;[email protected]>', // sender address
    to: '[email protected]', // list of receivers
    subject: 'Hello ✔', // Subject line
    text: 'Hello world?', // plain text body
    html: '&lt;b>Hello world?&lt;/b>' // html body
    }; // Send mail with defined transport object transporter.sendMail(mailOptions, (error, info) => {
    if (error) {
        return console.log(error);
    }
    console.log('Message sent: %s', info.messageId);
    });
  • Installation

    First, you need to install Nodemailer using npm:

    npm install nodemailer