How to extract full body content of a Bounced back email?

这一生的挚爱 提交于 2019-12-03 21:00:36

I finally found the answer to my own question.

This has worked for me and will pretty much work for anyone on our planet.

function test()
{
  var BouncedEmails = GmailApp.search("label:test The following message was undeliverable ");

  for( var i=0;i<BouncedEmails.length;i++)
  {
    var threadId = BouncedEmails[i].getId();

    var id = Session.getEffectiveUser().getEmail();
    var body = Gmail.Users.Threads.get(id, threadId, {format : 'full'});

    var messages = body.messages;

    var payLoad = messages[0].payload.parts[2];

    var string = JSON.stringify(payLoad);
    Logger.log(string);
  }
}   

The solutions provided by @AmitAgarwal and @ShyamKansagra would also work for some cases, but which solution to use depends on what is your exact requirement.

Don't use Logger.log as it truncates the output after a certain number of lines. Log the output in a spreadsheet and you'll see that the full body is extracted with getPlainBody() or getBody().

I recently published a Google Script to get all bounced emails in Gmail and logs them to a Google sheet. It is open so can build upon that script.

I also tried using getBody(), getPlainBody() and getRawContent() methods on bounced back emails. I noticed that these methods didn't give entire body of the email i.e. the part with technical details was skipped entirely in the logs.

So, I used this following code(all credits to @Amit Agarwal), which I found in the link which Amit has shared in his answer and it gave me entire body of bounced back email.

Here is the code:

var t = "in:anywhere from:(mailer-daemon@google.com OR mailer-daemon@googlemail.com)";
GmailApp.search(t,0,500).forEach(function(t)
                                          {
                                            t.getMessages().forEach(function(r)
                                                                    {
                                                                      if(r.getFrom().indexOf("mailer-daemon")!==-1)
                                                                      {
                                                                        var i=r.getPlainBody();
                                                                        Logger.log(i);
                                                                      }
                                                                    }
                                                                    )
                                          }

)

It worked for me and gave the entire content in the logs itself. Hope this helps.

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