首页 > 解决方案 > 从带有附件的 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
    }
  }
*/

标签: node.jsemailgmailgmail-apiinbox

解决方案


推荐阅读