Beginner26
Beginner26

Reputation: 25

How to send automated emails with hyperlinks using javascript in google sheets

I want to send email containing some text message and hyperlink so the user can click on the link and opens up the URL. But it only display as text when I send. Truly appreciate if anyone can help out.

function sendEmails() {

    var sheet = SpreadsheetApp.getActiveSheet();
    var startRow = 2;  // First row of data to process
    var numRows = 10;   // Number of rows to process
    var dataRange = sheet.getRange(startRow, 1, numRows, 4)
    var data = dataRange.getValues();
    for (i in data) {
        var row = data[i];
        var emailAddress = row[1];
        var name = row[0];
        var message = row[2];
        var links = <a href="https://www.google.com/">Click here</a>;
        var subject = "Sending emails from a Spreadsheet";
        MailApp.sendEmail(emailAddress, subject, message, links);
    }
}

Upvotes: 0

Views: 2737

Answers (1)

sneep
sneep

Reputation: 1918

https://developers.google.com/apps-script/reference/mail/mail-app

You are using sendEmail(String,String,String,String), but if you use sendEmail(String,String,String,Object) instead, you can use an object with an htmlBody property, which will allow HTML.

There's also sendEmail(Object), for which an example is given that has htmlBody:

MailApp.sendEmail({
  to: "[email protected]",
  subject: "Logos",
  htmlBody: "inline Google Logo<img src='cid:googleLogo'> images! <br>" +
            "inline YouTube Logo <img src='cid:youtubeLogo'>",
  inlineImages:
    {
      googleLogo: googleLogoBlob,
      youtubeLogo: youtubeLogoBlob
    }
});

You said you've managed to send text emails, so I'm taking it from there. I'm going to assume that you want the following things in your HTML message: row[2] and a link to https://www.google.com/. Your links variable becomes:

    var links = row[2] + '<a href="https://www.google.com/">Click here</a>';

If you e.g. want a newline between row[2] and the link, you can add <br>s:

    var links = row[2] + '<br /><a href="https://www.google.com/">Click here</a>';

(BTW: You might want to rename links to e.g. htmlBody. Using the sendEmail(String,String,String,Object) version of sendEmail to add the htmlBody we get this:

MailApp.sendEmail(emailAddress, subject, message, { htmlBody: links });

Upvotes: 2

Related Questions