我是javascript和node.js的新手,并尝试通过做一些有用的事情来学习它。所以,我想发送一封带有附件图片的电子邮件。通过发出HTTP GET请求从远程服务器检索图像,并通过nodemailer(SMTP)使用Gmail发送到电子邮件地址
By reading the docs and looking through examples,我设法发送了一封没有附件的电子邮件,但我无法弄清楚如何使用Streams发送它。我使用了以下代码,但它返回了错误,我无法修复自己并需要帮助:
var nodemailer = require('nodemailer');
var request = require('request');
var config = require('../config');
var mailer;
mailer = function (opts) {
var transporter = nodemailer.createTransport({
service: 'Gmail',
auth: {
user: config.GmailAuth.email,
pass: config.GmailAuth.password
}
});
var mailOptions = {
from: opts.from, // sender address
to: opts.to, // list of receivers
subject: opts.subject, // Subject line
html: opts.body, // html body
attachments: [
{
filename: 'screenshot.png',
content: request(opts.imageUrl) // <-- Error here
}
]
};
transporter.sendMail(mailOptions, function(error, info){
if (error) {
return console.log(error);
} else {
console.log('Message sent: ' + info.response);
}
});
}
mailer({
from: config.GmailAuth.email,
to: config.sendToAddress,
subject: 'TEST SUBJECT',
body: 'TEST MESSAGE BODY',
imageUrl: 'URL_to_an_image_for_HTTP_GET_request'
});
发生以下错误:
stream.js:74
throw er; // Unhandled stream error in pipe.
^
Error: write after end
at writeAfterEnd (_stream_writable.js:159:12)
at Encoder.Writable.write (_stream_writable.js:204:5)
at Encoder.Writable.end (_stream_writable.js:433:10)
at Request.<anonymous> (C:\Users\user\Desktop\graphite_monitor\node_modules\
buildmail\src\buildmail.js:573:35)
at Request.g (events.js:260:16)
at emitOne (events.js:82:20)
at Request.emit (events.js:169:7)
at Request.onRequestError (C:\Users\user\Desktop\graphite_monitor\node_modul
es\request\request.js:820:8)
at emitOne (events.js:77:13)
at ClientRequest.emit (events.js:169:7)
问题是什么,我该如何解决?
答案 0 :(得分:3)
尝试更改此内容:
attachments: [
{
filename: 'screenshot.png',
content: request(opts.imageUrl) // <-- Error here
}
]
为:
attachments: [
{
filename: "pin-marker.png",
path: "http://img.mapeando.net/map/pin-marker.png", // <-- should be path instead of content
cid: "pin-marker.png"
}
]
答案 1 :(得分:0)
我设法使用PassThrough Streams(here is somewhat similar question)使其工作,这是工作代码(在我的初始代码中需要添加更改):
var PassThrough = require('stream').PassThrough;
var nameOfAttachment = 'screenshot.png';
var imageUrlStream = new PassThrough();
request
.get({
proxy: 'http://YOUR_DOMAIN_NAME:3129', // if needed
url: opts.imageUrl
})
.on('error', function(err) {
// I should consider adding additional logic for handling errors here
console.log(err);
})
.pipe(imageUrlStream);
var mailOptions = {
from: opts.from, // sender address
to: opts.to, // list of receivers
subject: opts.subject, // Subject line
html: opts.body, // html body
attachments: [
{
filename: nameOfAttachment,
content: imageUrlStream
}
]
};
我希望它能帮助其他初学者