How to attach file to an email with nodemailer

65,821

Solution 1

Include in the var mailOption the key attachments, as follow:

var mailOptions = {
...
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' // stream this file
    },
    {   // 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/andris9/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='
    }
 ]}

Choose the option that adjust to your needs.

Link:Nodemailer Repository GitHub

Good Luck!!

Solution 2

Your code is almost right, just need to add, "attachments" property for attaching the files in your mail,

YOUR mailOption:

var mailOption = {
        from: from,
        to:  to,
        subject: subject,
        text: text,
        html: html
}

Just add attachments like

var mailOption = {
        from: from,
        to:  to,
        subject: subject,
        text: text,
        html: html,
        attachments: [{
            filename: change with filename,
            path: change with file path
        }]
}

attachments also provide some other way to attach file for more information check nodemailer community's documentation HERE

Solution 3

If you are passing options object in mail composer constructor and attachment is on http server then it should look like:

const options = {
    attachments = [
      { // use URL as an attachment
        filename: 'xxx.jpg',
        path: 'http:something.com/xxx.jpg'
      }
    ]
}

Solution 4

var express = require('express');
var router = express(),
multer = require('multer'),
upload = multer(),
fs = require('fs'),
path = require('path');
nodemailer = require('nodemailer'),

directory = path.dirname("");
var parent = path.resolve(directory, '..');
// your path to store the files
var uploaddir = parent + (path.sep) + 'emailprj' + (path.sep) + 'public' + (path.sep) + 'images' + (path.sep);
/* GET home page. */
router.get('/', function(req, res) {
res.render('index.ejs', {
    title: 'Express'
});
});

router.post('/sendemail', upload.any(), function(req, res) {

var file = req.files;
console.log(file[0].originalname)
fs.writeFile(uploaddir + file[0].originalname, file[0].buffer,     function(err) {
    //console.log("filewrited")
    //console.log(err)
})
var filepath = path.join(uploaddir, file[0].originalname);
console.log(filepath)
    //return false;
nodemailer.mail({
    from: "yourgmail.com",
    to: req.body.emailId, // list of receivers
    subject: req.body.subject + " ✔", // Subject line
    html: "<b>" + req.body.description + "</b>", // html body
    attachments: [{
        filename: file[0].originalname,
        streamSource: fs.createReadStream(filepath)
    }]
});
res.send("Email has been sent successfully");
})
module.exports = router;
Share:
65,821
DanialV
Author by

DanialV

Updated on October 16, 2020

Comments

  • DanialV
    DanialV over 3 years

    I have code that send email with nodemailer in nodejs but I want to attach file to an email but I can't find way to do that I search on net but I could't find something useful.Is there any way that I can attach files to with that or any resource that can help me to attach file with nodemailer?

    var nodemailer = require('nodemailer');
    var events = require('events');
    var check =1;
    var events = new events.EventEmitter();
    var smtpTransport = nodemailer.createTransport("SMTP",{
        service: "gmail",
        auth: {
            user: "[email protected]",
            pass: "pass"
        }
    });
    function inputmail(){
        ///////Email
        const from = 'example<[email protected]>';
        const to  = '[email protected]';
        const subject  = 'example';
        const text = 'example email';
        const html = '<b>example email</b>';
        var mailOption = {
            from: from,
            to:  to,
            subject: subject,
            text: text,
            html: html
        }
        return mailOption;
    }
    function send(){
            smtpTransport.sendMail(inputmail(),function(err,success){
            if(err){
                events.emit('error', err);
            }
            if(success){
                events.emit('success', success);
            }
        });
    }
    ///////////////////////////////////
    send();
    events.on("error", function(err){
        console.log("Mail not send");
        if(check<10)
            send();
        check++;
    });
    events.on("success", function(success){
        console.log("Mail send");
    });
    
  • Lonnie Best
    Lonnie Best about 9 years
    Thanks for showcasing all these different ways! The "file on disk as an attachment" method (you commented) worked for me.
  • Mistalis
    Mistalis about 7 years
    Explain your answer.
  • Luca
    Luca almost 7 years
    please dont provide code-only answers, explain OP why your code is helping his / her problem
  • Syed Ayesha Bebe
    Syed Ayesha Bebe over 6 years
    getting cannot property '0' of undefined.Because of this file[0].originalname.If I used for loop for this I am getting error.How can I solve??
  • Geek Guy
    Geek Guy over 5 years
    This one solved my problem when I didn't want to save files but send to user and then delete
  • Aaron Matthews
    Aaron Matthews over 2 years
    copy and pasted straight from the docs