6 Oct 2011

Sending JavaMail in Coldfusion using Gmail account

This is an example function that can be used in Coldfusion 9 component.
To avoid getting STARTTLS related exception, I added Transport.setStartTLS(true) method before connect() method.

private void function sendJavaMail(
required String aFromEmailAddr,
required String aToEmailAddr,
required String aSubject,
required String aBody
) {
// config
sMailServer = "smtp.gmail.com";
sUsername = "@gmail.com";
sPassword = "";
// set javamail properties
oProps = createObject("java", "java.util.Properties").init();
oProps.put("mail.smtp.host",sMailServer);
oProps.put("mail.smtp.port","465");
oProps.put("mail.smtp.user",sUsername);
oProps.put("mail.smtp.auth","true");
oProps.put("mail.smtp.starttls.enable","true");
oProps.put("mail.smtp.debug","true");
oProps.put("mail.smtp.socketFactory.port","465");
oProps.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
oProps.put("mail.smtp.socketFactory.fallback","false");
// get static recipient types
oRecipientType = createObject("java", "javax.mail.Message$RecipientType");
// create the session for the smtp server
oMailSession = createObject("java", "javax.mail.Session").getDefaultInstance(oProps);
oMailSession.setDebug(true);
// create a new MIME message
oMimeMessage = createObject("java", "javax.mail.internet.MimeMessage").init(oMailSession);
// create the to and from e-mail addresses
oAddressFrom = createObject("java", "javax.mail.internet.InternetAddress").init(aFromEmailAddr);
oAddressTo = createObject("Java", "javax.mail.internet.InternetAddress").init(aToEmailAddr);
// build message
// set who the message is from
oMimeMessage.setFrom(oAddressFrom);
// add a recipient
oMimeMessage.addRecipient(oRecipientType.TO, oAddressTo);
// set the subject of the message
oMimeMessage.setSubject(aSubject);
oMimeMessage.setContent(aBody,"text/html");
oMimeMessage.saveChanges();
// create a transport to actually send the message via SMTP
oTransport = oMailSession.getTransport("smtp");
// connect to the SMTP server using the parameters supplied
//oTransport.setRequireStartTLS(true);
oTransport.setStartTLS(true);
oTransport.connect(sMailServer, sUsername, sPassword);
// send the message to all recipients
oTransport.sendMessage(oMimeMessage,oMimeMessage.getAllRecipients());
// close the transport
oTransport.close();
}

0 comments:

Post a Comment