NodeJS
How to send Email Attachments with Nodemailer
May 15, 2020
1 min

Email is an essential means of communication in web applications that is fast, cheap, accessible and easily replicated.

Here, we are going to discuss about sending email via nodejs with attachments. We will use nodemailer module to send the email. Let’s dig into how this works in more detail.

Step 1: Installing Nodemailer

To install nodemailer, hit the below command in the terminal.

npm install nodemailer

Next, include the nodemailer module in your application.

const nodemailer = require('nodemailer');

Step 2: Configure Nodemailer with Gmail

The nodemailer needs a transport service that can send emails. Here, we will be creating a reusable transporter object using the default SMTP transport.

Then, we will be giving the service type to gmail. The auth object specifies the gmail account credentials that we will use to send emails.

let transporter = nodemailer.createTransport({
    service:'gmail',
    auth: {
        user: 'abc@gmail.com',       ## Your gmail address
        pass: 'abc1234',             ## password
    },
});

Step 3: Sending Email

We can define mail options as follows. Attachments can be added to an array labeled attachments.

const mailOptions={
    from: 'samplesender@gmail.com',                  ## sender address
    to: 'samplereceiver@gmail.com',                  ## list of receivers
    subject: " Sending Email using Node.js”          ## Subject line
    text: NodeJs is awesome,                         ## plain text body
    html: `<b>NodeJs is awesome</b>`,                ## html body
    attachments: [
        {   
        filename: 'text3.txt',                       ## file on disk as an attachment
        path: '/path/to/file.txt'                    ## stream this file
        },
    ]    
}

Attachment object consists of the following properties:

  • filename - filename to be reported as the name of the attached file. Use of unicode is allowed.
  • content - String, Buffer or a Stream contents for the attachment
  • path - path to the file if you want to stream the file instead of including it (better for larger attachments)
  • href – an URL to the file (data uris are allowed as well)
  • httpHeaders - optional HTTP headers to pass on with the href request, eg. {authorization: “bearer …“}
  • contentType - optional content type for the attachment, if not set will be derived from the filename property
  • contentDisposition - optional content disposition type for the attachment, defaults to ‘attachment’
  • cid - optional content id for using inline images in HTML message source
  • encoding - If set and content is string, then encodes the content to a Buffer using the specified encoding. Example values: ‘base64’, ‘hex’, ‘binary’ etc. Useful if you want to use binary attachments in a JSON formatted email object.
  • headers - custom headers for the attachment node. Same usage as with message headers
  • raw - is an optional special value that overrides entire contents of current mime node including mime headers. Useful if you want to prepare node contents yourself

For example, you can add as many attachments as you want below.

attachments: [
        {   ## utf-8 string as an attachment
            filename: 'text1.txt',
            content: 'hello world!'
        },
        {   ## binary buffer as an attachment
            filename: 'text2.txt',
            content: new Buffer('hello world!','utf-8')
        },
        {   ## file on disk as an attachment
            filename: 'text3.txt',
            path: '/path/to/file.txt' 
        },
        {   ## filename and content type is derived from path
            path: '/path/to/file.txt'
        },
        {   ## stream as an attachment
            filename: 'text4.txt',
            content: fs.createReadStream('file.txt')
        },
        {   ## define custom content type for the attachment
            filename: 'text.bin',
            content: 'hello world!',
            contentType: 'text/plain'
        },
        {   ## use URL as an attachment
            filename: 'license.txt',
            path: 'https:##raw.github.com/nodemailer/nodemailer/master/LICENSE'
        },
        {   ## encoded string as an attachment
            filename: 'text1.txt',
            content: 'aGVsbG8gd29ybGQh',
            encoding: 'base64'
        },
        {   ## data uri as an attachment
            path: 'data:text/plain;base64,aGVsbG8gd29ybGQ='
        },
        {   ## use pregenerated MIME node
            raw: 'Content-Type: text/plain\r\n' +
                 'Content-Disposition: attachment;\r\n' +
                 '\r\n' +
                 'Hello world!'
        }
    ]

Then we can send the email by using the sendMail method provided by the transporter object we created above.

transporter.sendMail(mailOptions)

Tags

nodejsnodemailer

Related Posts

NodeJS
How to send gmails using Nodemailer from your NodeJS server
May 09, 2020
3 min