Sending email with Nodemailer using a lambda

Get rid of your backend and use this lambda instead

Mon, 06 Aug 2018

I used this lambda with the Stripe example I shared yesterday. Whenever I processed a payment successfully, I would call this lambda to send a confirmation email to myself. Luckily for us, the implementation doesn’t change much from the example provided in the official repo. Here is the full code example

var sesAccessKey = '<email username>'
var sesSecretKey = '<email password>'

 exports.handler = function(event, context, callback) {

  	var nodemailer = require('nodemailer');
  	var smtpTransport = require('nodemailer-smtp-transport');

  	var transporter = nodemailer.createTransport(smtpTransport({
	    service: 'gmail',
	    auth: {
	        user: sesAccessKey,
	        pass: sesSecretKey
	    }
  	}));

  	var text = 'Email body goes here';

  	var mailOptions = {
	    from: '<from email address',
	    to: '<to email address>',
	    bcc: '<bcc email addres>',
	    subject: 'Test subject',
	    text: text
  	};

  	transporter.sendMail(mailOptions, function(error, info){
      if(error){
        const response = {
          statusCode: 500,
          body: JSON.stringify({
            error: error.message,
          }),
        };
        callback(null, response);
      }
      const response = {
        statusCode: 200,
        body: JSON.stringify({
          message: `Email processed succesfully!`
        }),
      };
      callback(null, response);
    });
}

To start using this example you’re going to need to download the following node packages using your package manager of choice

yarn

yarn add nodemailer-smtp-transport nodemailer

npm

npm install nodemailer-smtp-transport nodemailer

Starting from the top, we create two new variables, sesAccessKey and sesSecretKey. sesAccessKey will store your email username, for most email providers its usually just your full email address. The second variable sesSecretKey stores your password. This block will set settings for our smtp server

  	var transporter = nodemailer.createTransport(smtpTransport({
	    service: 'gmail',
	    auth: {
	        user: sesAccessKey,
	        pass: sesSecretKey
	    }
  	}));

The service option preconfigures outgoing and incoming ports/servers for popular mail services. Some of those services include, AOL, Godaddy, Hotmail, iCloud and Outlook365. For a full list of preconfigured services check out this link. If you don’t use one of the preconfigured services for email, you can replace the service option with the following

host: 'smtp.example.com',
port: 587,
secure: false, // Activate TLS/STARTTLS

Now that we have our smtp service configured we can start to get ready to send some email!

The variable text will contain the body of the email. Depending on your usage, you can make the body static or pass in variables when you call your lambda. If you wanted to pass an object containing some variables you can do it like this

var msg = JSON.stringify({
	 text: "This is a test message"
 )}

 axios.post('/.netlify/functions/email', msg)

To access the object in your lambda add the following lines of code inside your module.exports.handler method right at the beginning.

const requestBody = JSON.parse(event.body);
const emailBody = requestBody.text;

Any parameters sent to your lambda is sent inside the event object and is accessible from the body key within. I posted a full example in my tutorial for creating charges for Stripe.

The next section creates an object that stores the full email message. If you ever sent email before(I really hope so if you’re reading this 🙄) these options should be familiar. Just your typical to, from, bcc, subject and text(body of email).

The final portion is sending the actual email. Since we already set up our variables, the first line of code ends up doing the majority of the work for us.

transporter.sendMail(mailOptions, function(error, info)

This line uses the smtp config that we set up at the beginning and our mailOptions object contains our to, from, bcc, subject and body for the email. Once this function executes it takes the result and calls another basic function. If the call failed it will return a response object with a status code of 500(internal server error aka - server encountered an unexpected condition that prevented it from fulfilling the request) and a body object with the contents of the error message. If everything worked as intended, this is something we will hopefully not see. If the email sent successfully you will instead get a status code of 200(okay) and body message of “Email processed succesfully!”

Buy Me A CoffeeDigitalOcean Referral Badge
Loading...
Edward Beazer

Edward Beazer - I just like to build shit. Sometimes I get stuck for hours, even days while trying to figure out how to solve an issue or implement a new feature. Hope my tips and tutorials can save you some time.

DigitalOcean Referral Badge