Gmail AppScript mailMessage.getFrom() to return email not name

喜夏-厌秋 提交于 2021-02-17 03:59:08

问题


Similar to: Getting only email address to display when using message.getFrom() in JavaMail but could not apply the solution.

Trying to use mailMessage.getFrom() on Google AppScript with Gmail.

Default script:

function loadAddOn(event) {
  var accessToken = event.messageMetadata.accessToken;
  var messageId = event.messageMetadata.messageId;
  GmailApp.setCurrentMessageAccessToken(accessToken);
  var mailMessage = GmailApp.getMessageById(messageId);
  var from = mailMessage.getFrom();

  var openDocButton = CardService.newTextButton()
  .setText("open docs")
  .setOpenLink(
    CardService.newOpenLink().setUrl("https://developers.google.com/gmail/add-ons/"));

  var card = CardService.newCardBuilder()
  .setHeader(CardService.newCardHeader().setTitle("My First Gmail Addon"))
  .addSection(CardService.newCardSection()
              .addWidget(CardService.newTextParagraph().setText("The email is from: " + from))
              .addWidget(openDocButton))
  .build();

  return [card];
}

var from = mailMessage.getFrom();

This returns the name of the sender, not the actual email address. Tried getFrom().getAddress() trying my luck with post mentioned above, but obviously it didn't work, with getFrom() returning a string.

Any Idea how to access an array of data or dictionary with metadata of sender so I can extract email, name etc. myself?


回答1:


This appears to be a bug!

It appears that when using the getFrom() method in a card, the name appears but not the email address as you described, which is counter to what is contained in the GmailMessage.getFrom() documentation.

I have taken the liberty of reporting this behaviour for you on Google's Issue Tracker:

  • GmailMessage.getFrom() not returning email address within CardService.

You can hit the ☆ next to the issue number in the top left of this page which lets Google know more people are encountering this and so it is more likely to be seen to faster.

Workaround:

In the mean time, as the getFrom() method still works within the Apps Script interface, you can obtain the email address from the return string of getFrom().

If you use Logger.log(mailMessage.getFrom()), you get a return in the log of the form:

Firstname Lastname <emailaddress@domain.com>

So, all you need to do is replace:

var from = mailMessage.getFrom();

with:

var from = mailMessage.getFrom().split("<")[1].split(">")[0];

I hope this is helpful to you!

References:

  • Google Apps Script - GmailMessage.getFrom()
  • Issue Tracker - GmailMessage.getFrom() not returning email address within CardService.


来源:https://stackoverflow.com/questions/59449863/gmail-appscript-mailmessage-getfrom-to-return-email-not-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!