问题描述
我想创建一个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);
}