DEV Community

Cover image for Send Email using Nodemailer to Google SMTP
Tyler Steck
Tyler Steck

Posted on

Send Email using Nodemailer to Google SMTP

Express.js TypeScript function that takes in an email body and sends it to the Google SMTP server using an access and refresh token, as well as allowing the addition of CSS to the email template:

import express, { Request, Response } from 'express';
import nodemailer from 'nodemailer';

const app = express();

app.use(express.json());

const transporter = nodemailer.createTransport({
  service: 'gmail',
  auth: {
    type: 'OAuth2',
    user: process.env.GOOGLE_EMAIL,
    clientId: process.env.GOOGLE_CLIENT_ID,
    clientSecret: process.env.GOOGLE_CLIENT_SECRET,
    refreshToken: process.env.GOOGLE_REFRESH_TOKEN,
    accessToken: process.env.GOOGLE_ACCESS_TOKEN,
  },
});

app.post('/send-email', async (req: Request, res: Response) => {
  try {
    const { to, subject, body, css } = req.body;

    const mailOptions = {
      from: process.env.GOOGLE_EMAIL,
      to,
      subject,
      html: `
        <html>
          <head>
            <style>
              ${css}
            </style>
          </head>
          <body>
            ${body}
          </body>
        </html>
      `,
    };

    await transporter.sendMail(mailOptions);

    res.send('Email sent successfully');
  } catch (err) {
    console.error(err);
    res.status(500).send('Error sending email');
  }
});

app.listen(3000, () => {
  console.log('Server listening on port 3000');
});
Enter fullscreen mode Exit fullscreen mode

In this example, we create an Express.js server and use the nodemailer library to create a transporter object that connects to the Google SMTP server using OAuth2 authentication. We then define an endpoint at /send-email that accepts a POST request with a JSON payload containing the to, subject, body, and css fields. The to field specifies the email address of the recipient, the subject field specifies the subject of the email, the body field specifies the body of the email, and the css field specifies any custom CSS styles to be applied to the email template.

In the endpoint handler function, we create a mailOptions object that contains the from, to, subject, and html fields.

Html field contains an HTML string that specifies the email template. This string includes a tag that injects the CSS styles provided in the css field, as well as the body field that contains the body of the email.</p> <p>We then use the <code>transporter</code> object to send the email using the <code>sendMail</code> method, passing in the <code>mailOptions</code> object.</p> <p>If there are any errors during the sending process, we catch them and return a 500 error response. Otherwise, we return a success response indicating that the email was sent successfully.</p> <p>Note that in order to use this function, you&#39;ll need to provide the required environment variables for the Google OAuth2 authentication, including the <code>GOOGLE_EMAIL</code>, <code>GOOGLE_CLIENT_ID</code>, <code>GOOGLE_CLIENT_SECRET</code>, <code>GOOGLE_REFRESH_TOKEN</code>, and <code>GOOGLE_ACCESS_TOKEN</code> fields.</p>

Top comments (1)

Collapse
 
legadaxx profile image
Emmanuel Appah

Is it necessary for one to have a refresh token? And why is a refresh token needed?