Thursday, October 16, 2008

Javamail : Using SMTP server with SSL (Secure)

One of the major drawbacks of EC2 is the static IPs with history. Most of the services treat these IPs as dynamic IPs. The EC2 infrastructure makes in very easy for somebody to set up a server to send spam. Of course, Amazon is quite vigilant about it and takes it very seriously.

Now the IP address yo are using is most probably blacklisted. What do you do? Use external SMTP server.

Coming to the topic of the post. Sending mails via SMTP over SSL in Java. JavaMail looks to the widely used solution. I tried many examples on net, but couldn't it right. Everybody claimed "it should just work" and it just didn't. After going through documentation and the sample program, I manged to do it. The external documentation says the code has a bug. (If there is one, why can't you just fix it?) Here is the basic snippet to do this.



Properties props = new Properties();

props.put("mail.smtps.host", SMTP_HOST_NAME);
props.put("mail.smtps.port", Integer.toString(SMTP_PORT));
props.put("mail.smtps.auth", "true");

// Secure session
Session ssession = Session.getInstance(props, null);
ssession.setDebug(true);

Message msg = new MimeMessage(ssession);

msg.setFrom(new InternetAddress(FROM_ADDRESS));
InternetAddress[] address = {new InternetAddress(TO_ADDRESS, false)};
msg.setRecipients(Message.RecipientType.TO, address);
msg.setSubject("Test E-Mail through Java " + new Date());
msg.setSentDate(new Date());
// Set message content
msg.setText("This is a test of sending a " text e-mail through Java.\n");

//Send the message
SMTPTransport t = (SMTPTransport)ssession.getTransport("smtps");
t.connect(SMTP_HOST_NAME, SMTP_AUTH_USER, SMTP_AUTH_PWD);
t.sendMessage(msg, msg.getAllRecipients()); // !!! Note this.

Labels: , , ,


Google now understands forums.

Try this google search link : Javamail smtp nabble". In the results you can see number of posts on a thread and the date of last post.

To say this is useful, is an understatement.

Labels:


This page is powered by Blogger. Isn't yours?

Subscribe to Posts [Atom]