New ClickStart: SendGrid with Tomcat

Written by: Sacha Labourey
1 min read
Stay connected

Our serial ClickStack-writer, Cyrille, is happy to announce the availability of a Tomcat7 SendGrid ClickStart that will help you to integrate SendGrid email gateway in your Java applications.

As usual on CloudBees, we create a Java-style binding between your SendGrid account and your application by injecting the proper JNDI JavaMail Session straight in your Tomcat container.

Tomcat7 SendGrid ClickStart

After that, the integration of SendGrid can be as simple as the following lines of code:

<span style="font-family: Courier New, Courier, monospace; font-size: x-small;">@WebServlet(...) public class MyServlet extends HttpServlet {

   <span style="color: blue;"><b>// Get your SendGrid session injected in your application from JNDI</b> </span> 
   <span style="color: blue;"><b>//</b> </span> 
   @Resource(name = "mail/SendGrid", lookup = "mail/SendGrid")  private Session session;
   protected void service(HttpServletRequest req, HttpServletResponse resp) 
                     throws ServletException, IOException {

      <span style="color: blue;"><b>// Create your e-mail using the injected SendGrid session, easy...</b> </span> 
      <span style="color: blue;"><b>//</b> </span> 
      Message message = new MimeMessage(session);  
      message.setFrom(new InternetAddress("no-reply@example.com"));        
      message.setRecipients(Message.RecipientType.TO, new InternetAddress[]{
                                 new InternetAddress("you@example.com")
                           });
      message.setSubject("My Subject");
      message.setContent("My Content", "text/plain");

      <span style="color: blue;"><b>// Send your message!</b> </span> 
      <span style="color: blue;"><b>//</b> </span> 
      Transport.send(message);
   } 
}
</span> 

Note : if you use the JNDI JavaMail Session, beware not to bundle mail.jar in your .war application but to define it as provided in your project. Otherwise, you would get an error (see Tomcat docs here ).

Happy e-mailing!

Onward,

Sacha

Stay up to date

We'll never share your email address and you can opt out at any time, we promise.

Loading form...
Your ad blocker may be blocking functionality on this page. Please disable for an improved experience.