Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save goteamtim/5426106 to your computer and use it in GitHub Desktop.

Select an option

Save goteamtim/5426106 to your computer and use it in GitHub Desktop.

Revisions

  1. @invalid-email-address Anonymous created this gist Aug 23, 2012.
    39 changes: 39 additions & 0 deletions apps_script_extract_inline_images_from_gmail.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,39 @@

    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);
    }
    }
    }
    };