27

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

sdepold
  • 6,171
  • 2
  • 41
  • 47

13 Answers13

59

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
        }

    }
});
Philippe
  • 1,169
  • 12
  • 14
  • 1
    Missing a '})' in the last line. I can't edit directly because it's less than 6 characters... – Panickos Neophytou Jun 20 '15 at 22:12
  • There is a type for attachments properties. "contents" is incorrect. should be "content". – Dmytro Mykhailov Jan 19 '16 at 17:11
  • Does this code snippet handle binary files or only text? – David Jan 27 '16 at 19:43
  • Older versions of nodemailer user "contents". Be sure to check what version you're using and compare with the documentation for nodemailer at http://nodemailer.com – ttemple Jul 25 '16 at 17:00
  • Anyway to send db file. I am using sqlite deployed on Heroku and on every deployment, the app get formatted. I have database.db file in my directory and want to send it using email. Coz for such I need to implement cronjob. Any help would be appreciated – Eklavya Chandra Nov 24 '21 at 07:13
6

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));       
    });
omolina
  • 121
  • 2
  • 3
3

Have you tried Nodemailer?

Nodemailer supports

  • Unicode to use any characters
  • HTML contents as well as plain text alternative
  • Attachments
  • Embedded images in HTML
  • SSL (but not STARTTLS)
bpierre
  • 10,957
  • 2
  • 26
  • 27
3

Personally i use Amazon SES rest API or Sendgrid rest API which is the most consistent way to do it.

If you need a low level approach use https://github.com/Marak/node_mailer and set up your own smtp server (or one you have access too)

http://blog.nodejitsu.com/sending-emails-in-node

kilianc
  • 7,397
  • 3
  • 26
  • 37
1

You can also use AwsSum's Amazon SES library:

In there, there is an operation called SendEmail and SendRawEmail, the latter of which can send attachments via the service.

chilts
  • 451
  • 3
  • 12
1

use mailer package it is very flexible and easy.

1

Another alternative library to try is emailjs.

I gave some of the suggestions here a try myself but running code complained that send_mail() and sendMail() is undefined (even though I simply copy & pasted code with minor tweaks). I'm using node 0.12.4 and npm 2.10.1. I had no issues with emailjs, that just worked off the shelf for me. And it has nice wrapper around attachments, so you can attach it various ways to your liking and easily, compared to the nodemailer examples here.

David
  • 3,223
  • 3
  • 29
  • 41
1

You may use nodejs-phpmailer

Anatoliy
  • 29,485
  • 5
  • 46
  • 45
0

Nodemailer for any nodejs mail needs. It's just the best at the moment :D

StewartJarod
  • 64
  • 1
  • 5
0

I haven't used it but nodemailer(npm install nodemailer) looks like what you want.

Eran
  • 387,369
  • 54
  • 702
  • 768
Ari Porad
  • 2,834
  • 3
  • 33
  • 51
0

Send With express-mailer (https://www.npmjs.com/package/express-mailer)

Send PDF -->

var pdf="data:application/pdf;base64,JVBERi0xLjM..etc"

attachments: [  {  filename: 'archive.pdf',
                  contents: new Buffer(pdf.replace(/^data:application\/(pdf);base64,/,''), 'base64')
                 }   
             ]

Send Image -->

var img = 'data:image/jpeg;base64,/9j/4AAQ...etc'
attachments: [  
             {  
               filename: 'myImage.jpg',
               contents: new Buffer(img.replace(/^data:image\/(png|gif|jpeg);base64,/,''), 'base64')
               }   
             ]

Send txt -->

attachments: [  
             {  
               filename: 'Hello.txt',
               contents: 'hello world!'
               }   
             ]
  • Can you also provide a minimal example code. Like this the answer is not very helpful since I have no idea where `attachments` should be placed. – select May 24 '17 at 14:40
0

you can use official api of google for this. They have provided package for node for this purpose. google official api

Ive attached part of my code that did the attachment thing for me

function makeBody(subject, message) {
var boundary = "__myapp__";
var nl = "\n";
var attach = new Buffer(fs.readFileSync(__dirname + "/../"+fileName)) .toString("base64");
// console.dir(attach);
var str = [

        "MIME-Version: 1.0",
        "Content-Transfer-Encoding: 7bit",
        "to: " + receiverId,
        "subject: " + subject,
        "Content-Type: multipart/alternate; boundary=" + boundary + nl,
        "--" + boundary,
        "Content-Type: text/plain; charset=UTF-8",
        "Content-Transfer-Encoding: 7bit" + nl,
        message+ nl,
        "--" + boundary,
        "--" + boundary,
        "Content-Type: Application/pdf; name=myPdf.pdf",
        'Content-Disposition: attachment; filename=myPdf.pdf',
        "Content-Transfer-Encoding: base64" + nl,
        attach,
        "--" + boundary + "--"

    ].join("\n");

    var encodedMail = new Buffer(str).toString("base64").replace(/\+/g, '-').replace(/\//g, '_');
    return encodedMail;
}

P.S thanks to himanshu for his intense research on this

Community
  • 1
  • 1
Ishwar Rimal
  • 1,071
  • 11
  • 19
0

The answer is not updated with the last version of nodemailer@6.x

Here an updated example:

const fs = require('fs')
const path = require('path')

const nodemailer = require('nodemailer')
const transport = nodemailer.createTransport({
  host: 'smtp.libero.it',
  port: 465,
  secure: true,
  auth: {
    user: 'email@libero.it',
    pass: 'HelloWorld'
  }
})


fs.readFile(path.join(__dirname, 'test22.csv'), function (err, data) {
  transport.sendMail({
    from: 'email_from@libero.it',
    to: 'email_to@libero.it',
    subject: 'Attachment',
    text: 'mail content...', // or body: field
    attachments: [{ filename: 'attachment.txt', content: data }]
  }, function (err, success) {    
    if (err) {
      // Handle error
      console.log(err)
      return
    }
    console.log({ success })
  })
})
Manuel Spigolon
  • 11,003
  • 5
  • 50
  • 73