提取未读电子邮件(以纯文本格式)并存储在Google文档中

时间:2017-01-12 10:51:40

标签: email google-apps-script gmail

问题:每天我们收到十几封邮件。我们需要定期打印所有这些。 Google Apps脚本是否可以只读取未读邮件并将其存储在Google文档中?没有HTML,我只需要以下格式的纯文本。

  

来自: S. Banerjee 日期: 1月3日   2017 02:40 主题:回复:新年快乐:“Br.Sayan”   

     

...... ......消息...... ......

我正在寻找解决方案,但只是设法得到类似以下here的内容。现在我们需要将未读邮件的msgID传递给函数。其余的格式化可以在以后逐个零碎的基础上解决。

function saveGmail(msgID) {

  // Based on Drive Scoop
  // Available at https://github.com/google/gfw-deployments

  var message = GmailApp.getMessageById(msgID);

  // Grab the message's headers.
  var from = message.getFrom();
  var subject = message.getSubject();
  var to = message.getTo();
  var cc = message.getCc();
  var date = message.getDate();
  var body = message.getBody();

  // Begin creating a doc.
  var document = DocumentApp.create(subject);  
  var document_title = document.appendParagraph(subject);  
  document_title.setHeading(DocumentApp.ParagraphHeading.HEADING1);

  var style = {};
  style[DocumentApp.Attribute.HORIZONTAL_ALIGNMENT] = (DocumentApp.HorizontalAlignment.CENTER);
  document_title.setAttributes(style);

  var headers_heading = (document.appendParagraph("Gmail Message Headers"));
  headers_heading.setHeading(DocumentApp.ParagraphHeading.HEADING2);

  AddGmailHeaderToDoc(document, "From", from);
  AddGmailHeaderToDoc(document, "To", to);
  AddGmailHeaderToDoc(document, "Cc", cc);
  AddGmailHeaderToDoc(document, "Date", date);
  AddGmailHeaderToDoc(document, "Subject", subject);

  var body_heading = (
    document.appendParagraph("Body (without Markup)"));
  body_heading.setHeading(DocumentApp.ParagraphHeading.HEADING2);

  var sanitized_body = body.replace(/<\/div>/, "\r\r");
  sanitized_body = sanitized_body.replace(/<br.*?>/g, "\r");
  sanitized_body = sanitized_body.replace(/<\/p>/g, "\r\r");
  sanitized_body = sanitized_body.replace(/<.*?>/g, "");
  sanitized_body = sanitized_body.replace(/'/g, "'");
  sanitized_body = sanitized_body.replace(/"/g, '"');
  sanitized_body = sanitized_body.replace(/&/g, "&");
  sanitized_body = sanitized_body.replace(/\r\r\r/g, "\r\r");

  var paragraph = document.appendParagraph(sanitized_body);

  document.saveAndClose();

  return document.getUrl();

}

function AddGmailHeaderToDoc(document, header_name, header_value) {
  if (header_value === "") return;
  var paragraph = document.appendParagraph("");
  paragraph.setIndentStart(72.0);
  paragraph.setIndentFirstLine(36.0);
  paragraph.setSpacingBefore(0.0);
  paragraph.setSpacingAfter(0.0);    
  var name = paragraph.appendText(header_name + ": ");
  name.setBold(false);
  var value = paragraph.appendText(header_value);
  value.setBold(true);
}

非常感谢您的帮助!!

1 个答案:

答案 0 :(得分:2)

更简单的方法可能是使用'is:unread'搜索

  var threads = GmailApp.search('is:unread');
  var messages = threads[0].getMessages(); 
  for (var i = 0; i < messages.length; i++) {
    Logger.log(messages[i].getId());
  }

这将记录Id,但您也可以返回它们。还要注意线程和消息是不同的。上面将获得第一个未读线程和该线程中的所有消息(即使消息被读取)。