This tutorial shows how to use SendGrid to send email from an app running on a Compute Engine virtual machine (VM) instance.
Objectives
- Use SendGrid with Postfix on a Compute Engine instance.
- Use SendGrid in Java code running on a Compute Engine instance.
- Use SendGrid in Node.js code running on a Compute Engine instance.
- Use SendGrid with a Microsoft Exchange edge transport server on a Compute Engine instance.
For other information about setting up SendGrid, see the SendGrid developer documentation.
Costs
In this document, you use the following billable components of Google Cloud:
- Compute Engine
To generate a cost estimate based on your projected usage,
use the pricing calculator.
Before you begin
- Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
-
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
Roles required to select or create a project
- Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
-
Create a project: To create a project, you need the Project Creator
(
roles/resourcemanager.projectCreator), which contains theresourcemanager.projects.createpermission. Learn how to grant roles.
-
Verify that billing is enabled for your Google Cloud project.
-
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
Roles required to select or create a project
- Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
-
Create a project: To create a project, you need the Project Creator
(
roles/resourcemanager.projectCreator), which contains theresourcemanager.projects.createpermission. Learn how to grant roles.
-
Verify that billing is enabled for your Google Cloud project.
- In the Google Cloud console, go to the Create an instance page.
-
Set Name to
sendgrid-tutorial. - In the OS and Storage section, click Change to begin configuring your boot disk.
- On the Public images tab, choose a Debian or CentOS image version.
- Click Select.
- To create the VM, click Create.
-
Use the
Google Cloud Marketplace
to sign up for the SendGrid email service. Make a note of your SendGrid SMTP
account credentials, which include username, password, and hostname. Your
SMTP username and password are the same as what you used to sign up for the
service. The SendGrid hostname is
smtp.sendgrid.net. - Create an API key:
- Sign in to SendGrid and go to Settings > API Keys.
- Create an API key.
- Select the permissions for the key. At a minimum, the key must have Mail send permissions to send email.
- Click Save to create the key.
- SendGrid generates a new key. This is the only copy of the key, so make sure that you copy the key and save it for later.
Sending mail from your instance with Postfix
Complete the following steps to connect to your sendgrid-tutorial instance and run SendGrid with Postfix.
Connect to your sendgrid-tutorial instance using SSH
- In the Google Cloud console, go to the VM instances page.
- In the list of virtual machine instances, click SSH in the row of the instance that you want to connect to.
Configuring SendGrid as an SMTP relay with Postfix
Run the following commands in your SSH terminal to use SendGrid as an SMTP relay with Postfix.
Become a superuser:
sudo su -Set a safe umask:
umask 077Install the Postfix Mail Transport Agent:
Debian
apt update && apt -y install postfix libsasl2-modules
CentOS
yum install postfix cyrus-sasl-plain cyrus-sasl-md5 -y
If prompted, select the Local Only configuration and accept the default domain name.
Modify the Postfix configuration options. Open
/etc/postfix/main.cffor editing. For example, to use thenanotext editor, enter the following command:nano /etc/postfix/main.cfUpdate the file:
Comment out the following lines:
# default_transport = error # relay_transport = error
Add the following lines to the end of the file:
relayhost = [smtp.sendgrid.net]:2525 smtp_tls_security_level = encrypt smtp_sasl_auth_enable = yes smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd header_size_limit = 4096000 smtp_sasl_security_options = noanonymousThe above lines enforce SSL/TLS support and configure SMTP authentication for these requests. A simple access and security layer (SASL) module handles authentication in the Postfix configuration.
Save and close the file.
Generate the SASL password map using the API key you generated in the Before you begin section. Replace
your-api-keywith the API key you generated.echo [smtp.sendgrid.net]:2525 apikey:your-api-key >> /etc/postfix/sasl_passwd
Use the
postmaputility to generate a.dbfile:postmap /etc/postfix/sasl_passwdVerify that you have a
.dbfile:ls -l /etc/postfix/sasl_passwd*-rw------- 1 root root ... /etc/postfix/sasl_passwd -rw------- 1 root root ... /etc/postfix/sasl_passwd.db
Remove the file containing your credentials because it is no longer needed:
rm /etc/postfix/sasl_passwdSet the permissions on your
.dbfile and verify that the other file was removed:chmod 600 /etc/postfix/sasl_passwd.db ls -la /etc/postfix/sasl_passwd*-rw------- 1 root root ... /etc/postfix/sasl_passwd.db
Reload your configuration to load the modified parameters:
Debian
/etc/init.d/postfix restartCentOS
postfix reloadInstall the
mailutilsormailxpackage:Debian
apt -y install mailutils
CentOS
yum install mailx -ySend a test email:
echo 'message' | mail -s subject [email protected]
Replace the following:
message: The body of the email.subject: The subject of the email.[email protected]: The email address that you want to send a message to.
Look in your system logs for a status line containing
statusand the successful server response code(250):Debian
tail -n 5 /var/log/syslogCentOS
tail -n 5 /var/log/maillog
Sending mail with Java on your instance
Connect to your sendgrid-tutorial instance using SSH
- In the Google Cloud console, go to the VM instances page.
- In the list of virtual machine instances, click SSH in the row of the instance that you want to connect to.
Construct and send an email message
The following instructions use the SendGrid Java client library to construct and send an email message through SendGrid. You can view the full example on GitHub.
In your SSH terminal:
Become a superuser and set a safe umask:
sudo su - umask 077Install Java and Maven:
apt -y update && apt -y install git-core openjdk-11-jdk mavenClone the GitHub repo:
git clone https://github.com/GoogleCloudPlatform/java-docs-samples.gitGo to the main source code for the example:
cd /root/java-docs-samples/compute/sendgrid/src/main/java/com/example/compute/sendgridOpen
SendEmailServelet.javafor editing.Replace
your-sendgrid-api-keywith the API key for your SendGrid account.Replace
your-sendgrid-from-emailwith the email address you want to send mail from.Replace
destination-emailwith the email address you want to send mail to.
Go to the root directory of the sample code:
cd /root/java-docs-samples/compute/sendgridPackage the Java class:
mvn clean packageGo to the new
targetdirectory:cd targetSet permissions that let you execute the jar file:
chmod +x compute-sendgrid-1.0-SNAPSHOT-jar-with-dependencies.jarRun the alternative Java version selector:
update-alternatives --config javaSelect the
java-11-openjdk-amd64option.Execute the Java file:
java -jar compute-sendgrid-1.0-SNAPSHOT-jar-with-dependencies.jar
Sending mail with Node.js on your instance
To run this sample, you must have Node.js version 7.6 or later installed
on the VM instance.
Connect to your sendgrid-tutorial instance using SSH
- In the Google Cloud console, go to the VM instances page.
- In the list of virtual machine instances, click SSH in the row of the instance that you want to connect to.
Construct and send an email message
In your SSH terminal:
Become a superuser and set a safe umask:
sudo su - umask 077Update your package repositories:
Debian
apt updateCentOS
yum update -yInstall Node.js dependencies:
Debian
apt -y install git-core curl build-essential openssl libssl-devCentOS
yum install git-core curl openssl openssl-devel -y yum groupinstall "Development Tools" -yInstall Node.js. By default, the installation also installs npm:
Debian
curl -sL https://deb.nodesource.com/setup_14.x | sudo bash - sudo apt -y install nodejsCentOS
curl --silent --location https://rpm.nodesource.com/setup_14.x | bash -Then, install Node.js:
yum -y install nodejsInstall the SendGrid Node.js client:
npm install sendgridClone the sample repository:
git clone https://github.com/GoogleCloudPlatform/nodejs-docs-samples.gitGo to the directory that contains the SendGrid sample:
cd nodejs-docs-samples/computeCopy the
sendgrid.jsfile:cp sendgrid.js sendmail.jsOpen
sendmail.jsfor editing.Replace
your-sendgrid-api-keywith the API key for your SendGrid account.Replace
[email protected]with the email address that you want to send mail from.Replace
[email protected]with the email address that you want to send mail to.
Run the program to send an email message through SendGrid:
node sendmail.js
Sending mail from an Exchange edge transport server
You can set up Microsoft Exchange to send outbound email with SendGrid by configuring an outbound send connector. For details, see Deploying Microsoft Exchange Server 2016 on Compute Engine.
Clean up
To avoid incurring charges to your Google Cloud account for the resources used in this tutorial, either delete the project that contains the resources, or keep the project and delete the individual resources.
Delete the project
The easiest way to eliminate billing is to delete the project that you created for the tutorial.
To delete the project:
- In the Google Cloud console, go to the Manage resources page.
- In the project list, select the project that you want to delete, and then click Delete.
- In the dialog, type the project ID, and then click Shut down to delete the project.
Delete your Compute Engine instance
To delete a Compute Engine instance:
- In the Google Cloud console, go to the VM instances page.
-
Select the checkbox for
your
sendgrid-tutorialinstance. - To delete the instance, click More actions, click Delete, and then follow the instructions.
What's next
Explore reference architectures, diagrams, and best practices about Google Cloud. Take a look at our Cloud Architecture Center.