如何解决将无请求的Node.js中的REST请求主体中的多部分/表单数据文件转换为电子邮件附件格式
我想创建一个REST API,允许请求者对包含文件的PATCH多部分/表单数据进行PATCH。服务器提取文件并通过SMTP作为电子邮件附件发送。我有以下代码:
const nodemailer = require('nodemailer');
const smtpTransport = require('nodemailer-smtp-transport');
const username = 'email account'
const password = 'email password'
const smtpHost = 'mailhog'
const smtpPort = 1025
module.exports.endpoint = (event,context,callback) => {
const mailOptions = {
from: 'wat@address.com',to: 'inbox@address.com',subject: 'Here is a file',text: 'Please see attached'
};
const transporter = nodemailer.createTransport(smtpTransport({
host: smtpHost,port: smtpPort,secure: false,auth: {
user: username,pass: password
}
}));
transporter.sendMail(mailOptions,function (error,info) {
if (error) {
const response = {
statusCode: 500,body: JSON.stringify({
error: error.message,}),};
callback(null,response);
}
const response = {
statusCode: 202,headers: {
"Access-Control-Allow-Origin": "*"
},body: "Accepted",};
callback(null,response);
});
}
是否有很好的方法?
解决方法
使用aws-lambda-multipart-parser,我可以很简单地做到这一点:
use strict';
const multipart = require('aws-lambda-multipart-parser');
const nodemailer = require('nodemailer');
const smtpTransport = require('nodemailer-smtp-transport');
const username = 'email account'
const password = 'email password'
const smtpHost = 'mailhog'
const smtpPort = 1025
module.exports.endpoint = (event,context,callback) => {
const file = multipart.parse(event,true).file;
const mailOptions = {
from: 'wat@address.com',to: 'inbox@address.com',subject: 'Here is a file',text: 'Please see attached',attachments: [
{
filename: file.filename,content: file.content,contentType: 'image/png'
}
]
};
const transporter = nodemailer.createTransport(smtpTransport({
host: smtpHost,port: smtpPort,secure: false,auth: {
user: username,pass: password
}
}));
transporter.sendMail(mailOptions,function (error,info) {
if (error) {
const response = {
statusCode: 500,body: JSON.stringify({
error: error.message,}),};
callback(null,response);
}
const response = {
statusCode: 202,headers: {
"Access-Control-Allow-Origin": "*"
},body: "Accepted",};
callback(null,response);
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。