Sunday, February 3, 2008

Sending mail using Gmail SMTP server with Java

This is a companion project of my previous experiment with S/Mime encryption. This script is also based on Beanshell and it's purpose is basically to connect to Gmail SMTP servers and deliver the encrypted payload to the message recipients.

There are several examples off the Internet but, somehow, I had to combine the techniques before I finally pulled this off. I've enabled debug, otherwise this post would not have any image at all!

Here's the debug output..

Here's the script..

addClassPath( "./mail.jar" );
addClassPath( "./activation.jar" );

import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.Authenticator;
import javax.mail.internet.MimeMessage;

private class SMTPAuthenticator extends javax.mail.Authenticator {
public PasswordAuthentication getPasswordAuthentication()
return new PasswordAuthentication(smtpUsername, smtpPassword);

public static final String smtpHost = "";
public static final String smtpUsername = "";
public static final String smtpPassword = "-change-me-";
public static final String smtpPort = "465";

Properties props = new Properties();
props.put("mail.smtp.user", smtpUsername);
props.put("", smtpHost);
props.put("mail.smtp.port", smtpPort);
props.put("mail.smtps.auth", "true");
props.put("mail.smtp.debug", "true");
props.put("mail.smtp.socketFactory.port", smtpPort);
props.put("mail.smtp.socketFactory.class", "");
props.put("mail.smtp.socketFactory.fallback", "false");

SecurityManager security = System.getSecurityManager();
Authenticator auth = new SMTPAuthenticator();
Session smtpSession = Session.getInstance(props, auth);

MimeMessage smtpMessage = new MimeMessage(smtpSession,
new FileInputStream("Encrypted.eml"));
smtpMessage.setSentDate(new Date());

Transport tr = smtpSession.getTransport("smtp");
tr.connect(smtpHost, smtpUsername, smtpPassword);
tr.sendMessage(smtpMessage, smtpMessage.getAllRecipients());


$NPR$ said...

I want send mail using our own SMTP server (SSL enabled). The code given here is working for Gmail.But its not working for My SMTP server.
I am getting this error: Unrecognized SSL message, plaintext connection?

Please help me to resolve this issue.

Coboshhh... said...

I have exactly the same problem Unrecognized SSL
what should I do?

Legiongrid said...

I made it I just had to comment this line
props.put("mail.smtp.socketFactory.class", "");

j said...

There is a typo in the key for the auth flag. It should be "mail.smtp.auth."

I needed only the following three properties to make it work -
props.put("", host);
props.put("mail.smtp.auth", "true");

LittleHelper said...

I've removed to following code and it still works:


LittleHelper said...

I've removed to following code and it still works: