Search code examples
emailgoogle-apps-scriptautomationgmail-api

how can I force Google App Script MailApp.sendEmail to use a new thread for each email in a loop?


I am doing a simple app, I have an spread sheet with a few columns, one is an email addres and the others are filled with the information I want to send in an email to that addres. The code is really simple, it is just a while loop with the execution of MailApp.sendEmail with the data in each row.

The issue that I am having is that when I execute the app all the emails end up in the same email threard. And this makes really difficult to follow the responses beacause each email is independet. I've been looking for a while on how to force MailApp.sendEmail to start a new thread, but I can't find how to do it in the documentation or in the web.


Solution

    • The issue is that you are using the exact same subject for these emails and therefore they end up in the same email thread.

    For example:

    This will put all the emails in the same thread:

    function myFunction() {
      for (let i=0; i<2; i++){
      
      MailApp.sendEmail("example@gmail.com",
                      "Test", // subject is the same for every email
                      "This is an test email");
      }
    }
    

    This will put the emails in different threads:

    function myFunction() {
      for (let i=0; i<2; i++){
      
      MailApp.sendEmail("example@gmail.com",
                      "Test"+i, // subject is different for every email
                      "This is an test email");
      }
    }
    

    Instead of using i which is not very well descriptive as a subject, you could send the datetime:

    "Test"+new Date()

    although this might not work if the emails are sent instantly and therefore the subject will be the same again, but it might work in your case.

    Ideally, you would want something that is relevant to the email, for example relevant to the body of your email.