How to Send Email in Java using 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: