v3 API Java Code Example
(information)
Info
We recommend using SendGrid Java, our client library, available on GitHub, with full documentation.
(information)
Info
Do you have an API Key yet? If not, go get one. You're going to need it to integrate!
The following example sends a single email with the Twilio SendGrid Java library. Set your API key in the SENDGRID_API_KEY environment variable, then build and send the message.
1// using SendGrid's Java Library2// https://github.com/sendgrid/sendgrid-java3import com.sendgrid.*;4import com.sendgrid.helpers.mail.*;5import com.sendgrid.helpers.mail.objects.*;6import java.io.IOException;78public class Example {9public static void main(String[] args) throws IOException {10Email from = new Email("test@example.com");11String subject = "Sending with SendGrid is Fun";12Email to = new Email("test@example.com");13Content content = new Content("text/plain", "and easy to do anywhere, even with Java");14Mail mail = new Mail(from, subject, to, content);1516SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY"));17Request request = new Request();18try {19request.setMethod(Method.POST);20request.setEndpoint("mail/send");21request.setBody(mail.build());22Response response = sg.api(request);23System.out.println(response.getStatusCode());24System.out.println(response.getBody());25System.out.println(response.getHeaders());26} catch (IOException ex) {27throw ex;28}29}30}