Sending mails with attachment via NodeJS


Question

Is there any library for NodeJS for sending mails with attachment?

1
21
9/17/2018 2:56:13 PM

Accepted Answer

Yes, it is pretty simple, I use nodemailer: npm install nodemailer --save

var mailer = require('nodemailer');
mailer.SMTP = {
    host: 'host.com', 
    port:587,
    use_authentication: true, 
    user: 'you@example.com', 
    pass: 'xxxxxx'
};

Then read a file and send an email :

fs.readFile("./attachment.txt", function (err, data) {

    mailer.send_mail({       
        sender: 'sender@sender.com',
        to: 'dest@dest.com',
        subject: 'Attachment!',
        body: 'mail content...',
        attachments: [{'filename': 'attachment.txt', 'content': data}]
    }), function(err, success) {
        if (err) {
            // Handle error
        }

    }
});
49
1/19/2016 7:31:45 PM

Try with nodemailer, for example try this:

  var nodemailer = require('nodemailer');
  nodemailer.SMTP = {
     host: 'mail.yourmail.com',
     port: 25,
     use_authentication: true,
     user: 'info@youdomain.com',
     pass: 'somepasswd'
   };

  var message = {   
        sender: "sender@domain.com",    
        to:'somemail@somedomain.com',   
        subject: '',    
        html: '<h1>test</h1>',  
        attachments: [  
        {   
            filename: "somepicture.jpg",    
            contents: new Buffer(data, 'base64'),   
            cid: cid    
        }   
        ]   
    };

finally, send the message

    nodemailer.send_mail(message,   
      function(err) {   
        if (!err) { 
            console.log('Email send ...');
        } else console.log(sys.inspect(err));       
    });

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon