Sending mails with attachment via NodeJS
Asked Answered
A

13

27

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

Abelabelard answered 12/1, 2011 at 19:6 Comment(0)
S
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: '[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
        }

    }
});
Sociability answered 13/3, 2012 at 5:5 Comment(5)
Missing a '})' in the last line. I can't edit directly because it's less than 6 characters...Ransell
There is a type for attachments properties. "contents" is incorrect. should be "content".Uel
Does this code snippet handle binary files or only text?Swathe
Older versions of nodemailer user "contents". Be sure to check what version you're using and compare with the documentation for nodemailer at nodemailer.comWanderoo
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 appreciatedUndersurface
F
6

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));       
    });
Fca answered 31/7, 2012 at 14:38 Comment(2)
ReferenceError: data is not defined -- Am I missing a require?Phosphoric
i guess there is typo, its content not contentsTelfer
H
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)
Hairless answered 29/3, 2011 at 0:47 Comment(0)
H
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

Hemisphere answered 6/11, 2011 at 17:27 Comment(1)
Old answer, but how is an API more consistent than a local sendmail server...?Familiarize
S
1

You may use nodejs-phpmailer

Sohn answered 12/1, 2011 at 20:9 Comment(2)
he use node.js, why advice him to use a php solution ?Hostel
I think that uses node.js but is based on php, kind of slow and bad.. But I think does the job.Toil
M
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.

Milled answered 5/5, 2012 at 4:37 Comment(1)
Don't forget to fully disclose your affiliation with projects you recommend :)Knowhow
L
1

use mailer package it is very flexible and easy.

Leathern answered 13/12, 2012 at 13:29 Comment(0)
S
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.

Swathe answered 27/1, 2016 at 22:38 Comment(0)
P
0

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

Pavid answered 9/11, 2012 at 22:53 Comment(0)
F
0

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

Farra answered 25/12, 2012 at 16:37 Comment(0)
P
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!'
               }   
             ]
Poff answered 3/11, 2016 at 10:13 Comment(1)
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.Dkl
G
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

Guenon answered 15/4, 2017 at 7:23 Comment(0)
S
0

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 })
  })
})
Servomotor answered 9/2, 2020 at 14:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.