Gmail Photo Downloader

This is a Google Apps Script I wrote that automatically downloads pictures embedded in a daily email I receive from my son's daycare to a Google Drive folder.

 1function saveLatestExternalImagesFromEmail() {
 2  var query = 'from:connect-notification@constoso.com';
 3  var threads = GmailApp.search(query, 0, 1);  // Get only the most recent thread
 4  
 5  if (threads.length === 0) {
 6    console.log("No new threads found.");
 7    return;
 8  }
 9
10  console.log("Processing the latest thread.");
11
12  var folderName = 'Daycare';
13  var folders = DriveApp.getFoldersByName(folderName);
14  var folder;
15  if (folders.hasNext()) {
16    folder = folders.next();
17  } else {
18    folder = DriveApp.createFolder(folderName);
19  }
20  
21  var messages = threads[0].getMessages();
22  for (var j = 0; j < messages.length; j++) {
23    var body = messages[j].getBody();
24    
25    // Extracting and formatting the date from the Gmail message
26    var date = messages[j].getDate();
27    var formattedDate = Utilities.formatDate(date, Session.getScriptTimeZone(), 'yyyy-MM-dd');
28    
29    // Using the HTML service to parse
30    var output = HtmlService.createHtmlOutput(body);
31    var imgs = output.getContent().match(/<img [^>]*src="[^"]*"[^>]*>/g) || [];
32    
33    imgs.forEach(function(imgTag, index) {
34      if (imgTag.includes('alt="Photo"')) {  // Check for the desired attribute
35        var match = imgTag.match(/src="([^"]*)"/);
36        if (match && match[1]) {
37          var imageUrl = match[1];
38          
39          Logger.log("Found Image URL: " + imageUrl);
40          try {
41            var blob = UrlFetchApp.fetch(imageUrl).getBlob();
42            blob.setName(formattedDate + "_Image_" + j + "_0_" + index + ".jpg");  // As it's the latest thread, we're considering the index as 0.
43            folder.createFile(blob);
44            Logger.log("Saved Image: " + imageUrl);
45          } catch (e) {
46            Logger.log("Error fetching " + imageUrl + ". Error: " + e.toString());
47          }
48        }
49      }
50    });
51  }
52}

Example Image tag

For context, here's how the image tag looks in the daycare email:

1<img alt="Photo" border="0" title="Photo" width="100%" src="https://ci3.googleusercontent.com/proxy/L1Bhkyu1CzMzbd_mVCr3YwEPxKZhmzyce3uAkFuwTq1Fco1msKzwi270_a4_gnUBGJCl_1Yx9ZL4E7I76YQXE_xqbKjepm0AGiPbcT4HxYatKGdluYUqZehMEly5Y_cLpQylyC_YWORwY-pOhXa28n0Vsztq_XxMTuuj1PlXLc_N8UiBnW1JfT5Ydm6VofcibFcZhDqzwfdof9XXRRL7AA585lrxnpMU_8xpXFcVY61syua5YzBGkU7XMDtheRVpbysYLzvf1jTeMg7V4NaBVhf-ac4fNqkfiKdYhcCZC_0oNY-i_rvZmqUboioMK-yJcQKjmwVmUgNnLbfeTwNXbOE=s0-d-e1-ft#https://private.kinderlime.com/profile_pics/files/2f791232-d5f1-44c3-ab14-437643988c23/profilepic_1997707fb0462088434fe6e1b5c79a7f03d85ae0fe669997a2ca0dd912bb85d841/main/img_cropped7753123271202479858.jpg_1694105215459_photo.jpg?1694109217" class="CToWUd a6T" data-bit="iit" tabindex="0">

The script specifically looks for image tags with alt="Photo" to ensure we're only downloading relevant images.