How To Send Mail Using Sendgrid In Java

Sendgrid is a service hosted on the cloud that helps businesses in delivering emails. It enables companies to send notifications via API in a programmed manner. In this guide, we will provide a step-by-step process to send emails using SendGrid in Java.

Step 1: Create a SendGrid Account

Firstly, you need to create a SendGrid account. Visit the SendGrid signup page and fill out the form. Once you’re signed up and signed in, you should be able to create an API Key. Save this key; it’ll be used in your Java program.

Step 2: Setup Your Java Project

In your Java project, you need to manage dependencies. If you’re using Maven, include SendGrid’s library into your pom.xml file:

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

Step 3: Send an Email

Now, you’re ready to send an email. Let’s create a simple Java program to do just that. Replace the placeholders in the below code with your actual values.

    import com.sendgrid.*;

    public class SendMail {
        public static void main(String[] args) {
            Email from = new Email("[email protected]");
            String subject = "Hello World from SendGrid";
            Email to = new Email("[email protected]");
            Content content = new Content("text/plain", "This is a test email sent via SendGrid");
            Mail mail = new Mail(from, subject, to, content);

            SendGrid sg = new SendGrid("your_sendgrid_api_key");
            Request request = new Request();

            try {
                request.setMethod(Method.POST);
                request.setEndpoint("mail/send");
                request.setBody(mail.build());

                Response response = sg.api(request);
                System.out.println(response.getStatusCode());
                System.out.println(response.getBody());
                System.out.println(response.getHeaders());
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }
    

With just a few lines of code, you can send an email from your Java application using SendGrid. The above program is pretty straightforward:

  • from: The sender’s email address.
  • to: The recipient’s email address.
  • subject: The subject of the email.
  • content: The actual content of the email.
  • sg: The SendGrid object, initialized with your API key.

Once the Mail object is built, it’s attached to the request, and the request is sent to the SendGrid API via the sg.api(request) function.

And that’s it! Now you know how to send mail using SendGrid in Java. Happy emailing!