Sendgrid Dynamic Templates with Spring Boot

Upasana | September 22, 2020 | 2 min read | 0 views


In this tutorial we will use Twilio SendGrid Dynamic Templates for sending emails from a Spring Boot application.

About Twilio SendGrid

Twilio SendGrid is a popular cloud-based email delivery service that offers a free account with limit of 100 emails per day (checkout SendGrid Pricing)

Prerequisites

  • You have a Twilio SendGrid Account

  • You have configured a Dynamic template that you want to use in this article

  • You have Java 11 + IDE for java development (IntelliJ IDEA)

Gradle Setup

You can always head to https://start.spring.io/ for creating a Spring Boot starter project.

build.gradle
dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation('com.sendgrid:sendgrid-java:4.6.1')
}

You can get the latest version of SendGrid from Maven Repository.

Next is to specify either the username/password or SendGrid API key in your application.properties to activate Spring Boot Auto configuration for SendGrid (org.springframework.boot.autoconfigure.sendgrid.SendGridAutoConfiguration).

/src/main/resources/application.properties
#Sendgrid API key
spring.sendgrid.api-key: SG.xxxx.yyyy

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

Create a dynamic template

Login to your Twilio SendGrid account and navigate to Dynamic template section under Email API menu on left hand sidebar. Now create a new template with dynamic placeholders, like shown in the current image.

sendgrid dynamic template
Sample Dynamic Template

Capture the Dynamic template ID as that will be used from Spring Boot application.

Send email from Spring

To send an email using Dynamic Templates, you need to grab Id of the dynamic template and use the below code to attach DynamicTemplateData.

SendGridService.kt
@Component
class SendGridService(val sendGrid: SendGrid) {

    private val logger = LoggerFactory.getLogger(SendGridService::class.java)

    fun handNewUserEvent(name: String, email: String) {
        val templateId = "d-cabxxxxxxxxxxxxxxxxxxxxxxxx"
        val mail = Mail()
        mail.setFrom(Email("donotreply@example.org", "Example Org"))
        mail.setTemplateId(templateId)  (1)
        val personalization = Personalization()
        personalization.addDynamicTemplateData("name", name)        (2)
        personalization.addTo(Email(email))
        mail.addPersonalization(personalization)
        sendInternal(mail)
    }

     private fun sendInternal(mail: Mail) {
        logger.info("Sending email with subject {}", mail.subject)
        val request = Request()
        try {
            request.method = Method.POST
            request.endpoint = "mail/send"
            request.body = mail.build()
            val response = sendGrid.api(request)
            println(response.statusCode)    (3)
            println(response.body)
            println(response.headers)
        } catch (ex: IOException) {
            throw ex
        }
    }
}
1 This is the Dynamic Template ID from SendGrid.
2 Dynamic template data is substituted in template to create the real email.
3 We shall check the status code, it should be in 200-299 range for a successful operation, check here for details on status & error codes.

Attachment support

Sendgrid support email attachments, this article covers attachments supprot in detail.


Top articles in this category:
  1. SendGrid emails in Spring Boot
  2. SendGrid Attachments with Spring Boot
  3. Redis rate limiter in Spring Boot
  4. Testing web layer in Spring Boot using WebMvcTest
  5. Basic Auth Security in Spring Boot 2
  6. Elasticsearch with Spring Boot + Spring Data
  7. Dialoglfow fulfillment with Spring Boot

Recommended books for interview preparation:

Find more on this topic:
Buy interview books

Java & Microservices interview refresher for experienced developers.