DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • Integration Between Java and Slack With Webhooks
  • Integrate Spring With Open AI
  • How To Build Web Service Using Spring Boot 2.x
  • Aggregating REST APIs Calls Using Apache Camel

Trending

  • Manual Sharding in PostgreSQL: A Step-by-Step Implementation Guide
  • Cosmos DB Disaster Recovery: Multi-Region Write Pitfalls and How to Evade Them
  • Agile and Quality Engineering: A Holistic Perspective
  • Endpoint Security Controls: Designing a Secure Endpoint Architecture, Part 1
  1. DZone
  2. Coding
  3. Frameworks
  4. Integrate SendGrid With a Spring Boot and Java App

Integrate SendGrid With a Spring Boot and Java App

In this post, you will learn how to integrate SendGrid's Java Web APIs into your Spring Boot application. Read on to get started!

By 
Ajitesh Kumar user avatar
Ajitesh Kumar
·
Apr. 16, 18 · Tutorial
Likes (4)
Comment
Save
Tweet
Share
34.7K Views

Join the DZone community and get the full member experience.

Join For Free

In this post, you will learn how to integrate your Spring Boot and Java app with the SendGrid Web API. The following are some of the points covered:

  • Create and Configure/Load the SendGrid API Key.
  • Configure the SendGrid Maven entry in POM.xml.
  • Use the SendGrid EmailService custom implementation.
  • Invoke/Test the Email Service.

Create and Configure/Load the SendGrid API Key

  • Create an account with SendGrid.com
  • Go to the SendGrid Setup Guide to using the Web API page. Create an API key.
  • Execute the following script in your development environment.
    echo "export SENDGRID_API_KEY='Paste_Your_API_Key'" > sendgrid.env
    echo "sendgrid.env" >> .gitignore
    source ./sendgrid.env
  • Alternatively, you could also configure the SendGrid API key in your application.properties file and read the key details as part of loading the configuration beans. The following is the sample code:
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.context.annotation.PropertySource;
    
    import com.sendgrid.SendGrid;
    
    @Configuration
    @PropertySource("classpath:application.properties")
    public class SendGridConfig {
    
        @Value("${sendgrid.api.key}") String sendGridAPIKey;
            return new SendGrid(sendGridAPIKey);
        }
    }
    In the above code sample, the SendGrid API Key is read from the application.properties file. The following is the content of the application.properties file.
    sendgrid.api.key = ABCcvbdTYDRS_ksjdhIUYICS.-836jksjsdhYTkPt12hdgsT-whdk
    ahdjfpT3shdBCVNS

    Make sure that you put the API key and not the API Key Id. Or, else, you would get an exception notifying you that the SendGrid API Key not working, such as,"The provided authorization grant is invalid, expired or revoked."

Configure the SendGrid Maven Entry in POM.xml

Get the latest SendGrid Java dependency from the Maven SendGrid Java page.

<!-- https://mvnrepository.com/artifact/com.sendgrid/sendgrid-java -->
<dependency>
    <groupId>com.sendgrid</groupId>
    <artifactId>sendgrid-java</artifactId>
    <version>4.1.2</version>
</dependency>

SendGrid EmailService Custom Implementation

The following represents the implementation for SendGrid APIs. Pay attention to some of the following:

  • SendGrid instances are auto-wired at the time of construction.
  • Content type "text/plain" is used for sending emails in plain text format.
  • Content type "text/html" is used for sending emails in HTML format.
@Service
public class SendGridEmailService implements EmailService {

    private SendGrid sendGridClient;

    @Autowired
    public SendGridEmailService(SendGrid sendGridClient) {
        this.sendGridClient = sendGridClient;

    }

    @Override
    public void sendText(String from, String to, String subject, String body) {
        Response response = sendEmail(from, to, subject, new Content("text/plain", body));
        System.out.println("Status Code: " + response.getStatusCode() + ", Body: " + response.getBody() + ", Headers: "
                + response.getHeaders());
    }

    @Override
    public void sendHTML(String from, String to, String subject, String body) {
        Response response = sendEmail(from, to, subject, new Content("text/html", body));
        System.out.println("Status Code: " + response.getStatusCode() + ", Body: " + response.getBody() + ", Headers: "
                + response.getHeaders());
    }

    private Response sendEmail(String from, String to, String subject, Content content) {
        Mail mail = new Mail(new Email(from), subject, new Email(to), content);
        mail.setReplyTo(new Email("abc@gmail.com"));
        Request request = new Request();
        Response response = null;
        try {
            request.setMethod(Method.POST);
            request.setEndpoint("mail/send");
            request.setBody(mail.build());
            this.sendGridClient.api(request);
        } catch (IOException ex) {
            System.out.println(ex.getMessage());
        }
        return response;
    }
}

The above class implements the following custom Email Service interface:

public interface EmailService {
    void sendText(String from, String to, String subject, String body);
    void sendHTML(String from, String to, String subject, String body);
}

Invoke/Test the SendGrid Email Service

The following is the sample Spring Boot code which can be used to invoke the custom SendGrid email implementation created in the above example.

@SpringBootApplication
public class RecruiterbotApplication implements CommandLineRunner {

    @Autowired EmailService sendGridEmailService;

    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(RecruiterbotApplication.class);
        app.run(args);
    }

    @Override
    public void run(String... arg0) throws IOException, URISyntaxException {
        this.sendGridEmailService.sendHTML("abc@gmail.com", "efg@gmail.com", "Hello World", "Hello, <strong>how are you doing?</strong>");
    }
}

Further Reading / References

  • SendGrid Documentation
  • SendGrid Java API Library on GitHub

Summary

In this post, you learned how to integrate SendGrid's Java Web APIs into your Spring Boot application.

Did you find this article useful? Do you have any questions or suggestions about this article? Leave a comment and ask your questions and I shall do my best to address your queries.

Spring Framework Spring Boot Java (programming language) app Integration API

Published at DZone with permission of Ajitesh Kumar, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Integration Between Java and Slack With Webhooks
  • Integrate Spring With Open AI
  • How To Build Web Service Using Spring Boot 2.x
  • Aggregating REST APIs Calls Using Apache Camel

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!