How to Send Email Using SendGrid from Java

This guide demonstrates how to perform common programming tasks with the SendGrid email service on Azure. The samples are written in Java. The scenarios covered include constructing email, sending email, adding attachments, using filters, and updating properties. For more information on SendGrid and sending email, see the Next steps section.

What is the SendGrid Email Service?

SendGrid is a cloud-based email service that provides reliable transactional email delivery, scalability, and real-time analytics along with flexible APIs that make custom integration easy. Common SendGrid usage scenarios include:

  • Automatically sending receipts to customers
  • Administering distribution lists for sending customers monthly e-fliers and special offers
  • Collecting real-time metrics for things like blocked e-mail, and customer responsiveness
  • Generating reports to help identify trends
  • Forwarding customer inquiries
  • Email notifications from your application

For more information, see https://sendgrid.com.

Create a SendGrid account

Azure customers can unlock 25,000 free emails each month. These 25,000 free monthly emails will give you access to advanced reporting and analytics and all APIs (Web, SMTP, Event, Parse and more). For information about additional services provided by SendGrid, visit the SendGrid Solutions page.

To sign up for a SendGrid account

  1. Sign in to the Azure portal.

  2. In the menu on the left, click Create a resource.

    command-bar-new

  3. Click Add-ons and then SendGrid Email Delivery.

    sendgrid-store

  4. Complete the signup form and select Create.

    sendgrid-create

  5. Enter a Name to identify your SendGrid service in your Azure settings. Names must be between 1 and 100 characters in length and contain only alphanumeric characters, dashes, dots, and underscores. The name must be unique in your list of subscribed Azure Store Items.

  6. Enter and confirm your Password.

  7. Choose your Subscription.

  8. Create a new Resource group or use an existing one.

  9. In the Pricing tier section select the SendGrid plan you want to sign up for.

    sendgrid-pricing

  10. Enter a Promotion Code if you have one.

  11. Enter your Contact Information.

  12. Review and accept the Legal terms.

  13. After confirming your purchase you will see a Deployment Succeeded pop-up and you will see your account listed in the All resources section.

    all-resources

    After you have completed your purchase and clicked the Manage button to initiate the email verification process, you will receive an email from SendGrid asking you to verify your account. If you do not receive this email, or have problems verifying your account, please see this FAQ.

    manage

    You can only send up to 100 emails/day until you have verified your account.

    To modify your subscription plan or see the SendGrid contact settings, click the name of your SendGrid service to open the SendGrid Marketplace dashboard.

    settings

    To send an email using SendGrid, you must supply your API Key.

To find your SendGrid API Key

  1. Click Manage.

    manage

  2. In your SendGrid dashboard, select Settings and then API Keys in the menu on the left.

    api-keys

  3. Click the Create API Key.

    general-api-key

  4. At a minimum, provide the Name of this key and provide full access to Mail Send and select Save.

    access

  5. Your API will be displayed at this point one time. Please be sure to store it safely.

To find your SendGrid credentials

  1. Click the key icon to find your Username.

    key

  2. The password is the one you chose at setup. You can select Change password or Reset password to make any changes.

To manage your email deliverability settings, click the Manage button. This will redirect to your SendGrid dashboard.

manage

For more information on sending email through SendGrid, visit the Email API Overview.

How to: Use the javax.mail libraries

Obtain the javax.mail libraries, for example from https://www.oracle.com/technetwork/java/javamail and import them into your code. At a high-level, the process for using the javax.mail library to send email using SMTP is to do the following:

  1. Specify the SMTP values, including the SMTP server, which for SendGrid is smtp.sendgrid.net.
        import java.util.Properties;
        import javax.mail.*;
        import javax.mail.internet.*;

        public class MyEmailer {
           private static final String SMTP_HOST_NAME = "smtp.sendgrid.net";
           private static final String SMTP_AUTH_USER = "your_sendgrid_username";
           private static final String SMTP_AUTH_PWD = "your_sendgrid_password";

           public static void main(String[] args) throws Exception{
               new MyEmailer().SendMail();
           }

           public void SendMail() throws Exception
           {
              Properties properties = new Properties();
                 properties.put("mail.transport.protocol", "smtp");
                 properties.put("mail.smtp.host", SMTP_HOST_NAME);
                 properties.put("mail.smtp.port", 587);
                 properties.put("mail.smtp.auth", "true");
                 // …
  1. Extend the javax.mail.Authenticator class, and in your implementation of the getPasswordAuthentication method, return your SendGrid user name and password.

    private class SMTPAuthenticator extends javax.mail.Authenticator {
    public PasswordAuthentication getPasswordAuthentication() {
       String username = SMTP_AUTH_USER;
       String password = SMTP_AUTH_PWD;
       return new PasswordAuthentication(username, password);
    }
    
  2. Create an authenticated email session through a javax.mail.Session object.

    Authenticator auth = new SMTPAuthenticator();
    Session mailSession = Session.getDefaultInstance(properties, auth);
    
  3. Create your message and assign To, From, Subject and content values. This is shown in the How To: Create an Email section.

  4. Send the message through a javax.mail.Transport object. This is shown in the [How To: Send an Email][#how-to-send-an-email] section.

How to: Create an email

The following shows how to specify values for an email.

MimeMessage message = new MimeMessage(mailSession);
Multipart multipart = new MimeMultipart("alternative");
BodyPart part1 = new MimeBodyPart();
part1.setText("Hello, Your Contoso order has shipped. Thank you, John");
BodyPart part2 = new MimeBodyPart();
part2.setContent(
    "<p>Hello,</p>
    <p>Your Contoso order has <b>shipped</b>.</p>
    <p>Thank you,<br>John</br></p>",
    "text/html");
multipart.addBodyPart(part1);
multipart.addBodyPart(part2);
message.setFrom(new InternetAddress("john@contoso.com"));
message.addRecipient(Message.RecipientType.TO,
   new InternetAddress("someone@example.com"));
message.setSubject("Your recent order");
message.setContent(multipart);

How to: Send an email

The following shows how to send an email.

Transport transport = mailSession.getTransport();
// Connect the transport object.
transport.connect();
// Send the message.
transport.sendMessage(message, message.getAllRecipients());
// Close the connection.
transport.close();

How to: Add an attachment

The following code shows you how to add an attachment.

// Local file name and path.
String attachmentName = "myfile.zip";
String attachmentPath = "c:\\myfiles\\";
MimeBodyPart attachmentPart = new MimeBodyPart();
// Specify the local file to attach.
DataSource source = new FileDataSource(attachmentPath + attachmentName);
attachmentPart.setDataHandler(new DataHandler(source));
// This example uses the local file name as the attachment name.
// They could be different if you prefer.
attachmentPart.setFileName(attachmentName);
multipart.addBodyPart(attachmentPart);

How to: Use filters to enable footers, tracking, and analytics

SendGrid provides additional email functionality through the use of filters. These are settings that can be added to an email message to enable specific functionality such as enabling click tracking, Google analytics, subscription tracking, and so on. For a full list of filters, see Filter Settings.

  • The following shows how to insert a footer filter that results in HTML text appearing at the bottom of the email being sent.

    message.addHeader("X-SMTPAPI",
        "{\"filters\":
        {\"footer\":
        {\"settings\":
        {\"enable\":1,\"text/html\":
        \"<html><b>Thank you</b> for your business.</html>\"}}}}");
    
  • Another example of a filter is click tracking. Let’s say that your email text contains a hyperlink, such as the following, and you want to track the click rate:

    messagePart.setContent(
        "Hello,
        <p>This is the body of the message. Visit
        <a href='http://www.contoso.com'>http://www.contoso.com</a>.</p>
        Thank you.",
        "text/html");
    
  • To enable the click tracking, use the following code:

    message.addHeader("X-SMTPAPI",
        "{\"filters\":
        {\"clicktrack\":
        {\"settings\":
        {\"enable\":1}}}}");
    

How to: Update email properties

Some email properties can be overwritten using set Property or appended using add Property.

For example, to specify ReplyTo addresses, use the following:

InternetAddress addresses[] =
    { new InternetAddress("john@contoso.com"),
      new InternetAddress("wendy@contoso.com") };

message.setReplyTo(addresses);

To add a Cc recipient, use the following:

message.addRecipient(Message.RecipientType.CC, new
InternetAddress("john@contoso.com"));

How to: Use additional SendGrid services

SendGrid offers web-based APIs that you can use to leverage additional SendGrid functionality from your Azure application. For full details, see the SendGrid API documentation.

Next steps

Now that you’ve learned the basics of the SendGrid Email service, follow these links to learn more.