Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save mrklein/3852307 to your computer and use it in GitHub Desktop.
Save mrklein/3852307 to your computer and use it in GitHub Desktop.
Google Apps Script quick hack to extract inline images from Gmail
function fetchInlineImage() {
var results = GmailApp.search("Subject: Inline Image Test");
for(var i in results) {
var thread = results[i];
messages = thread.getMessages();
for(var j in messages) {
var msg = messages[j];
var pattern = /<img.*src="([^"]*)"[^>]*>/;
var matches = pattern.exec(msg.getBody());
if(matches) {
var url = matches[1];
var urlPattern = /^https*\:\/\/.*$/;
// If this matches, that means this was copied and pasted from a browser and it's a
// standard URL that we can urlFetch
if(urlPattern.exec(url)) {
// NO OP!
} else {
// Else this means the user copied and pasted from an OS clipboard and the image
// exists on Google's servers. The image can only be retrieved when logged in. Fortunately,
// if we use URLFetchApp, this will act as a logged in user and be able to URLFetch the image.
// We'll need to prepend a Gmail URL (subject to change)
url = "https://mail.google.com/mail/u/0/" + url;
}
// TODO - there is one more case that we're not covering - embedded images that newsletters use
Logger.log("Fetching image from URL: " + url);
var response = UrlFetchApp.fetch(url);
Logger.log("Response status: " + Utilities.jsonStringify(response.getHeaders()));
var blob = response.getBlob();
Logger.log("Response blob: " + blob.getBytes().length);
}
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment