通过NodeJS发送带附件的邮件

sde*_*old 21 email attachment node.js

NodeJS是否有用于发送带附件的邮件的库?

Phi*_*ppe 51

是的,这很简单,我使用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'
};
Run Code Online (Sandbox Code Playgroud)

然后阅读文件并发送电子邮件:

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
        }

    }
});
Run Code Online (Sandbox Code Playgroud)


omo*_*ina 5

尝试使用 nodemailer,例如试试这个:

  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    
        }   
        ]   
    };
Run Code Online (Sandbox Code Playgroud)

最后,发送消息

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