Can I create a Google Docs script to auto-email the editor when they open the document?

Hey everyone! I’m trying to set up a Google Apps Script that automatically sends an email to the person who opens a Google Doc. The idea is that when an editor opens the document, they should get an email from themselves.

I’ve been tinkering with this code:

function notifyEditor() {
  var doc = DocumentApp.getActiveDocument();
  var user = Session.getActiveUser();
  var email = user.getEmail();
  
  MailApp.sendEmail({
    to: email,
    subject: 'Document Opened',
    body: 'You just opened the document!'
  });
}

However, it’s not sending the email as I expected. When a friend opened the document, they didn’t receive any email. Am I overlooking something? What can I do to ensure the script triggers correctly when the document is opened?

I appreciate any guidance on this. Thanks in advance!

Your approach is on the right track, but there are a few adjustments needed to make it work as intended. First, as others have mentioned, you’ll need to set up a trigger for the function to run on document open. Additionally, Session.getActiveUser() may not always return the expected result, especially in a shared document context.

Instead, consider using PropertiesService to store the last editor’s email, and update it each time the document is edited. Then, when the document is opened, you can retrieve this stored email and send the notification.

Remember to thoroughly test your script and ensure you’ve granted the necessary permissions for it to function correctly. Good luck with your implementation!

I’ve noticed that when you set up an Apps Script for Google Docs, it’s crucial to define a trigger so that the function runs on the desired event. If your function is not bound to an open trigger, it won’t run automatically when the document is opened. Also, bear in mind that Session.getActiveUser() can be unreliable if the script executes under the owner’s permissions rather than that of the editor. You might consider obtaining the user’s information using DriveApp methods. Finally, ensure you have enabled the necessary permissions to access user data and send emails.

hey bob, i think ur script needs a trigger to work. try goin to “edit” > “current project’s triggers” and set up a new trigger for ur function. choose “from spreadsheet” and “on open” as the event type. that should make it run when someone opens the doc. hope this helps!