How to Send Email in Java using Twilio SendGrid

November 27, 2019
Written by

How to Send Email in Java using Twilio SendGrid

If you’re writing a Java app and you need to programmatically send some emails, the Twilio SendGrid API is just the thing you need.

You’ll need to sign up for a free Twilio SendGrid account and create an API key. Then you can get started with a few lines of code.

In this post I’ll go through each step to get you up and emailing in no time.

Starting Out

You’ll need:

The first thing you should do is to create a SendGrid account. The free tier will work just fine for this tutorial. Once you are signed up and logged in, create an API key. You can choose any name you like, but make sure to save the key before moving on.

A screenshot of the "Create API Key" dialog on the SendGrid  console, showing 3 options, of which I have selected "Full Access" and called my key "my-api-key"

Choose “Create & View” then make sure to copy your key somewhere safe:

The "API Key Created" dialog, showing my new API Key (redacted) and a warning to copy it because I won't be shown it again.

To avoid writing your API key in your Java code, it is best to store it as an environment variable. That way you can share your code without exposing an API key that would give access to your SendGrid account. IntelliJ and Eclipse can manage environment variables for you, or you can set them manually. For this post I’ll assume you have set an environment variable called SENDGRID_API_KEY.

Sending an Email with Java

I strongly recommend using an IDE and a build tool for your Java projects. Eclipse and IntelliJ IDEA Community Edition are good free IDE choices, and Apache Maven and Gradle are both popular build tools. Whichever combination you choose you can use the IDE to create a new project. Add the SendGrid helper library to your project configuration:

Gradle config, add this in build.gradle:

implementation 'com.sendgrid:sendgrid-java:4.4.1'

or Maven config, add this in pom.xml:

<dependency>
  <groupId>com.sendgrid</groupId>
  <artifactId>sendgrid-java</artifactId>
  <version>4.4.1</version>
</dependency>

Create a new class called SendGridEmailer in your project with the following content:

import com.sendgrid.*;
import com.sendgrid.helpers.mail.Mail;
import com.sendgrid.helpers.mail.objects.*;

import java.io.IOException;

public class SendGridEmailer {

   public static void main(String[] args) throws IOException {

       Email from = new Email("test@example.com");
       Email to = new Email("matthew@<REDACTED>"); // use your own email address here

       String subject = "Sending with Twilio SendGrid is Fun";
       Content content = new Content("text/html", "and <em>easy</em> to do anywhere with <strong>Java</strong>");

       Mail mail = new Mail(from, subject, to, content);

       SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY"));
       Request request = new Request();

       request.setMethod(Method.POST);
       request.setEndpoint("mail/send");
       request.setBody(mail.build());

       Response response = sg.api(request);

       System.out.println(response.getStatusCode());
       System.out.println(response.getHeaders());
       System.out.println(response.getBody());
   }
}

Notice that on the highlighted line the code reads your API key from an environment variable, so be sure to set this in your IDE. If you forget to do this you will see an error: The provided authorization grant is invalid, expired, or revoked.

Run the code in your IDE to send yourself an email, then check your inbox:

Screenshot of an email inbox with a message "sent via sendgrid.net" reading "Sending with Twilio SendGrid is Fun and easy to do anywhere with Java"

What next?

You just sent your first email using Java and SendGrid, but what else could you do? You can process and respond to incoming mail using SendGrid’s Inbound Parse Webhook, add attachments and personalizations, schedule mail or check the SendGrid API docs for lots more ideas.

I can’t wait to hear about what you build. Feel free to get in touch with your experiences, comments or questions.