How To Send Email Using Sendgrid In Java

Managing email correspondence has become extremely convenient with the introduction of SendGrid. In this article, we will delve into the process of sending emails through SendGrid using Java.

Why Use SendGrid?

SendGrid is a cloud-based email delivery platform designed to send transactional emails, marketing emails, or email campaigns. It offers a simplified process of email handling with its easy-to-use API, which we can integrate with a wide range of programming languages, including Java.

Getting Started

Before we delve into the code, you need to make sure that you’ve set up your SendGrid account and have your API key ready. If you haven’t done so, you can follow the guide on how to create an API Key in SendGrid.

Sending an Email with SendGrid and Java

To send an email using SendGrid in Java, you’ll need to add the SendGrid dependency to your project. If you’re using Maven, you can add the following dependency in your pom.xml:

      <dependency>
          <groupid>com.sendgrid</groupid>
          <artifactid>sendgrid-java</artifactid>
          <version>4.1.2</version>
      </dependency>
    

Once the dependency is set, we can proceed with writing our Java code to send the email. Here is a basic example:

      import com.sendgrid.*;

      public class SendGridEmail {
          public static void main(String[] args) {
              Email from = new Email("test@example.com");
              String subject = "Hello World from SendGrid";
              Email to = new Email("test@example.com");
              Content content = new Content("text/plain", "Hello, Email!");
              Mail mail = new Mail(from, subject, to, content);

              SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY"));
              Request request = new Request();
              try {
                request.method = Method.POST;
                request.endpoint = "mail/send";
                request.body = mail.build();
                Response response = sg.api(request);
                System.out.println(response.statusCode);
                System.out.println(response.body);
                System.out.println(response.headers);
              } catch (IOException ex) {
                throw ex;
              }
          }
      }
    

This code sends an email from test@example.com to test@example.com with a subject of ‘Hello World from SendGrid’ and a body of ‘Hello, Email!’. The SendGrid API key is retrieved from the environment variables.

Conclusion

With SendGrid and Java, sending emails is a breeze. This guide has shown you the basic setup and usage for sending emails in Java using SendGrid.