sdepold
sdepold

Reputation: 6241

Sending mails with attachment via NodeJS

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

Upvotes: 28

Views: 58234

Answers (13)

Manuel Spigolon
Manuel Spigolon

Reputation: 12930

The answer is not updated with the last version of [email protected]

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 protected]',
    pass: 'HelloWorld'
  }
})


fs.readFile(path.join(__dirname, 'test22.csv'), function (err, data) {
  transport.sendMail({
    from: '[email protected]',
    to: '[email protected]',
    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 })
  })
})

Upvotes: 0

bpierre
bpierre

Reputation: 11467

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)

Upvotes: 3

Ishwar Rimal
Ishwar Rimal

Reputation: 1101

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

Upvotes: 0

Luis Sanchez
Luis Sanchez

Reputation: 17

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!'
               }   
             ]

Upvotes: 0

David
David

Reputation: 3441

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.

Upvotes: 1

Philippe
Philippe

Reputation: 1179

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: '[email protected]', 
    pass: 'xxxxxx'
};

Then read a file and send an email :

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

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

    }
});

Upvotes: 60

Ari Porad
Ari Porad

Reputation: 2922

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

Upvotes: 0

Krunal Goswami
Krunal Goswami

Reputation: 65

use mailer package it is very flexible and easy.

Upvotes: 1

StewartJarod
StewartJarod

Reputation: 64

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

Upvotes: 0

omolina
omolina

Reputation: 121

Try with nodemailer, for example try this:

  var nodemailer = require('nodemailer');
  nodemailer.SMTP = {
     host: 'mail.yourmail.com',
     port: 25,
     use_authentication: true,
     user: '[email protected]',
     pass: 'somepasswd'
   };

  var message = {   
        sender: "[email protected]",    
        to:'[email protected]',   
        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));       
    });

Upvotes: 6

chilts
chilts

Reputation: 451

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.

Upvotes: 1

kilianc
kilianc

Reputation: 7816

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

Upvotes: 3

Anatoliy
Anatoliy

Reputation: 30103

You may use nodejs-phpmailer

Upvotes: 1

Related Questions