How do I use smtp.gmail.com in Google Apps Script?

Viewed 929

Is it possible to use smtp.gmail.com from within Google Apps Script?

I am getting this error:

Exception: Address unavailable: http://smtp.gmail.com

Here's the code:

var user = 'user@gmail.com';
var password = 'thisisapassword';

var emailData = {
              'to': 'recipient@example.com',
              'subject': 'This works!',
              'content': '<b>Testing successful</b>'
            };
            
            var url = "smtp.gmail.com";
            var request = {method:'POST',
                          contentType: 'text/html', 
                          payload: emailData, 
                          headers:{"Authorization":"Basic " + Utilities.base64Encode(user + ":" + password), 
                          muteHttpExceptions: true}};
            
            UrlFetchApp.fetch(url, request);
1 Answers

In Apps Script you can use the Class MailApp to send emails.

You can use for example the sendEmail(recipient, subject, body, options) method:

// Send an email with two attachments: a file from Google Drive (as a PDF) and an HTML file.
var file = DriveApp.getFileById('1234567890abcdefghijklmnopqrstuvwxyz');
var blob = Utilities.newBlob('Insert any HTML content here', 'text/html', 'my_document.html');
MailApp.sendEmail('mike@example.com', 'Attachment example', 'Two files are attached.', {
    name: 'Automatic Emailer Script',
    attachments: [file.getAs(MimeType.PDF), blob]
});
Related