30

我有在nodejs中使用nodemailer发送电子邮件的代码,将文件附加到电子邮件中,但我找不到这样做的方法,我在网上搜索但找不到有用的东西。有什么方法可以附加文件到那个或任何可以帮助我用nodemailer附加文件的资源?

var nodemailer = require('nodemailer');
var events = require('events');
var check =1;
var events = new events.EventEmitter();
var smtpTransport = nodemailer.createTransport("SMTP",{
    service: "gmail",
    auth: {
        user: "example@gmail.com",
        pass: "pass"
    }
});
function inputmail(){
    ///////Email
    const from = 'example<example@gmail.com>';
    const to  = 'example@yahoo.com';
    const subject  = 'example';
    const text = 'example email';
    const html = '<b>example email</b>';
    var mailOption = {
        from: from,
        to:  to,
        subject: subject,
        text: text,
        html: html
    }
    return mailOption;
}
function send(){
        smtpTransport.sendMail(inputmail(),function(err,success){
        if(err){
            events.emit('error', err);
        }
        if(success){
            events.emit('success', success);
        }
    });
}
///////////////////////////////////
send();
events.on("error", function(err){
    console.log("Mail not send");
    if(check<10)
        send();
    check++;
});
events.on("success", function(success){
    console.log("Mail send");
});
4

7 回答 7

76

在 var mailOption 中包含关键附件,如下所示:

var mailOptions = {
...
attachments: [
    {   // utf-8 string as an attachment
        filename: 'text1.txt',
        content: 'hello world!'
    },
    {   // binary buffer as an attachment
        filename: 'text2.txt',
        content: new Buffer('hello world!','utf-8')
    },
    {   // file on disk as an attachment
        filename: 'text3.txt',
        path: '/path/to/file.txt' // stream this file
    },
    {   // filename and content type is derived from path
        path: '/path/to/file.txt'
    },
    {   // stream as an attachment
        filename: 'text4.txt',
        content: fs.createReadStream('file.txt')
    },
    {   // define custom content type for the attachment
        filename: 'text.bin',
        content: 'hello world!',
        contentType: 'text/plain'
    },
    {   // use URL as an attachment
        filename: 'license.txt',
        path: 'https://raw.github.com/andris9/Nodemailer/master/LICENSE'
    },
    {   // encoded string as an attachment
        filename: 'text1.txt',
        content: 'aGVsbG8gd29ybGQh',
        encoding: 'base64'
    },
    {   // data uri as an attachment
        path: 'data:text/plain;base64,aGVsbG8gd29ybGQ='
    }
]

}

选择适合您需要的选项。

链接:Nodemailer 存储库 GitHub

祝你好运!!

于 2014-10-09T19:48:31.643 回答
4

您的代码几乎是正确的,只需添加“附件”属性即可在邮件中附加文件,

您的邮件选项:

var mailOption = {
        from: from,
        to:  to,
        subject: subject,
        text: text,
        html: html
}

只需添加附件,例如

var mailOption = {
        from: from,
        to:  to,
        subject: subject,
        text: text,
        html: html,
        attachments: [{
            filename: change with filename,
            path: change with file path
        }]
}

附件还提供了一些其他方式来附加文件以获取更多信息,请在此处查看 nodemailer 社区的文档

于 2019-02-05T13:00:32.027 回答
3

如果您在邮件编写器构造函数中传递选项对象并且附件在 http 服务器上,那么它应该如下所示:

const options = {
    attachments = [
      { // use URL as an attachment
        filename: 'xxx.jpg',
        path: 'http:something.com/xxx.jpg'
      }
    ]
}
于 2018-08-29T19:02:01.640 回答
1
var express = require('express');
var router = express(),
multer = require('multer'),
upload = multer(),
fs = require('fs'),
path = require('path');
nodemailer = require('nodemailer'),

directory = path.dirname("");
var parent = path.resolve(directory, '..');
// your path to store the files
var uploaddir = parent + (path.sep) + 'emailprj' + (path.sep) + 'public' + (path.sep) + 'images' + (path.sep);
/* GET home page. */
router.get('/', function(req, res) {
res.render('index.ejs', {
    title: 'Express'
});
});

router.post('/sendemail', upload.any(), function(req, res) {

var file = req.files;
console.log(file[0].originalname)
fs.writeFile(uploaddir + file[0].originalname, file[0].buffer,     function(err) {
    //console.log("filewrited")
    //console.log(err)
})
var filepath = path.join(uploaddir, file[0].originalname);
console.log(filepath)
    //return false;
nodemailer.mail({
    from: "yourgmail.com",
    to: req.body.emailId, // list of receivers
    subject: req.body.subject + " ✔", // Subject line
    html: "<b>" + req.body.description + "</b>", // html body
    attachments: [{
        filename: file[0].originalname,
        streamSource: fs.createReadStream(filepath)
    }]
});
res.send("Email has been sent successfully");
})
module.exports = router;
于 2017-03-01T12:17:05.947 回答
0

看看这里。Nodemailer > 消息配置 > 附件

代码片段如下(pdfkit 获取流):

// in async func
pdf.end();
const stream = pdf;
const attachments = [{ filename: 'fromFile.pdf', path: './output.pdf', 
contentType: 'application/pdf' }, { filename: 'fromStream.pdf', content: stream, contentType: 'application/pdf' }];
await sendMail('"Sender" <sender@test.com>', 'reciver@test.com', 'Test Send Files', '<h1>Hello</h1>', attachments);

Streamcontent用不上streamSource这个之前一直困扰着我,分享给大家:)

于 2020-10-16T00:47:05.657 回答
0

另一种解决方案是使用 CDN 在线托管您的图像,并链接到您的 HTML 中的在线图像源,例如。<img src="list_image_url_here">.

(我在使用 nodemailer 版本 2.6.0 嵌入 nodemailer 的图像时遇到了问题,这就是我想出这个解决方法的原因。)

此解决方案的另一个好处是您不会向 nodemailer 发送附件,因此发送过程更加简化。

于 2016-09-20T15:39:43.080 回答
0
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
        }

    }
});
于 2017-08-09T08:43:16.560 回答