Last Updated: December 26, 2018
·
4.28K
· Ionut-Cristian Florescu

Sending emails from Node.js, the simplest way

There are many excellent email related services in the Cloud (like SendGrid or MailGun to name just two of them) and almost all of them have Node.js modules and APIs to work with.

Sending emails from Node.js - the simplest way

However, sometimes simpler is better, and if you have a simple/small webapp and need a straightforward way to send just a few emails, there's an easy way do it with Nodemailer and Gmail, in just a few lines of code and almost no configuration at all:

smtp = require('nodemailer').createTransport 'SMTP',
  service: 'Gmail'
  auth:
    user: process.env.GMAIL_USER
    pass: process.env.GMAIL_PASS

...

await smtp.sendMail
    from:    "The Awesome Company <#{process.env.COMPANY_EMAIL}>"
    to:      "Recipient name <#{user.email}>"
    subject: "Thank you for your feedback, #{user.name}!"
    html:    """
             <p>Your feedback is very important to us!</p>
             <p>
               Sincerely,<br />
               The Awesome Team
             </p>
             """
  , defer err, message

The code sample above assumes you're using IcedCoffeeScript to streamline the asynchronous control flow, but of course, it can be done in CoffeeScript or plain Javascript as well.

Have a fresh tip? Share with Coderwall community!

Post
Post a tip