SendGrid emails in Spring Boot

Carvia Tech | July 17, 2020 | 3 min read | 577 views


In this tutorial we will learn how to send sendgrid text email, multimedia email, email with attachment using sdk from Java and Spring Boot applications.

SendGrid emails with Spring Boot

Spring Boot has auto-configuration (org.springframework.boot.autoconfigure.sendgrid.SendGridAutoConfiguration) for SendGrid that activates when you include the sendgrid java library in build.gradle and specify the below property in config.

build.gradle
implementation 'com.sendgrid:sendgrid-java:4.4.1'

You can find the latest version of sendgrid-java from https://github.com/sendgrid/sendgrid-java/releases

/src/main/resources/application.yml
# SENDGRID CONFIG (SendGridAutoConfiguration)
spring.sendgrid.api-key: <API-KEY> # SendGrid API Key

spring.sendgrid.username: # SendGrid account username (if API key not provided).
spring.sendgrid.password: # SendGrid account password.

pring.sendgrid.proxy.host: # SendGrid proxy host. (optional)
spring.sendgrid.proxy.port: # SendGrid proxy port. (optional)

Spring boot will automatically create a Bean of type SendGridAPI which you can autowire into your component for sending emails.

SendGridMailer.java
import com.sendgrid.Method;
import com.sendgrid.Request;
import com.sendgrid.Response;
import com.sendgrid.SendGridAPI;
import com.sendgrid.helpers.mail.Mail;
import com.sendgrid.helpers.mail.objects.Content;
import com.sendgrid.helpers.mail.objects.Email;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class SendGridMailer {

    @Autowired
    private SendGridAPI sendGridAPI;

    void sendMail() {
        Email from = new Email("from@example.com", "Foo Bar");
        String subject = "Test email with SendGrid";
        Email to = new Email("to@example.com");
        Content content = new Content("text/plain", "Test email with Spring");
        Mail mail = new Mail(from, subject, to, content);
        Request request = new Request();
        try {
            request.setMethod(Method.POST);
            request.setEndpoint("mail/send");
            request.setBody(mail.build());
            Response response = sendGridAPI.api(request);
            System.out.println(response.getBody());
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

Attachment support

We can easily add attachments to Send Grid emails using attachment support in their API. All we need to do is to add base64 encoded attachment. We can use the following Java 8 Base64 based function to convert a byte array into Base64 format.

convertFileToBase64 - converts byte array to base64
private String convertFileToBase64(byte[] input) {
    return Base64.getEncoder().encodeToString(input);
}

Now convert a given file to Base64 and attach it to email, as shown in following code:

Attachment support
Mail mail = new Mail(from, subject, to, content);
Attachments attachment = new Attachments();
attachment.setContent(convertFileToBase64(Files.toByteArray(new File("foo.pdf"))));
attachment.setFilename("foo.pdf");
attachment.setType("application/pdf");
mail.addAttachments(attachment);

Alternatively, SendGrid java api also provides support for attachments using Attachments.Builder

Using Attachments.Builder
final Attachments attachments = new Attachments
        .Builder("foo.pdf", Files.newInputStream(Paths.get("/path/to/foo.pdf")))
        .withType("application/pdf")
        .build();
mail.addAttachments(attachments);

SendGrid email with plain Java without Spring

We can use SendGrid without Spring framework, by managing our own instance of SendGrid created with right SendGrid API Key.

Plain Java implementation for SendGrid
// using SendGrid's Java Library
// https://github.com/sendgrid/sendgrid-java

import com.sendgrid.*;

import java.io.IOException;

public class Example {

    public static void main(String[] args) throws IOException {
        Email from = new Email("test@example.com");
        String subject = "Sending with SendGrid is Fun";
        Email to = new Email("test@example.com");
        Content content = new Content("text/plain", "and easy to do anywhere, even with Java");
        Mail mail = new Mail(from, subject, to, content);
        SendGrid sg = new SendGrid(System.getenv("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 (IOException ex) {
            throw ex;
        }
    }
}

Did you know?

You can use Unix command line utility to encode and decode in base64 format.

Encode into Base64
$ echo  'linuxhint.com' | base64
Decode Base64 content
$ echo 'bGludXhoaW50LmNvbQo=' | base64 --decode

That’s all.


Top articles in this category:
  1. Sendgrid Dynamic Templates with Spring Boot
  2. SendGrid Attachments with Spring Boot
  3. Setting a Random Port in Spring Boot Application at startup
  4. Basic Auth Security in Spring Boot 2
  5. Feign RequestInterceptor in Spring Boot
  6. Redis based rate limiter in Spring Boot
  7. Custom banner in spring boot


Find more on this topic:
Spring Framework image
Spring Framework

Spring Framework - MVC, Dependency Injection, Spring Hibernate, Spring Data JPA, Spring Boot and Spring Cloud for Microservices Architecture.

Last updated 1 week ago


Recommended books for interview preparation:

This website uses cookies to ensure you get the best experience on our website. more info