node.js - 从带有附件的 Gmail 中读取邮件 - Node.js
问题描述
我一直在努力阅读来自 Gmail API 的消息。
我可以使用 mail.Payload.Parts[0].Body.Data 获取每封邮件的正文,其中包含 base64 中的消息正文。
问题是当我检索的邮件有附件时,parts[0] MimeType 是“multipart/alternative”,并且它的正文只有空字段。
如果邮件有附件,如何获取邮件正文?代码 velow 适用于没有附件的邮件,但对于有附件的邮件则没有任何效果
请指教。谢谢!
function getRecentEmail(auth) {
const gmail = google.gmail({version: 'v1', auth});
// Only get the recent email - 'maxResults' parameter
gmail.users.messages.list({auth: auth, userId: 'me', maxResults: 13 ,}, function(err, response) {
if (err) {
console.log('The API returned an error: ' + err);
return;
}
// Get the message id which we will need to retreive tha actual message next.
var message_id = response['data']['messages'][0]['id'];
// Retreive the actual message using the message id
gmail.users.messages.get({auth: auth, userId: 'me', 'id': message_id}, function(err, response) {
if (err) {
console.log('The API returned an error: ' + err);
return;
}
// console.log(response['data']);
console.log('xxxxxxxxxxxxxxxxxxxxxxxxx');
console.log(data.payload.parts);
console.log(data.payload);
message_raw = response.data.payload.parts[0].body.data;
data = message_raw;
buff = new Buffer.from(data, 'base64');
text = buff.toString();
console.log(text);
});
});
}
/*Below is the console output.
The part [0].body returns null while part [1].body has the attachment. Cannot see the email message part anywhere. Below is the console output.
{
partId: '0',
mimeType: 'multipart/alternative',
filename: '',
headers: [ [Object] ],
body: { size: 0 },
parts: [ [Object], [Object] ]
},
{
partId: '1',
mimeType: 'image/jpeg',
filename: '3.JPG',
headers: [ [Object], [Object], [Object], [Object], [Object] ],
body: {
attachmentId: 'ANGjdJ80EeMqROfRj4fMz751dKoqD4OW1rW6qu483Fo2vZw1FG2YT7AOJcV
UsnO5cbeHoSWiftO5Z_OAtPghlftkLdpMTUFzGSYgcJ3fLR2nnNoMbvJxl-BCsFCPndRlL2G5-OUKmO0
mhO8knKAYtDrdAcaMb_9lbQcG379jtXIYQEpnKADEbLFy1i_ZAmyAg3prC-P0QNBQE-FTi4x26qRUeTM
hv8quTt9LMOhwnA',
size: 44199
}
}
*/
解决方案
推荐阅读
- amazon-web-services - 重新生成证书时 SSH 命令失败
- java - 在 Java 中切换和循环
- c# - 如何为 ASP.NET 生成的模型中的所有对象添加相同的方法以实现相同的目的?
- javascript - 单击按钮时如何仅添加音频类?
- php - SSL 导致 Wordpress 网站上的 3 次重定向
- android - 用字符串在正文上改造帖子请求
- php - php 脚本的输出如何成为包含脚本的 URL 的资源
- java - 指向外部文档的 Javadoc 链接不起作用
- python - 在 Python 中读取以 .rds 格式从 R 导出的“sf”空间数据集
- python - 使用 PySide2.QtSql.QSqlRelationalTableModel()