如何将邮件正文保存到 Google 文档

How to save text of a mail body to Google Docs

我正在 Google.Scripts 中编写一个小脚本来查找我的 Gmail 帐户中的特定邮件地址并将正文复制到 google.docs。它在查找电子邮件和阅读正文内容时似乎工作正常,正如我在执行痕迹中看到的那样。

它还会创建文档或打开它(如果不存在)。但是,当我检查文档时,它是空的。我在这里迷路了,因为在我看来我正在正确地使用文档方法。这是脚本的代码:

/**
 * Creates a Google Doc and copy the texts of mails in it.
 * Mails will be retrieved by sender. This script is intended
 * as a way to get information from newsletters in a single document
 */
function getMailsToDoc() {
  // Create a new Google Doc named 'MyMailsText'
  var doc = DocumentApp.create('MyMailsText');

  // Get the email address of the active user - that's you.
  var email = Session.getActiveUser().getEmail();

  var threads = GmailApp.search('from:NewsLetterMail', 0, 20);
  Logger.log("Messages unread in inbox: " + GmailApp.getInboxUnreadCount());
  var messages = threads[0].getMessages();
  var senderEmail = 'admin@newsletter.com';
  for (var i = 0; i < threads.length; i++) {
        messages = threads[i].getMessages()
        Logger.log(messages[0].getPlainBody());

        // Get all possible mails in the thread and copy their bodies to 
        for (var j = 0; j < messages.length; j++) {
          if(senderEmail == messages[j].getFrom()){
            Logger.log(messages[0].getFrom());
            doc.getBody().appendParagraph(messages[j].getPlainBody());
          }
        }
  }
  doc.saveAndClose();

}

这里是痕迹的例子:

[18-09-08 06:07:56:535 PDT] Iniciando ejecución
[18-09-08 06:07:57:592 PDT] DocumentApp.create([MyMailsText]) [1,051 segundos]
[18-09-08 06:07:57:593 PDT] Session.getActiveUser() [0 segundos]
[18-09-08 06:07:57:593 PDT] User.getEmail() [0 segundos]
[18-09-08 06:07:58:109 PDT] GmailApp.search([from:NewsLetterMail, 0, 20]) [0,514 segundos]
[18-09-08 06:07:58:212 PDT] GmailApp.getInboxUnreadCount() [0,102 segundos]
[18-09-08 06:07:58:213 PDT] Logger.log([Messages unread in inbox: 265, []]) [0 segundos]
[18-09-08 06:07:58:334 PDT] GmailThread.getMessages() [0,12 segundos]
[18-09-08 06:07:58:335 PDT] GmailThread.getMessages() [0 segundos]
[18-09-08 06:07:58:443 PDT] GmailMessage.getPlainBody() [0,107 segundos]
**[18-09-08 06:07:58:444 PDT] Logger.log([News and information related to different topics, blablablabla, []]...) [0 segundos]**
[18-09-08 06:07:58:444 PDT] GmailMessage.getFrom() [0 segundos]
[18-09-08 06:07:58:839 PDT] GmailThread.getMessages() [0,395 segundos]
[18-09-08 06:07:58:934 PDT] GmailMessage.getPlainBody() [0,094 segundos]
**[18-09-08 06:07:58:934 PDT] Logger.log([More interesting news from this interesting newsletter blablabla , []]...) [0 segundos]**

你能给我一些提示,告诉我我做错了什么,或者关于如何弄清楚 google 文档为何为空的任何建议吗?我将不胜感激任何帮助。非常感谢!

基于评论的解决方案

正如评论者 tehhowch 所指出的,if 条件始终为假。这是由于与 messages[j].getFrom().

进行比较时错误的 senderEmail 字符串引起的

按如下方式更改它使其工作:

var senderEmail = 'NewsLetterMail <admin@newsletter.com>';