详细了解 ChrisR 在 cmets 中所说的内容,我能够认识到使用 node-mailer 我可以指定一个字符串作为要作为附件传递的内容。在这种情况下,我只需将我的数据格式化为csv 字符串。通过这样做,我可以使用.csv 扩展名设置我的文件名并传入数据字符串。这使我可以使用node-mailer 发送带有csv 附件的电子邮件。在papaparse 包的帮助下,我也能做到这一点。下面列出了代码,以防万一有人需要做类似的事情。
我的文件.js
...code above
// this would be called onClick on <button> element
TestEmail(){
// this would be the data you want to send as attachment
let temp = [
{
"Column 1": "1-1",
"Column 2": "1-2",
"Column 3": "1-3",
"Column 4": "1-4"
},
{
"Column 1": "2-1",
"Column 2": "2-2",
"Column 3": "2-3",
"Column 4": "2-4"
},
{
"Column 1": "3-1",
"Column 2": "3-2",
"Column 3": "3-3",
"Column 4": "3-4"
},
{
"Column 1": 4,
"Column 2": 5,
"Column 3": 6,
"Column 4": 7
}
]
let to = MYEMAIL;
let text =
`<div width="100%",style="text-align:left;">` +
`<h1 style="text-align:center;">Testing CSV</h1>` +
`</div >`;
let data = Papa.unparse(temp);
$.get("/sendRaw", { to: to, subject: 'Testing CSV', text: text, data: data }, function (data) { });
}
server.js
... code above
app.get('/sendRaw', (request, response) => {
var mailOptions = {
to: request.query.to,
bcc: request.query.bcc,
subject: request.query.subject,
text: request.query.text,
attachment: request.query.data
}
//console.log(mailOptions); Read up on NodeMailer for details.
smtpTransport.sendMail({ //email options
from: MYEMAIL
to: mailOptions.to,
bcc: MYEMAIL, // sending to itself
subject: mailOptions.subject, // subject
html: mailOptions.text, // body
attachments: [
{
filename: 'test.csv',
content: mailOptions.attachment,
}
]
}, function (error, response) { //callback
if (error) {
console.log(error);
} else {
console.log("Message sent");
//console.log("Amount of people getting this email: " + response.accepted.length);
}
smtpTransport.close(); // shut down the connection pool, no more messages. Comment this line out to continue sending emails.
});
})