Nodemailer nodejs email with attachment

A Quick Guide to Nodemailer: Add Email Functionality to Node.js Projects

From SMTP to Sendmail — a guide to demonstrate how Nodemailer makes it easy to send emails from your Node.js applications.

Trends come & trends go. But emails seem to be forever.

In the online world, it is a common requirement to share attachments with emails.

From SaaS-based Martech applications sending social engagement reports and ad spending reports as an attachment to eCommerce apps auto-generating PDF invoices — emails with attachment is everywhere

In this insight, we shall demonstrate how to programmatically generate PDFs on the go using NodeJs

The library we have used is Nodemailer. It’s a zero-dependency, highly secure nodeJS library to send emails from your servers in your preferred format with or without attachments.

Jump to this section to explore the features of the Nodemailer.

First, let’s install Nodemailer, before we do anything else.

You can easily install Nodemailer using:

npm install nodemailer

Nodemailer Features

  • Supports Unicode & you can also add emojis to your emails.
  • You can deploy it from anywhere — Cloud, or local server.
  • Send plain text, or HTML emails — with or without attachments and embedded images.
  • Support for DKIM, TLS, STARTTLS, SMTP, OAuth2, Proxies, Ethereal.email for fake SMTP servers, etcetera.

For more features, you can read the Nodemailer documentation.

How to create dynamic emails with Nodemailer?

As mentioned earlier, you need to install the nodemailer package by running the following command in your terminal:

npm install nodemailer

To use the package in your code, add the following line:

const nodemailer = require('nodemailer')

Now, add the credentials file.

For security reasons, it is recommended to keep the credentials in a separate file.

const crd = require('PATH_TO_YOUR_FILE_CONTAINING_CREDENTIALS')

Now, we shall use the GMAIL SMTP server to create a dummy Nodemailer module for creating & sending emails automatically from your server

exports.SendInvoiceMail = async (email,attachmentUrl) => {
    const mail = nodemailer.createTransport({
        host: 'smtp.gmail.com',
        port: 587,
        secure: false,
        auth: { user: crd.user1 , pass: crd.pass1 },
    })

In the above code, we have created a controller where it is named as SendInvoiceMail. This handles the routes for sending mail inside the function. 

The ‘mail’ variable invokes an instance of the nodemailer’s createTransport function.

CreateTransport defines the host, port, security protocol, and email authentication credentials — the essential components to trigger your email from the server. 

Multiple other options can be configured, you may find the same in the documentation.

Host relates to the mail server which your nodeJs app should use to send emails. We have used Gmail’s SMTP i.e., smtp.gmail.com. The Port used is 587, and the value for the ‘secure’ function can be set to ‘true’ or ‘false’.

Two credential parameters are passed to the auth attribute — for user authentication.

Next, we create the email which needs to be sent.

  mail.sendMail({
        from: 'hi@company.com',
        to: [email],
        subject: 'Whatever you want',
        html: message,
        attachments: [{
            filename: 'Receipt.pdf',
            path: attachmentUrl,
            contentType: 'application/pdf'
          }]
    }, (err) => {
        if (err) throw err;
        console.log(`Invoice Mail sent to ${email}`)
        return true
    })
    return true

We have invoked the sendMail method of the Nodemailer’s create transport function. 

sendMail method attributes

  • From: Sender’s email
  • To: Receiver’s email
  • Subject: Email’s subject line
  • HTML: The HTML email format
  • Attachment: To define the file path & contentType
const message = 'We thank you wholeheartedly for the contribution made towards Codewave Go Green. Please find the <br> receipt enclosed. We will be sending an 80G certificate in the month of Mar/April 2023. <br><br> Best regards,Codewave;    

Attachments this property allows you to attach documents where you can name your file using filename and path is the attachment which is generated or attached document and contentType is the type of document that needs to be sent like pdf so application/pdf.

The last block of code is to catch errors.

Summing it up

Nodemailer is a powerful and flexible Node.js library for sending emails.

It allows developers to easily send emails from their Node.js applications using a variety of transport methods, including SMTP, SES, and Sendmail.

Nodemailer also supports advanced features such as HTML email, attachments, and authentication.

With its simple API and comprehensive documentation, Nodemailer makes it easy for developers to add email functionality to their projects.

Overall, Nodemailer is a great choice for any Node.js developer looking to add email functionality to their application.

For more insights on tech, design, and culture — follow Codewave.

Visit Codewave.com for building innovative digital products.

Total
0
Shares
Leave a Reply

Your email address will not be published. Required fields are marked *

Prev
Codewave’s Reflections & Takeaways From 2022
2022 REFLECTIONS TAKEAWAYS Codewave

Codewave’s Reflections & Takeaways From 2022

Stepping into the new year 2023 by reflecting on the top highlights & takeaways

Next
Celebrate Progress, not Perfection
perfection is a journey, not a destination

Celebrate Progress, not Perfection

A story of how a Dad nurtures his son to keep getting better at his craft,

Subscribe to Codewave Insights