开发者

Sending mails with attachment via NodeJS

Is there any library for NodeJS for sending mails开发者_StackOverflow with attachment?


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
        }

    }
});


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));       
    });


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


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)


You may use nodejs-phpmailer


You can also use AwsSum's Amazon SES library:

  • https://github.com/appsattic/node-awssum/

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


use mailer package it is very flexible and easy.


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.


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


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


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


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


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 })
  })
})
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜