loading...

Test Emails in Your Node/Express Apps using Mailtrap.io

kwabenberko profile image Kwabena Bio Berko Updated on ・3 min read

One feature usually present in almost all software applications is an emailing feature, as it's one of the surest ways to get in touch and communicate with your users. There are many email delivery services that make the development of such a feature a breeze, such as Sendgrid, Postmark, Mailgun and Sparkpost. My favourite is Sendgrid. :)

Anyhow, the most common problem when developing an email feature in the pre-production stage is spamming, since you will definitely be using real email addresses when using any of the email delivery services listed above. Hence its neccessary to do sandbox testing.

Enter Mailtrap. Mailtrap is a fake SMTP server developed by railsware and its very useful for pre-production testing. Ideally, you should do email testing with a service like mailtrap and switch to sendgrid and the likes when rolling to production.

In this short example, I will show you how i do sandbox email testing in Node. If you want to follow along, kindly download or clone the project from github. Open up the project in your terminal, and install the required npm packages using npm install. Once installed, cd into the start folder and open the app.js file in your favorite editor. If you haven't done so already, head on over to the mailtrap website and create a free account. Once done navigate to the inbox and you should see both your SMTP and POP3 credentials.

Mailtrap inbox

We are going to use the nodemailer module to send our email. Lets create a nodemailer SMTP transporter and configure it for use.

  //Start Here
  const transporter = nodemailer.createTransport({
    host: "smtp.mailtrap.io",
    port: 2525,
    auth: {
        user: "MAILTRAP_SMTP_USERNAME",
        pass: "MAILTRAP_SMTP_PASSWORD"
    }
  });

Now, let's setup our message options:

  const mailOptions= {
    from: '"Test Server" <test@example.com>',
    to: req.body.email,
    subject: "Email Test",
    text: "This is an email test using Mailtrap.io"
  };

Then we send our message using the sendMail() method of our transporter object:



  transporter.sendMail(mailOptions, (err, info) => {
    if(err){
        console.log(err);
        return next(err);
    }
    console.log("Info: ", info);
    res.json({
      message: "Email successfully sent."
    });
  });

Let us test to see if this works. Fire up the server by typing node app.js. Now lets send a POST request to http://localhost:8001/email. I am going to use cURL for this. You can use Postman or any REST client of your choice.


curl -X POST -H "Content-Type:application/json" -d "{"""email""":"""johndoe@gmail.com"""}" http://localhost:8001/email                    

Hopefully, you get a response like the one below, which should mean the code worked:


{"message":"Email successfully sent."}

Let's check to see if this is the case by checking our mailtrap inbox.

Mailtrap inbox

Mailtrap inbox 2

As you can see, Mailtrap allows you to easily test sending emails, as was described above. The Node.js app used in this example makes use of Nodemailer to send emails, but there are other transport options and email packages out there. If you are looking for Nodemailer alternatives, kindly check out this article: Sending Emails with Node.js. This article goes in depth about some email-oriented packages like Email.js and how to use Gmail to send messages from your Node.js app.

Happy Coding!

Posted on by:

Discussion

pic
Editor guide
 

Hi Kwabena! This was pretty great but I think there are some errors. When I ran the app it could not even start because "req.body.email" was not defined. When I hard coded the recipient e-mail it worked, but the first time the app just runs and does not wait for information from POST. Once it's done sending that first pass I could not get it to return info from cURL or Postman. Any hints?

Again, great tutorial! I did not know about Mailtrap before I came across it.

 

Oops, nevermind, I see what I did! I should have tucked all of the demo inside of the POST route brackets. My bad! Now the tutorial is even better. Thanks again!

 

πŸ˜„
Glad you've resolved it.

 

Great article, Kwabena! Thanks for sharing ;)