解析来自 Sendgrid 的入站电子邮件

Parsing inbound emails from Sendgrid

我正在尝试使用 Meteor、Picker 和 Body-Parser 解析来自 Sendgrid Inbound Webhook 的传入电子邮件。我收到了电子邮件,但是当我记录请求正文时,我得到了一个空对象。我在这里错过了什么??

var bodyParser = require('body-parser');;

Picker.middleware( bodyParser.json() );

Picker.route('/incoming/', function(params, req, res, next) {
    console.log("Body: " + JSON.stringify(req.body));
}

听起来来自 SendGrid 的传入内容没有 application/json 内容类型,因此 bodyParser.json() 无法正确解析它。也尝试添加 bodyParser.urlencoded() 调用,以尝试解析 application/x-www-form-urlencoded 内容类型,看看是否有帮助。所以像:

var bodyParser = require('body-parser');

Picker.middleware(bodyParser.json());
Picker.middleware(bodyParser.urlencoded({ extended: false }));

Picker.route('/incoming/', function(params, req, res, next) {
  console.log("Body: " + JSON.stringify(req.body));
}

问题与 multipart/form-data 的内容类型有关。让它像这样工作:

var multiparty = require('multiparty');
var bodyParser = Npm.require('body-parser');

Picker.middleware(bodyParser.urlencoded({ extended: true }));
Picker.middleware(bodyParser.json());

Picker.route('/incoming/', function(params, req, res, next) {
  var form = new multiparty.Form();
  form.parse(req, function(err, fields, files) {
    console.log("Heureka: " + JSON.stringify(fields) + JSON.stringify(files));
    res.writeHead(200, {'content-type': 'text/plain'});
    res.write('received upload:\n\n');
    res.end("thanks");
  });
});

您也可以使用 multer 执行此操作。这是快速服务器版本:

const express = require(“express”);
const app = express();
var multer = require(“multer”);
var upload = multer();
app.post(“/”, upload.none(), function (req, res) {
  console.log(req.body);
});

我知道这个问题已经得到解答,但我有一个使用 expressmulter 的替代解决方案。我创建了一个存储库 express-sendgrid-inbound-parse 来帮助您入门。

我建议不选中 POST 原始的完整 MIME 消息,因为您可以访问更多电子邮件数据。

console.log('dkim: ', body.dkim)
console.log('to: ', body.to)
console.log('cc: ', body.cc)
console.log('from: ', body.from)
console.log('subject: ', body.subject)
console.log('sender_ip: ', body.sender_ip)
console.log('spam_report: ', body.spam_report)
console.log('envelope: ', body.envelope)
console.log('charsets: ', body.charsets)
console.log('SPF: ', body.SPF)
console.log('spam_score: ', body.spam_score)

if (rawFullMimeMessageChecked) {
    console.log('email: ', body.email)
} else {
    console.log('headers: ', body.headers)
    console.log('html: ', body.html)
    console.log('text: ', body.text)
    console.log('attachments: ', body.attachments)
    console.log('attachment-info: ', body['attachment-info'])
    console.log('content-ids: ', body['content-ids'])
}