Sending Email with Mailjet

Mailjet is a third-party global email service that offers Google Compute Engine users a free tier with 25,000 emails each month. In addition, Mailjet also offers:

  • An API, user interface, and SMTP relay to send transactional and marketing email.
  • European data privacy compliance.
  • Email and deliverability features such as customizable priority settings and automated throttle management.
  • API resource library in Go, PHP, Nodejs, Java, Python, Ruby to manage sub-accounts, authentication, contacts, campaigns, custom payloads, statistics, real time events and parsing through the Event API.
  • Integrated MJML framework to create responsive HTML email templates.
  • 24/7 follow-the-sun support in 4+ languages.
  • Ability to send emails from domains other than gmail.com.

Before you begin

  1. Create a new Mailjet account on Mailjet's Google partner page*. When signing up, provide the domain and email address from which you want to send email messages.

    If you sign up for Mailjet without using the partner page linked above, the free usage tier has much lower limits of 200 messages per day (6,000 messages per month).

  2. Get your Mailjet SMTP account credentials.

Next, follow some of the examples below to set up your mail configuration. For extensive documentation of other email solutions, including examples of integration with most common SMTP servers, libraries, and frameworks, see Mailjet's documentation.

Configuring relay with Postfix

Configuring Mailjet as a mail relay allows Postfix to forward emails destined for remote delivery.

  1. Connect to your instance using SSH:

    gcloud compute ssh INSTANCE
    
  2. Install the Postfix Mail Transport Agent. When prompted, accept the default choices for domain names but select the Local Only configuration.

    Debian


    user@test-instance:~# sudo apt-get update && sudo apt-get install postfix libsasl2-modules -y
    

    CentOS


    user@test-instance:~# sudo yum install postfix cyrus-sasl-plain cyrus-sasl-md5 -y
    

  3. Modify the Postfix configuration options. Postfix configuration options are set in the main.cf file. Open the file with the text editor of your choice:

    user@test-instance:~# sudo vi /etc/postfix/main.cf
    
  4. If they exist, comment out the following lines:

    # default_transport = error
    # relay_transport = error
    
  5. Add the Mailjet SMTP service by adding the following line to the end of the file:

    relayhost = in.mailjet.com:2525
    
  6. Next, add the following lines to enforce SSL/TLS support and to configure STMP authentication for these requests. A simple access and security layer (SASL) module handles authentication in the Postfix configuration. Add the following lines to the end of the file:

    smtp_tls_security_level = encrypt
    smtp_sasl_auth_enable = yes
    smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd
    smtp_sasl_security_options = noanonymous
    

    Save your changes and close the file.

  7. Create the SASL password map with the text editor of your choice:

    user@test-instance:~# sudo vi /etc/postfix/sasl_passwd
    
  8. To the sasl_passwd file, add the following lines to provide the credentials for Mailjet:

    in.mailjet.com:2525 YOUR_SMTP_KEY:YOUR_SMTP_SECRET
    
  9. Use the postmap utility to generate a .db file:

    user@test-instance:~# sudo postmap /etc/postfix/sasl_passwd
    user@test-instance:~# sudo ls -l /etc/postfix/sasl_passwd*
    -rw------- 1 root root    68 Jun  1 10:50 /etc/postfix/sasl_passwd
    -rw------- 1 root root 12288 Jun  1 10:51 /etc/postfix/sasl_passwd.db
    
  10. Next, remove the file containing your credentials as it is no longer needed:

    user@test-instance:~# sudo rm /etc/postfix/sasl_passwd
    
  11. Set the permissions on your .db file:

    user@test-instance:~# sudo chmod 600 /etc/postfix/sasl_passwd.db
    user@test-instance:~# sudo ls -la /etc/postfix/sasl_passwd.db
    -rw------- 1 root root 12288 Aug 31 18:51 /etc/postfix/sasl_passwd.db
    
  12. Finally, reload your configuration to load the modified parameters:

    Debian


    user@test-wheezy:~# sudo /etc/init.d/postfix restart
    

    CentOS


    [user@test-centos ~]# sudo postfix reload
    

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

    Debian


    user@test-wheezy:~# sudo apt-get install mailutils -y
    

    CentOS


    [user@test-centos ~]# sudo yum install mailx -y
    

    Send a test message:

     user@test-instance:~# echo 'Test passed.' | mail -s Test-Email EMAIL@EXAMPLE.COM
    

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

    Debian


    user@test-wheezy:~# sudo tail -n 5 /var/log/syslog
    

    CentOS


    [user@test-centos ~]# sudo tail -n 5 /var/log/maillog
    

If you run into issues setting up Postfix with Mailjet, see the Mailjet Postfix setup instructions.

Sending mail with Java

Debian
  1. Connect to your instance using SSH:
    gcloud compute ssh [INSTANCE_NAME]
  2. Update your package repositories and install the required packages:
    user@test-instance:~# sudo apt-get update && sudo apt-get install git-core openjdk-8-jdk maven
  3. Clone the Java repo from GitHub:
    user@test-instance:~# git clone https://github.com/GoogleCloudPlatform/java-docs-samples.git
  4. Go to the main source code for the example, located at:
    /root/java-docs-samples/compute/mailjet/src/main/java/com/example/compute/mailjet
  5. Configure your Mailjet settings, replacing the following variables:

    • YOUR-MAILJET-API-KEY with an API key for your Mailjet account.
    • YOUR-MAILJET-SECRET-KEY with the corresponding secret key for your Mailjet account.

    public class MailjetSender{
    
      public static void main(String[] args) throws MailjetException, MailjetSocketTimeoutException {
        final String mailjetApiKey = "YOUR-MAILJET-API-KEY";
        final String mailjetSecretKey = "YOUR-MAILJET-SECRET-KEY";
        MailjetClient client = new MailjetClient(mailjetApiKey, mailjetSecretKey, new ClientOptions("v3.1"));
    
        MailjetSender sender = new MailjetSender();
        sender.sendMailjet(args[0], args[1], client);
      }
    
      public MailjetResponse sendMailjet(String recipient, String sender, MailjetClient client)
      throws MailjetException, MailjetSocketTimeoutException {
        MailjetRequest email = new MailjetRequest(Emailv31.resource)
          .property(Emailv31.MESSAGES, new JSONArray()
            .put(new JSONObject()
              .put(Emailv31.Message.FROM, new JSONObject()
                .put("Email", sender)
                .put("Name", "pandora"))
              .put(Emailv31.Message.TO, new JSONArray()
                .put(new JSONObject()
                  .put("Email", recipient)))
              .put(Emailv31.Message.SUBJECT, "Your email flight plan!")
              .put(Emailv31.Message.TEXTPART, "Dear passenger, welcome to Mailjet! May the delivery force be with you!")
              .put(Emailv31.Message.HTMLPART, "<h3>Dear passenger, welcome to Mailjet!</h3><br />May the delivery force be with you!")));
    
    
        try {
          // trigger the API call
          MailjetResponse response = client.post(email);
          // Read the response data and status
          System.out.println(response.getStatus());
          System.out.println(response.getData());
          return response;
        } catch (MailjetException e) {
          System.out.println("Mailjet Exception: " + e);
          return null;
        }
      }
    }
  6. From the mailjet directory, use Maven to package the class as a JAR file:
    user@test-instance:~# mvn clean package
  7. Ensure that you are using OpenJDK 8:
    user@test-instance:~# sudo update-alternatives --config java
  8. To send an email, from the target directory, run the JAR file with your recipient and sender email addresses as arguments:
    user@test-instance:~# java -jar compute-mailjet-1.0-SNAPSHOT-jar-with-dependencies.jar [RECIPIENT_EMAIL] [SENDER_EMAIL]
CentOS
  1. Connect to your instance using SSH:
    gcloud compute ssh [INSTANCE_NAME]
  2. Update your package repositories and install the required packages:
    user@test-centos:~# sudo yum update && sudo yum install git-core openjdk-8-jdk maven
  3. Clone the Java repo from GitHub:
    user@test-centos:~# git clone https://github.com/GoogleCloudPlatform/java-docs-samples.git
  4. Go to the main source code for the example, located at:
    /root/java-docs-samples/compute/mailjet/src/main/java/com/example/compute/mailjet
  5. Configure your Mailjet settings, replacing the following variables:

    • YOUR-MAILJET-API-KEY with an API key for your Mailjet account.
    • YOUR-MAILJET-SECRET-KEY with the corresponding secret key for your Mailjet account.

    public class MailjetSender{
    
      public static void main(String[] args) throws MailjetException, MailjetSocketTimeoutException {
        final String mailjetApiKey = "YOUR-MAILJET-API-KEY";
        final String mailjetSecretKey = "YOUR-MAILJET-SECRET-KEY";
        MailjetClient client = new MailjetClient(mailjetApiKey, mailjetSecretKey, new ClientOptions("v3.1"));
    
        MailjetSender sender = new MailjetSender();
        sender.sendMailjet(args[0], args[1], client);
      }
    
      public MailjetResponse sendMailjet(String recipient, String sender, MailjetClient client)
      throws MailjetException, MailjetSocketTimeoutException {
        MailjetRequest email = new MailjetRequest(Emailv31.resource)
          .property(Emailv31.MESSAGES, new JSONArray()
            .put(new JSONObject()
              .put(Emailv31.Message.FROM, new JSONObject()
                .put("Email", sender)
                .put("Name", "pandora"))
              .put(Emailv31.Message.TO, new JSONArray()
                .put(new JSONObject()
                  .put("Email", recipient)))
              .put(Emailv31.Message.SUBJECT, "Your email flight plan!")
              .put(Emailv31.Message.TEXTPART, "Dear passenger, welcome to Mailjet! May the delivery force be with you!")
              .put(Emailv31.Message.HTMLPART, "<h3>Dear passenger, welcome to Mailjet!</h3><br />May the delivery force be with you!")));
    
    
        try {
          // trigger the API call
          MailjetResponse response = client.post(email);
          // Read the response data and status
          System.out.println(response.getStatus());
          System.out.println(response.getData());
          return response;
        } catch (MailjetException e) {
          System.out.println("Mailjet Exception: " + e);
          return null;
        }
      }
    }
  6. From the mailjet directory, use Maven to package the class as a JAR file:
    user@test-centos:~# mvn clean package
  7. Ensure that you are using OpenJDK 8:
    user@test-centos:~# sudo alternatives --config java
  8. To send an email, from the target directory, run the JAR file with your recipient and sender email addresses as arguments:
    user@test-centos:~# java -jar compute-mailjet-1.0-SNAPSHOT-jar-with-dependencies.jar [RECIPIENT_EMAIL] [SENDER_EMAIL]

Sending mail with Node.js

The following instructions describe how to use Mailjet with Node.js on Debian Wheezy.

Debian
  1. Connect to your instance using SSH:
    gcloud compute ssh [INSTANCE_NAME]
  2. Update your package repositories:
    user@test-wheezy:~# sudo apt-get update
  3. Install Node.js dependencies:
    user@test-wheezy:~# sudo apt-get install git-core curl build-essential openssl libssl-dev -y
  4. Clone the Node.js repo from github:
    user@test-wheezy:~# git clone https://github.com/nodejs/node
  5. Change directory to the Node.js source tree:
    user@test-wheezy:~# cd node
  6. Configure node software for this OS and virtual machine:
    user@test-wheezy:~# ./configure
  7. Build Node.js, npm, and related objects:
    user@test-wheezy:~# sudo make

    This take might take a few minutes to complete.

  8. Install Node.js, npm, and other software in the default location:
    user@test-wheezy:~# sudo make install
  9. Install the mailer package:
    user@test-wheezy:~# npm install nodemailer nodemailer-smtp-transport
  10. In the node directory, create a new file named sendmail.js containing the following Javascript:
    var mailer = require('nodemailer');
    var smtp = require('nodemailer-smtp-transport');
    
    var transport = mailer.createTransport(smtp({
      host: 'in.mailjet.com',
      port: 2525,
      auth: {
        user: process.env.MAILJET_API_KEY || '<your-mailjet-api-key',
        pass: process.env.MAILJET_API_SECRET || '<your-mailjet-api-secret>'
      }
    }));
    
    transport.sendMail({
      from: 'ANOTHER_EMAIL@ANOTHER_EXAMPLE.COM', // From address
      to: 'EMAIL@EXAMPLE.COM', // To address
      subject: 'test email from Node.js on Google Cloud Platform', // Subject
      text: 'Hello!\n\nThis a test email from Node.js.' // Content
    }, function (err, json) {
      if (err) {
        console.log(err);
      } else {
        console.log(json);
      }
    });
  11. Execute the program to send an email message through Mailjet:
    user@test-wheezy:~# node sendmail
CentOS
  1. Connect to your instance using SSH:
    gcloud compute ssh [INSTANCE_NAME]
  2. Update package repositories:
    user@test-centos:~# sudo yum update -y
  3. Install Node.js dependencies:
    user@test-centos:~# sudo yum install git-core curl openssl openssl-dev -y
    ...
    user@test-centos:~# sudo yum groupinstall "Development Tools" -y
    ...
  4. Clone Node.js repository from github:
    user@test-centos:~# git clone https://github.com/nodejs/node
  5. Change directory to the Node.js source tree:
    user@test-centos:~# cd node
  6. Configure node software for this OS and virtual machine:
    user@test-centos:~# ./configure
  7. Build Node.js, npm, and related objects:
    user@test-centos:~# sudo make

    This take might take a few minutes to complete.

  8. Install Node.js, npm, and other software in the default location:
    user@test-centos:~# sudo make install
  9. Install the mailer package:
    user@test-centos:~# npm install npm install nodemailer nodemailer-smtp-transport
  10. In the node directory, create a new file named sendmail.js containing the following Javascript:
    var mailer = require('nodemailer');
    var smtp = require('nodemailer-smtp-transport');
    
    var transport = mailer.createTransport(smtp({
      host: 'in.mailjet.com',
      port: 2525,
      auth: {
        user: process.env.MAILJET_API_KEY || '<your-mailjet-api-key',
        pass: process.env.MAILJET_API_SECRET || '<your-mailjet-api-secret>'
      }
    }));
    
    transport.sendMail({
      from: 'ANOTHER_EMAIL@ANOTHER_EXAMPLE.COM', // From address
      to: 'EMAIL@EXAMPLE.COM', // To address
      subject: 'test email from Node.js on Google Cloud Platform', // Subject
      text: 'Hello!\n\nThis a test email from Node.js.' // Content
    }, function (err, json) {
      if (err) {
        console.log(err);
      } else {
        console.log(json);
      }
    });
  11. Execute the program to send an email message through SendGrid:
    user@test-centos:~# node sendmail

Mailjet SMTP settings

Here is a quick reference to Mailjet-specific SMTP settings that are used to configure clients:

  • Host: in.mailjet.com
  • Port: 2525

* Google will be compensated for customers who sign up for a non-free account.

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

Send feedback about...

Compute Engine Documentation