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

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 Azure portal menu or the home page, select Create a resource.

    Screenshot of the Azure portal menu with the Create a resource option selected.

  3. Search for and select SendGrid.

    Screenshot of the Azure portal Marketplace screen showing "SendGr" in the search box and SendGrid selected in the search results.

  4. Complete the signup form and select Create.

    Screenshot of the Create a New SendGrid Account dialog with the Name, Password, Subscription and Resource group fields filled in.

  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.

    Screenshot of the Create a New SendGrid Account dialog with the Choose your pricing tier section opened and the Free pricing tier selected.

  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.

    Screenshot of the SendGrid Accounts page showing the new account ContosoSendGrid listed.

    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 our FAQ.

    Screenshot of the ContosoSendGrid account page with the Manage button highlighted.

    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.

    Screenshot showing that the Settings page for the ContosoSendGrid account is opened by selecting All settings from the ContosoSendGrid account page.

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

To find your SendGrid API Key

  1. Click Manage.

    Screenshot of the ContosoSendGrid account page with the Manage button highlighted.

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

    Screenshot of the SendGrid dashboard with the Settings dropdown opened and API Keys selected.

  3. Click the Create API Key.

    Screenshot of the API Keys screen with the Create API Key button selected.

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

    Screenshot of the Add New General API Key screen with Mail Send set to Full Access, Scheduled Sends set to No Access, and the Save button highlighted.

  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.

    Screenshot of the ContosoSendGrid account page with the Key icon highlighted.

  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.

Screenshot of the ContosoSendGrid account page with the Manage button highlighted.

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 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

    import java.util.Properties;
    import javax.mail.*;
    import javax.mail.internet.*;
    public class MyEmailer {
        private static final String SMTP_HOST_NAME = "";
        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("", SMTP_HOST_NAME);
                properties.put("mail.smtp.port", 587);
                properties.put("mail.smtp.auth", "true");
                // …
  2. 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);
  3. Create an authenticated email session through a javax.mail.Session object.

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

  5. 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();
    <p>Your Contoso order has <b>shipped</b>.</p>
    <p>Thank you,<br>John</br></p>",
message.setFrom(new InternetAddress(""));
    new InternetAddress(""));
message.setSubject("Your recent order");

How to: Send an email

The following shows how to send an email.

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

How to: Add an attachment

The following code shows you how to add an attachment.

// Local file name and path.
String attachmentName = "";
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.

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.

        \"<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:

        <p>This is the body of the message. Visit
        <a href=''></a>.</p>
        Thank you.",
  • To enable the click tracking, use the following code:


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(""),
        new InternetAddress("") };


To add a Cc recipient, use the following:

message.addRecipient(Message.RecipientType.CC, new

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.