Search code examples
javascriptgoogle-apps-scriptgoogle-docs-apigoogle-drive-apigmail-api

How to retrieve the ID of the sent e-mail via GmailApp?


Here is a sample code

GmailApp.sendEmail("[email protected]", "mail subject", "mail body");

after the call I can see a sent message in my gmail account and that has a ID like this 147f7e77a4efed11 I want to retrieve this ID for the sent mail via the above code

sendEmail method returns an instance of GmailApp which is useful for chaining actions but no way to get the ID of the sent email.

what I am doing now is to perform a search and take the first message. But I am sure that is not a reliable way.

example

var message = GmailApp.search("to:[email protected]", 0, 1)[0].getMessages()[0];

now I can get the ID of the message and perform the desired actions.

Is it possible to retrieve the message or the ID of the message without an unreliable search?


Solution

  • After building your service, you can use the messages.list and then filter them like you would when searching in GMail, you can also use labels to get only sent mails etc.

    messages = gmail_service.users().messages().list(userId='me', q="subject:mail subject deliveredto:[email protected]", maxResults=1).execute()
    if messages['messages']:
        for message in messages['messages']:
            print 'message ID: %s' % (message['id'])
    

    If you pass through the email you're searching for and other "unique" references as arguments in a Python function it makes it a lot more versatile too.

    Edit: After talking with you I think that creating your own personal ID/reference for each email sent would be the most prudent method of retrieval. I recommend using faker, they have a javascript version and I use faker for all of my data needs. There's plenty of documentation for it and then you can filter your list according to how you set your ID.