Skip to content

Instantly share code, notes, and snippets.

@dfkoz
Last active June 30, 2023 12:49
Show Gist options
  • Save dfkoz/5860786 to your computer and use it in GitHub Desktop.
Save dfkoz/5860786 to your computer and use it in GitHub Desktop.
The Honeymailer sends a random photo from Google Drive at a preset interval.
// HOW TO USE THIS SCRIPT:
// 0. Upload your photos to Google Drive.
// 1. Log into Google Drive, and click CREATE -> Script -> Blank Project.
// 2. Delete all of the default code, and paste this code into your project.
// 3. Customize the email parameters below to your liking (note that the quotes around each line are very important.)
// 4. Test the script by selecting Run -> sendRandomPic. You should receive an email with a random picture.
// 5. Click Resources -> Current Project's Triggers, and set up the email to run as often as you would like.
// Name of the folder that contains your photos.
// Leave blank to search your top-level folder.
var folderName = "";
var extensions = ["JPG", "JPEG", "PNG", "GIF"];
// Email parameters
var to = "you@domain.com" // Comma-separated list of email addresses.
var subject = "Honeymailer Daily" // Subject line.
var body = "<p>Your daily picture:</p>" + // Body of the email. Important that the.
"<p><img src='cid:imageBlob' style='width: 200px;' /></p>" +
"<p>Like this one? See it <a href='{picture-link}'>here</a>.</p>";
function sendRandomPic() {
// Scan each file to see if it matches any of our filters.
// Iterating over all files appears to be faster than searching [?]
var folder = DocsList.getFolder(folderName);
var results = [];
var flag = true;
var startIndex = 0;
while (flag) {
var files = folder.getFiles(startIndex, 250);
for (f in files) {
var file = files[f];
var ext = file.getName().split('.').pop();
if (extensions.indexOf(ext) > -1) results.push(file);
}
files.length > 0 ? startIndex += files.length : flag = false;
}
// Finally, select a random file.
if (results.length == 0) {
file = null;
} else {
file = results[Math.floor(Math.random() * results.length + 1)];
}
if (file) {
// Send an email containing the picture.
MailApp.sendEmail({
to: to,
subject: subject,
htmlBody: body.replace("{picture-link}",file.getUrl()),
inlineImages: { imageBlob: file.getThumbnail() },
});
}
}
@SpinyN0rman
Copy link

Thanks for this, I used much of it as part of a chain that updates my Android phone wallpaper with a different drive image each day (details here if you're interested: https://northrop.tech/daily-random-google-drive-image-to-phone-wallpaper/)

Anyhow, I'm sure you got the same email as me from Google stating that the DocsList service was being terminated in April so I've updated the relevant section with the new DriveApp code. It's actually much shorter now. Instead of lines 26-42 use this:

var files = DriveApp.getFolderById(folderID).getFiles();
var results = [];

while ( files.hasNext() ){
  results.push(files.next().getId());
}

The only other tweak is that you need to use the folder ID now, rather than the name (or, at least, it's easier to) so I changed the name of the variable on line 11 to match.

Hope that's useful and thanks again for posting this!

@Bodysoulspirit
Copy link

Thanks @dfkoz !

However, as @SpinyN0rman mentioned, it seems some changes where made on Google's side.

For me the code the work I had to
a/ Use @SpinyN0rman his changes.
b/ But remove his .getId() while collecting the files.

So that the code looks like this :


var folderID = "yourGoodleDriveFolderID"; //Folder ID is not the folder name !
var extensions = ["JPG", "JPEG", "PNG"];

// Email parameters
var to      = "yourcustomemail@yourdomain.com"
var subject = "yourcustomsubject"
var body    = "<p><img src='cid:imageBlob' style='width: 200px;' /></p>" +
              "<p>Like this one? See it <a href='{picture-link}'>here</a>.</p>";

function sendRandomPic()
{

   var files = DriveApp.getFolderById(folderID).getFiles();
   var results = [];

   // Scan each file to see if it matches any of our filters.
   while ( files.hasNext() )
      {
         results.push(files.next());
         // else error: no file found
      }

   // Select a random file. 
   if (results.length == 0)
      {
         file = null;
      }
   else 
      {
         file = results[Math.floor(Math.random() * results.length + 1)];
      }

   // Send an email containing the picture.
   MailApp.sendEmail
         ({
            to: to,
            subject: subject,
            htmlBody: body.replace("{picture-link}",file.getUrl()),
            inlineImages: { imageBlob: file.getThumbnail() },
         });
}

Then, add the triggers as mentioned in the original code at // #5: Click Resources -> Current Project's Triggers, and set up the script to run as often as you would like.

Please Note that:

  • As mentioned in this stack overflow answer [http://stackoverflow.com/questions/17355823/mailapp-sendemail-not-working], putting your own Gmail Adress (the address the script belongs to) won't work. The messages will be visible from within your outbox folders, but not your inbox folders. I have no workaround for that.
  • Your Google Folder ID can be found by navigating into your folder and grab the last number and digits part of the url from within your navigator address bar. So if your folder url is something like that "https://drive.google/drive/folders/lkuLk0LyChz6sFfdVjOGdhcj", your folder ID will be "llkuLk0LyChz6sFfdVjOGdhcj"
  • Please also note that you could have to enable some API's as mentioned in the Google Developers Sections here : https://developers.google.com/apps-script/guides/services/advanced

@jruysaribeiro
Copy link

jruysaribeiro commented Sep 20, 2016

Hey! Great work! I need your help with something though.

I adapted your original with all the comments and did some changes of my own.

MailApp.sendEmail(emailAddress, subject, body, message,
{attachments: file.getAs('image/jpeg')}
);

This way the image goes to the email as an actual image (attachment) and not as a link or as a thumbnail which didn't work (maybe because of the latest changes).

What I need now is to send the same file that is emailed to me to the trash. As soon as the script emails me the picture it should send the picture to Google Drive trash. I have tried a bunch of things but to no avail. I have no experience with Google Scripts at all, only what I researched to get this to work. I send you the script as I have it right now.

var folderID = "FolderID"; //Folder ID is not the folder name !
var extensions = ["JPG", "JPEG", "PNG"];

// Email parameters
var emailAddress = "your e-mail (cannot be the same as the one that owns the Google Drive account"
var subject = "Subject"
var message = "Message";

function sendRandomPic()
{

var files = DriveApp.getFolderById(folderID).getFiles();
var results = [];

// Scan each file to see if it matches any of our filters.
while ( files.hasNext() )
{
results.push(files.next());
// else error: no file found
}

// Select a random file.
if (results.length == 0)
{
file = null;
}
else
{
file = results[Math.floor(Math.random() * results.length + 1)];
}

// Send an email containing the picture.
MailApp.sendEmail(emailAddress, subject, message,
{attachments: file.getAs('image/jpeg')}
);

}

Any suggestions?

Edit 1: I'm sorry for digging up this old thread but I didn't find anything like this anywhere.

@benlind
Copy link

benlind commented Oct 21, 2016

I updated the script to work with the most recent Google Apps Script API. See the new script in my repo.

@Artapel
Copy link

Artapel commented Sep 21, 2017

Good day. Please may i ask for your assistance

I Would like to Have the script pick a random line from a txt or csv file and use it as the subject line. I would also like to Have the script pick a random line from a txt or csv file and use it in the the body of the E-mail.

Would you mind helping me with this?

Regards

@VarsharaniDesai
Copy link

Hey! Great work! I need your help with a error that I am receiving sometimes after execution of the script.

TypeError: Cannot read properties of undefined (reading 'getUrl')

Could you please help me with this?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment