cloud_foundry java products

Sending Email from Cloud Foundry Java Applications with SendGrid

featured-cf-genericThe following is a guest blog post by Scott Motte (@scottmotte), Developer Evangelist at SendGrid, a cloud based SMTP email delivery and management service.

A few weeks ago SendGrid released their sendgrid-java helper library. The library goes a step further in sticking with Cloud Foundry’s “it just works” experience and making your life as a developer easier. Previously, you had to write a large amount of boilerplate code using JavaMail. Now, you can send email with just a few lines of code.

How Does It Work?

At your Cloud Foundry Command Line Interface, add SendGrid as a service and bind it your app.

cf create-service sendgrid  
cf bind-service

Next, Install the vcapenv library, and install the sendgrid-java library.

Then add the following code to your project:

import com.github.scottmotte.Vcapenv;
import com.github.sendgrid.SendGrid;

Vcapenv vcapenv = new Vcapenv();
String sendgrid_username = vcapenv.SENDGRID_USERNAME();
String sendgrid_password = vcapenv.SENDGRID_PASSWORD();

SendGrid sendgrid = new SendGrid(sendgrid_username, sendgrid_password);

sendgrid.addTo("[email protected]");
sendgrid.setFrom("[email protected]");
sendgrid.setSubject("Hello World");
sendgrid.setText("My first email through SendGrid");

sendgrid.send();

That’s it. Now you can start sending emails from your Java application! Cloud Foundry developers can send 25,000 emails every month for free. Check out the Cloud Foundry documentation page to get started.

Video Demo

For a working demo of Cloud Foundry + SendGrid, just follow the easy steps in this example video. It uses the sample spring-attack app.