Monday, January 23, 2012

Integrating JangoSMTP with Java

Since Oracle provides the JavaMail package for sending emails in Java, it's easy to integrate JangoSMTP into your current Java software.

First, you need to obtain the JavaMail library. If you're using the enterprise edition of Java, then you probably already have JavaMail installed. Otherwise, you will need to unzip the contents and add them to your buildpath in Eclipse, or your classpath in Windows. To add the package to your buildpath, click Project > Properties > Libraries > Add External JARs.

Then you can use JavaMail to connect to the JangoSMTP server and send a message. You should connect to relay.jangosmtp.net using your JangoSMTP credentials. We've already built a simple example that will connect to JangoSMTP to send a message.

Properties props = new Properties();
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.host", "relay.jangosmtp.net");
props.put("mail.smtp.port", 25);
props.put("mail.smtp.auth", "true");
 
// set up a new authenticator
Authenticator Authorization = new SMTPAuthenticator();
Session JangoSMTPSession = 
             Session.getDefaultInstance(props, Authorization);
Transport transport = JangoSMTPSession.getTransport();
 
// this object will hold the details of the email
MimeMessage EmailMessage = new MimeMessage(JangoSMTPSession);
 
// store the plain text and HTML portions of our email
Multipart MultipartContent = new MimeMultipart("alternative");
 
// first set the plain text message
BodyPart part1 = new MimeBodyPart();
part1.setText(PlainTextMessage);
MultipartContent.addBodyPart(part1);
 
// then set the HTML message
BodyPart part2 = new MimeBodyPart();
part2.setContent(HTMLMessage, "text/html");
MultipartContent.addBodyPart(part2); 
 
EmailMessage.setContent(MultipartContent);
        
// Set the From Address.
// Must be a sender that is saved in your from-addresses.
EmailMessage.setFrom(new InternetAddress(FromAddress));
        
// Set the subject
EmailMessage.setSubject(Subject);
        
// set the to-address
EmailMessage.addRecipient(Message.RecipientType.TO,
                                new InternetAddress(ToAddress));
 
// Connect, Send the Message, and Close the Connection
transport.connect();
transport.sendMessage(EmailMessage, 
          EmailMessage.getRecipients(Message.RecipientType.TO));
transport.close();

With the authentication code that is in the example file, this code will allow you to construct and send a transactional email using JangoSMTP. This email will contain all the tracking and other features set up in the settings section of the JangoSMTP site.