Node.js: how to send an email with attachments using Nodemailer

Node.js: how to send an email with attachments using Nodemailer

Nodemailer allows us to send emails with attachments.

Nodemailer allows us to send emails with attachments.

We can use the attachments options providing an array of objects whose properties refer to the main data of each file.


'use strict';

const nodemailer = require('nodemailer');
const path = require('path');
const ABSPATH = path.dirname(process.mainModule.filename); // Absolute path to our app directory

const transporter = nodemailer.createTransport({ // Use an app specific password here
  service: 'Gmail',
  auth: {
    user: 'email@gmail.com',
    pass: 'password'
  }
});

const options = {
    from: 'email@gmail.com',
    to: 'recipient@site.tld',
    subject: 'Test',
    text: 'Hello World',
    attachments: [
       {
        path: ABSPATH + '/images/test.jpg'
       }
    ]
};

transporter.sendMail(options, (error, info) =>{
    if(error) {
        //...
    } else {
        //...
    }
});