Search for emails containg a specific URL using Gmail API

Viewed 347

I'm looking for all emails in Gmail containing a specific URL like:

http://www.example.com/page1/?utm_source=foo1234&utm_medium=bar

This is not accessible via the Gmail web interface (see the search syntax here): I tried to search the whole URL, the same text with quotes, or only parts of the URL like foo1234, utm_source=foo1234, all these queries return no result.

You can reproduce this by sending an email to yourself containing this URL (with a displayed text other than the URL itself, you can customize this with CTRL+K, "Edit link"), here is the result:

enter image description here

Note that if the displayed text is the URL itself, then there is a search match, but here I'm speaking about cases where the displayed text is different to the URL. See note (*) below.

 

Question: is a deeper search available from Gmail API (for example in Python) / Google Apps Script with Javascript, allowing to find messages containing a specific URL?

If so, how would you search for all emails containing such an URL?

I tried with the Gmail Python API:

service = build('gmail', 'v1', credentials=creds)
r1 = service.users().messages().list(userId="me", q="utm_source=foo1234").execute()
r2 = service.users().messages().list(userId="me", q="http://www.example.com/page1/?utm_source=foo1234&utm_medium=bar").execute()

with no success. Is there a way to perform a deeper search?


Note (*): Here is such an example:

enter image description here

2 Answers

This worked for me:

function searchForUrls() {
  const ts = GmailApp.search('http');
  let html = "";
  ts.forEach((t,i) => {
    t.getMessages().forEach(m => {
      html += `<br>from: ${m.getFrom()} to: ${m.getTo()} msg: ${m.getPlainBody()}`;
    });
  }); 
  SpreadsheetApp.getUi().showModelessDialog(HtmlService.createHtmlOutput("<textarea>" + html + "</textarea>"),'String Search');
}

There is no inbuilt search function, you'll need to loop through all your messages and their bodies

In Apps Script you can do it as following:

function findThatLink() {
  GmailApp.getInboxThreads().forEach(function(thread){
    var messages = thread.getMessages()
    messages.forEach(function(message){      
      if(message.getPlainBody().indexOf("http://www.example.com/page1/?utm_source=foo1234&utm_medium=bar"))
      {
        console.log("Success! The message id is " + message.getId()) 
      }
    }) 
  })
}

Note that instead of searching within the plainBody, you can also find your link with message.getBody(), however in the latter case your link will be url-encoded, so

http://www.example.com/page1/?utm_source=foo1234&amp;utm_medium=bar

instead of

http://www.example.com/page1/?utm_source=foo1234&utm_medium=bar

Related