Sendgrid email tutorials in java with examples


Java project create using maven

Maven has different archetypes for different application generates for web and standard java project.

mvn archetype:generate -DarchetypeGroupId=org.apache.maven.archetypes -DarchetypeArtifactId=maven-archetype-quickstart -DarchetypeVersion=1.4

This creates an java sample module project

Next add sendgrid mvn jar file sendgrid-java in pom.xml


    <dependency>
      <groupId>com.sendgrid</groupId>
      <artifactId>sendgrid-java</artifactId>
      <version>4.7.2</version>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-log4j12</artifactId>
      <version>1.7.30</version>
      <scope>test</scope>
    </dependency>
    ```
Next install the depedencies using mvn clean install command

## Sendgrid email java

```java
import com.sendgrid.Method;
import com.sendgrid.Request;
import com.sendgrid.Response;
import com.sendgrid.SendGrid;
import com.sendgrid.helpers.mail.Mail;
import com.sendgrid.helpers.mail.objects.Content;
import com.sendgrid.helpers.mail.objects.Email;

import java.io.IOException;

public class SendEmail {
    final private String sendGridApi = "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";

    public static void main(String[] args) throws IOException {

            Email from = new Email("admin@azym.com");
            Email to = new Email("kbabu@azym.com"); // use your own email address here

            String subject = "This is test subject";
            Content content = new Content("text/html", "<strong>Test Content</strong>");

            Mail mail = new Mail(from, subject, to, content);

            SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY"));
            Request request = new Request();

            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.getHeaders());
            System.out.println(response.getBody());
        }

    }
THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.