RUN@cloud » SendGrid Service

SendGrid Service

Last modified by Cyrille Le Clerc on 2014/03/15 19:25

CloudBees now supports sending mail from applications with the SendGrid Service for RUN@cloud. To activate your subscription, go to SendGrid in grandcentral.

Once the subscription has been activated, go to the Sendgrid page (click on the SendGrid service in the Services page) to configure your service.

SendGrid Credentials

For most application stacks, your SendGrid credentials are automatically injected into the application as System properties (for Java) or environment variables.  The injected names are SENDGRID_USERNAME and SENDGRID_PASSWORD.

If you need to get direct access to your password from outside your application, you can use the following Bees SDK command:

bees service:info sendgrid

Configure JavaEE Applications

A default mail session is defined for your application running in a Tomcat cloud container under the "mail/SendGrid" JNDI name. The session is configured with your SendGrid subscription information for a TLS/plain connection on port 587.

You can then use the mail session (mail/SendGrid) resource from your application by retrieving it from the environment context:

            Context initCtx = new InitialContext();
            Session session = (Session) initCtx.lookup("java:comp/env/mail/SendGrid");

Then send emails via the standard JavaMail API:

            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress(FROM);
            InternetAddress to[] = new InternetAddress[1];
            to[0] = new InternetAddress(TO);
            message.setRecipients(Message.RecipientType.TO, to);
            message.setSubject(SUBJECT);
            message.setContent(CONTENT, "text/plain");
            Transport.send(message);

Configure other Applications

On alternative application stack that don't use JNDI to get a Mail Session, or don't use JavaMail at all, the SendGrid subscription information is also available as system properties:

SENDGRID_SMTP_HOST

SENDGRID_USERNAME

SENDGRID_PASSWORD

as a sample, configuring a Play! application.conf to use SendGrid is :

mail.smtp.host=${SENDGRID_SMTP_HOST}
mail.smtp.user=${SENDGRID_USERNAME}
mail.smtp.pass=${SENDGRID_PASSWORD}
mail.smtp.channel=starttls
mail.smtp.port=587

Customize the default Mail Session

The default "mail/SendGrid" mail session can be customized by defining session resource parameters via the cloudbees-web.xml

For example: to turn on mail debugging mode

<?xml version="1.0"?>
<cloudbees-web-app xmlns="http:~/~/www.stax.net/xml/webapp/1">     
   <resource name="mail/SendGrid" auth="Container"  type="javax.mail.Session">
       <param name="mail.debug" value="true" />
   </resource>
</cloudbees-web-app>

Mail Session Alias

If a mail session with a specific name is needed, a mail session alias can be defined as a web.xml resource-ref

For example: to define a mail session JNDI name as "mail/MySession" add the following resource-ref to your web.xml

  <resource-ref>
       <res-ref-name>mail/MySession</res-ref-name>
       <res-type>javax.mail.Session</res-type>
       <res-auth>Container</res-auth>
   </resource-ref>

Custom Mail Session

To create a fully custom java mail session, define a new resource in the WEB-INF/cloudbees-web.xml file.

For example: to define a mail session that uses a SSL connection to the mail server

<?xml version="1.0"?>
<cloudbees-web-app xmlns="http:~/~/www.stax.net/xml/webapp/1">     
   <resource name="mail/Session" auth="Container"  type="javax.mail.Session">
       <param name="mail.transport.protocol" value="smtps" />
       <param name="mail.smtp.host" value="smtp.sendgrid.net" />
       <param name="mail.smtp.port" value="465" />
       <param name="mail.smtp.auth" value="true" />
       <param name="mail.smtp.ssl.enable" value="true" />
       <param name="mail.smtp.user" value="sendgrid account user name" />
       <param name="password" value="sendgrid account password" />
       <param name="mail.smtp.socketFactory.class" value="javax.net.ssl.SSLSocketFactory" />
       <param name="mail.smtp.socketFactory.fallback" value="false" />
       <param name="mail.smtp.quitwait" value="false" />
   </resource>
</cloudbees-web-app>

Sending mail with Wildfly

See the Wildfly 8 ClickStack page.

Sending mail with JBoss

The JBoss Web Profile does not support mail session JNDI access. To use SendGrid with JBoss you need to instantiate your own mail client. The smtp host and credentials are available via System Properties

Example java mail client:
   
    private void mailClient(String from, String to, String subject, String content) {
        SMTP_HOST_NAME = System.getProperty("SENDGRID_SMTP_HOST");
        SMTP_AUTH_USER = System.getProperty("SENDGRID_USERNAME");
        SMTP_AUTH_PWD = System.getProperty("SENDGRID_PASSWORD");        

        Properties props = new Properties();
        props.put("mail.transport.protocol", "smtp");
        props.put("mail.smtp.host", SMTP_HOST_NAME);
        props.put("mail.smtp.port", 587);
        props.put("mail.smtp.auth", "true");

        Authenticator auth = new SMTPAuthenticator();
        Session mailSession = Session.getDefaultInstance(props, auth);
        mailSession.setDebug(true);
        Transport transport = null;
       try {
            transport = mailSession.getTransport();

            MimeMessage message = new MimeMessage(mailSession);

            Multipart multipart = new MimeMultipart("alternative");

            BodyPart part1 = new MimeBodyPart();
            part1.setText(content);

            BodyPart part2 = new MimeBodyPart();
            part2.setContent("<strong>" + content + "</strong>", "text/html");

            multipart.addBodyPart(part1);
            multipart.addBodyPart(part2);

            message.setContent(multipart);

            message.setFrom(new InternetAddress(from));
            InternetAddress toAddress[] = new InternetAddress[1];
            toAddress[0] = new InternetAddress(to);
            message.setRecipients(Message.RecipientType.TO, toAddress);
            message.setSubject(subject);

            transport.connect();
            transport.sendMessage(message, message.getRecipients(Message.RecipientType.TO));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
           if (transport != null)
               try {
                    transport.close();
                } catch (MessagingException e) {
                    e.printStackTrace();
                }
        }
    }

    private class SMTPAuthenticator extends javax.mail.Authenticator {
        public PasswordAuthentication getPasswordAuthentication() {
           String username = SMTP_AUTH_USER;
           String password = SMTP_AUTH_PWD;
          return new PasswordAuthentication(username, password);
        }
    }

Tags:
Created by Fabian Donze on 2011/11/10 14:01