Send Emails using Google Apps Script and PHP

In the past, I have written about sending website emails using the Gmail API. Though it works perfectly, its flow is a little bit complex to build. In order to achieve this functionality it requires

  • to use a few libraries like Symfony Mailer and HybridAuth.
  • It also requires building the OAuth flow.
  • To integrate OAuth, you need to have a database to store the access token.
  • Database class to insert, update and fetch the access token.

For me, it feels like an overwhelming process just to send emails. And so I have been searching for a solution where I would not require OAuth, packages, and the database to send my emails.

Fortunately, I found a solution from Google itself. With the help of Google Apps Script’s MailApp class, you can easily send emails from your website. The benefit of using MailApp is its sole purpose is sending emails and nothing more. On the other hand, when you give access to the OAuth App, it gets access to your Gmail inbox.

To use MailApp, you need to write Apps Script(which I’ll share in a moment) into your Google account. It’ll have a Web APP URL to accept the POST request. In this POST request, we send the metadata of emails – to, cc, bcc, name, message body, and attachment. Apps Script receives this data and delivers your email via MailApp.

Having said that, let’s study how to send emails using Google Apps Script and PHP. Keep a note, I am using PHP for server-side language. You can use any other programming language and send a POST request to the Apps Script.

Create Web App URL

Head over to the Apps Script page of your Google account. Click on New Project. It will open a page where you’ll find the script editor. You have to write a script inside this editor. Give some name to your project, maybe like SendEmailApp.

Copy and paste the below script into the editor.

const doPost = (request = {}) => {
  const { parameter, postData: { contents, type } = {} } = request;
  if (type === 'application/json') {
	const jsonData = JSON.parse(contents);

	// check quota first
	var emailQuotaRemaining = MailApp.getRemainingDailyQuota();
	if (emailQuotaRemaining == 0) {
  	result = {
    	status: 'error',
    	message: 'Your daily quota is exceeded.'
  	};
  	return ContentService.createTextOutput(JSON.stringify(result));
	}

	to = jsonData.to ? jsonData.to : '';
	cc = jsonData.cc ? jsonData.cc : '';
	bcc = jsonData.bcc ? jsonData.bcc : '';
	subject = jsonData.subject ? jsonData.subject : '';
	message = jsonData.body ? jsonData.body : '';
	name = jsonData.name ? jsonData.name : '';
	replyTo = jsonData.replyTo ? jsonData.replyTo : '';

	if(to == '' || subject == '' || message == '') {
  	result = {
    	status: 'error',
    	message: 'to, subject and message are required.'
  	};
  	return ContentService.createTextOutput(JSON.stringify(result));
	}

	arr_email = {to: to, subject: subject, htmlBody: message};

	if(name != '') {
  	arr_email.name = name;
	}
	if(cc != '') {
  	arr_email.cc = cc;
	}
	if(bcc != '') {
  	arr_email.bcc = bcc;
	}
	if(replyTo != '') {
  	arr_email.replyTo = replyTo;
	}
	try {
  	attachements = jsonData.files ? jsonData.files : [];
  	if(attachements.length > 0) {
    	arr_files = [];
    	for(var i = 0; i < attachements.length; i++) {
      	url = attachements[i];
      	response = UrlFetchApp.fetch(url);
      	blob = response.getBlob();
      	ctype = blob.getContentType();
      	filename = blob.getName();
      	file = blob.setContentType(ctype).setName(filename);
      	arr_files.push(file);
    	}
    	arr_email.attachments = arr_files;
  	}

  	MailApp.sendEmail(arr_email);

  	result = {
    	status: 'success',
    	message: 'Email is sent successfully.',
    	email_quota_remain: MailApp.getRemainingDailyQuota()
  	};
  	return ContentService.createTextOutput(JSON.stringify(result));
	} catch(e) {
  	result = {
    	status: 'error',
    	message: e.message
  	};
  	return ContentService.createTextOutput(JSON.stringify(result));
	}
  }
}

The above code accepts parameters via POST request, builds an array containing email information, and finally sends an email using the sendEmail() method of class MailApp. It also checks if the daily quota is exceeded or not. Google provides different quotas for consumers(gmail.com) and Google Workspace account. For more details about the quota, refer to the documentation.

Next, generate a Web App URL that helps to connect your PHP application with Apps Script. 

Just above the script editor, click on the Save icon and then hit Run.

google-mailapp

It’ll prompt for Authorization. Complete the steps. During the process, you may see a screen where it says Google hasn’t verified this app. Don’t worry about this screen as you’re the one who asks for permission. Click on Advanced and proceed with it.

google-app-verify

Once you complete the authorization, click on Deploy -> New deployment from the top right corner. Choose a Web app from the settings icon.

choose-web-app-type

Execute the web app as yourself, set access to Anyone, and hit the Deploy button.

execute-web-app

In the next window, you’ll get a Web app URL. Note this URL to use in the code later.

Send Emails using Google Apps Script and PHP

Once you’re set with Apps Script and a Web APP URL, the rest of the job is simple. All you need to do is build an array containing details of your email and send this array via a POST request to the Web APP URL.

I’ll use PHP cURL to send the data via POST request as follows.

<?php
$url = "WEB_APP_URL";

$data = array(
	'to' => 'TO_EMAIL',
	'cc' => 'CC_EMAIL',
	'bcc' => 'BCC_EMAIL',
	'subject' => 'Test Subject',
	'body' => 'Test message',
	'name' => 'Artisans Web',
	'files' => ['ATTACHMENT_URL'],
);
$payload = json_encode($data);

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // follow redirects response
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
$response = json_decode($result);
echo $response->message;

Here, we are creating an array by passing a few values to it. You can remove values that you don’t want to use like cc, bcc. The only required parameters are to, subject, and body. This code also works for HTML emails. Just wrap your message inside HTML tags and pass it to the body.

Run this file on a browser and you should see your email is delivered as expected. Following this technique, you don’t need to use PHP’s mail() function anymore. Your emails will be sent via Google MailApp service.

Related Articles

If you liked this article, then please subscribe to our YouTube Channel for video tutorials.

Leave a Reply

Your email address will not be published. Required fields are marked *