Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Use serverless function to send low-volume emails without 3rd party mail services.

Sending email with serverless functions

You can deploy this function on any of the serverless platforms - AWS Lambda, Google Cloud Functions, Azure Functions, Netlify, Cloudflare Workers, etc.

  1. Create a new function and paste in the following code.
  2. You will need to add nodemailer to your package.json (npm i nodemailer), and follow your platform's instructions on bundling dependencies.
  3. Obtain Gmail API credentials for your account. You will need clientID, clientSecret, and refreshToken. Follow this YouTube tutorial
  4. Expose these credentials as the follwing environment variables:
GMAIL_EMAIL_ADDRESS
GMAIL_API_CLIENT_ID
GMAIL_API_CLIENT_SECRET
GMAIL_API_REFRESH_TOKEN
  1. Deploy!
  // Docs on event and context https://www.netlify.com/docs/functions/#the-handler-method
const nodemailer = require("nodemailer");

function createMailClient() {
  return nodemailer.createTransport({
    host: "smtp.gmail.com",
    port: 587,
    secure: false, // true for 465, false for other ports
    auth: {
      type: 'OAuth2',
      user: process.env.GMAIL_EMAIL_ADDRESS,
      clientId: process.env.GMAIL_API_CLIENT_ID,
      clientSecret: process.env.GMAIL_API_CLIENT_SECRET,
      refreshToken: process.env.GMAIL_API_REFRESH_TOKEN,
    }
  });
}


const mailClient = createMailClient();

exports.handler = async (event, context) => {
  try {
    const json = JSON.parse(event.body);
    const gmailResponse = await mailClient.sendMail({
      from: '"Benedict Arnold" <barnold@us.gov>', // sender address
      to: "Sir Henry Clinton <hclinton@gov.uk>", // list of receivers
      subject: json.subject,
      text: json.text, // plain text body
      html: json.html
    });

    return {
      statusCode: 200,
      body: "Message sent!" + gmailResponse.messageId
    }
  } catch (err) {
    return { statusCode: 500, body: err.toString() }
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment