Sending Email with SendGrid

This tutorial shows how to use SendGrid to send email from an application running on a Compute Engine instance. SendGrid is a third-party email service that offers Compute Engine users a free trial with 12,000 transactional emails free each month.

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.

Costs

This tutorial uses billable components of Cloud Platform including Google Compute Engine.

New Cloud Platform users might be eligible for a free trial.

Before you begin

  1. Sign in to your Google account.

    If you don't already have one, sign up for a new account.

  2. Select or create a Cloud Platform project.

    Go to the Manage resources page

  3. Enable billing for your project.

    Enable billing

  4. In the Cloud Platform Console, go to the VM Instances page.

    Go to the VM Instances page

  5. Click the Create instance button.
  6. Set Name to sendgrid-tutorial.
  7. In the Boot disk section, click Change to begin configuring your boot disk.
  8. In the OS images tab, choose a Debian or CentOS image.
  9. Click Select.
  10. Click the Create button to create the instance.
  11. Use the Google Cloud Launcher 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.
  12. Create an API key:
    1. Sign in to Sendgrid and go to Settings > API Keys.
    2. Create an API key.
    3. Select the permissions for the key. At a minimum, the key will need Mail send permissions to send email.
    4. Click Save to create the key.
    5. SendGrid generates a new key. This is the only copy of the key so make sure to copy the key and save it for later.

Sending mail with Postfix on your instance

Follow these steps to connect to your sendgrid-tutorial instance and run SendGrid with Postfix.

Connect to your sendgrid-tutorial instance using SSH

  1. In the Cloud Platform Console, go to the VM Instances page.

    Go to the VM Instances page

  2. In the list of virtual machine instances, click SSH in the row of the instance that you want to connect to.

Run Postfix on your instance

In your SSH terminal:

  1. Become a superuser and set a safe umask:

    sudo su -
    umask 077
    
  2. Install the Postfix Mail Transport Agent. If prompted, select the Local Only configuration and accept the default choices for domain names.

    Debian

    apt-get update && apt-get install postfix libsasl2-modules -y
    

    CentOS

    yum install postfix cyrus-sasl-plain cyrus-sasl-md5 -y
    

  3. To modify the Postfix configuration options, open /etc/postfix/main.cf for editing.

  4. If the following lines are in the file, comment them out:

    default_transport = error
    relay_transport = error
    

  5. Add the SendGrid SMTP service by adding the following line to the end of the file:

    relayhost = [smtp.sendgrid.net]:2525
    
  6. At the end of the file, add the following lines to enforce SSL/TLS support and to configure SMTP authentication for these requests. A simple access and security layer (SASL) module handles authentication in the Postfix configuration:

    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 = noanonymous
    
  7. Generate the SASL password map:

    echo [smtp.sendgrid.net]:2525 [YOUR_SMTP_LOGIN]:[YOUR_SMTP_PASSWORD] >> /etc/postfix/sasl_passwd
    

    where:

    • [YOUR_SMTP_LOGIN] is your SendGrid username.
    • [YOUR_SMTP_PASSWORD] is your SendGrid password.
  8. Use the postmap utility to generate a .db file:

    postmap /etc/postfix/sasl_passwd
    
  9. Verify that you have a .db file:

    ls -l /etc/postfix/sasl_passwd*
    

    -rw------- 1 root root    ...  /etc/postfix/sasl_passwd
    -rw------- 1 root root    ...  /etc/postfix/sasl_passwd.db
    

  10. Remove the file containing your credentials, as it is no longer needed:

    rm /etc/postfix/sasl_passwd
    
  11. Set the permissions on your .db file:

    chmod 600 /etc/postfix/sasl_passwd.db
    ls -la /etc/postfix/sasl_passwd.db
    

    -rw------- 1 root root    ...  /etc/postfix/sasl_passwd.db
    

  12. Reload your configuration to load the modified parameters:

    Debian

    /etc/init.d/postfix restart
    

    CentOS

    postfix reload
    

  13. Install the mailx or mailutils package:and test your configuration.

    Debian

    apt-get install mailutils -y
    

    CentOS

    yum install mailx -y
    

  14. Send a test message:

    echo 'Test passed.' | mail -s Test-Email EMAIL@EXAMPLE.COM
    

    Look in your system logs for a status line containing status and the successful server response code (250):

    Debian

    tail -n 5 /var/log/syslog
    

    CentOS

    tail -n 5 /var/log/maillog
    

Sending mail with Java on your instance

Connect to your sendgrid-tutorial instance using SSH

  1. In the Cloud Platform Console, go to the VM Instances page.

    Go to the VM Instances page

  2. 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:

  1. Become a superuser and set a safe umask:

    sudo su -
    umask 077
    
  2. Install Java and Maven:

    apt-get update -y && apt-get install git-core openjdk-8-jdk maven -y
    
  3. Clone the GitHub repo:

    git clone https://github.com/GoogleCloudPlatform/java-docs-samples.git
    
  4. Go to the main source code for the example:

    cd /root/java-docs-samples/compute/sendgrid/src/main/java/com/example/compute/sendgrid
    
  5. Open SendEmailServelet.java for editing.

    • Replace YOUR-SENDGRID-API-KEY with the API key for your SendGrid account.

    • Replace YOUR-SENDGRID-FROM-EMAIL with the email address you you want to send mail from.

    • Replace DESTINATION-EMAIL with the email address you want to send mail to.

  6. Go to the root directory of the sample code:

    cd /root/java-docs-samples/compute/sendgrid
    
  7. Package the Java class:

    mvn clean package
    
  8. Go to the new target directory:

    cd target
    
  9. Set permissions to allow you to execute the jar file:

    chmod +x compute-sendgrid-1.0-SNAPSHOT-jar-with-dependencies.jar
    
  10. Run the alternative Java version selector:

    update-alternatives --config java
    

    Select the java-8-openjdk-amd64 option.

  11. Execute the Java file:

    java -jar compute-sendgrid-1.0-SNAPSHOT-jar-with-dependencies.jar
    

Sending mail with Node.js on your instance

Connect to your sendgrid-tutorial instance using SSH

  1. In the Cloud Platform Console, go to the VM Instances page.

    Go to the VM Instances page

  2. 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:

  1. Become a superuser and set a safe umask:

    sudo su -
    umask 077
    
  2. Update your package repositories:

    Debian

    apt-get update
    

    CentOS

    yum update -y
    

  3. Install Node.js dependencies:

    Debian

    apt-get install git-core curl build-essential openssl libssl-dev -y
    

    CentOS

    yum install git-core curl openssl openssl-devel -y
    yum groupinstall "Development Tools" -y
    

  4. Install Node.js. The installation will also install npm by default:

    Debian

    curl -sL https://deb.nodesource.com/setup_6.x | sudo -E bash -
    sudo apt-get install -y nodejs
    

    CentOS

    curl --silent --location https://rpm.nodesource.com/setup_6.x | bash -
    

    Then, install Node.js:

    yum -y install nodejs
    

  5. Install the SendGrid Node.js client:

    npm install sendgrid
    
  6. Clone the sample repository:

    git clone https://github.com/googleapis/nodejs-compute.git
    
  7. Go to the directory that contains the SendGrid sample:

    cd nodejs-compute/samples
    
  8. Copy the sendgrid.js file:

    cp sendgrid.js sendmail.js
    
  9. Open sendmail.js for editing.

    • Replace <your-sendgrid-api-key> with the API key for your SendGrid account.

    • Replace from_email@example.com with the email address that you want to send mail from.

    • Replace to_email@example.com with the email address that you want to send mail to.

    // This sample is based off of https://www.npmjs.com/package/sendgrid#without-mail-helper-class
    var Sendgrid = require('sendgrid')(
      process.env.SENDGRID_API_KEY || '<your-sendgrid-api-key>'
    );
    
    var request = Sendgrid.emptyRequest({
      method: 'POST',
      path: '/v3/mail/send',
      body: {
        personalizations: [
          {
            to: [{email: 'to_email@example.com'}],
            subject: 'Sendgrid test email from Node.js on Google Cloud Platform',
          },
        ],
        from: {email: 'from_email@example.com'},
        content: [
          {
            type: 'text/plain',
            value:
              'Hello!\n\nThis a Sendgrid test email from Node.js on Google Cloud Platform.',
          },
        ],
      },
    });
    
    Sendgrid.API(request, function(error, response) {
      if (error) {
        console.log('Mail not sent; see error message below.');
      } else {
        console.log('Mail sent successfully!');
      }
      console.log(response);
    });

  10. Execute the program to send an email message through SendGrid:

    node sendmail.js
    

Cleaning up

To avoid incurring charges to your Google Cloud Platform account for the resources used in this tutorial:

Delete the project

The easiest way to eliminate billing is to delete the project you created for the tutorial.

To delete the project:

  1. In the Cloud Platform Console, go to the Projects page.

    Go to the Projects page

  2. In the project list, select the project you want to delete and click Delete project. After selecting the checkbox next to the project name, click
      Delete project
  3. 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:

  1. In the Cloud Platform Console, go to the VM Instances page.

    Go to the VM Instances page

  2. Click the checkbox next to your sendgrid-tutorial instance.
  3. Click the Delete button at the top of the page to delete the instance.

What's next

Try out other Google Cloud Platform features for yourself. Have a look at our tutorials.

Monitor your resources on the go

Get the Google Cloud Console app to help you manage your projects.

Send feedback about...

Compute Engine Documentation