Become a fan
Twitter
Home

How to: Send Mail Over SMTPS In Java

Author Joseph Stenhouse on November 27, 2010 | | |


Introduction

This tutorial will show you how to send mail in Java over SMTPS. SMTP, or Simple Mail Transfer Protocol, is the de facto standard for email transmissions across the internet. The SSL protocol, or Secure Socket Layer, provides an encrypted, secure connection. Many providers try to use this secure version of smtp and I encourage everyone to make use of it.

Example code

In the example given, we will use the smtps server of Google. To use this server, you will need a Gmail account. The example makes use of the fictive email account ‘mail@gmail.com’ with ‘password’ and the JavaMail library.

import java.util.Properties;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import com.sun.mail.smtp.SMTPSSLTransport;


 

public static void sendMail(String to, String from, String subject, Multipart content) {
try {
// create properties
Properties props = System.getProperties();
// < -- authorization, i.e. account &amp; password is required -->
props.put("mail.smtps.auth", "true");
// < -- it is important you use the correct port. smtp uses 25, smtps 465 -->
props.put("mail.smtps.port", "465");
// < -- put the smtps server host address here -->
props.put("mail.smtps.host", "smtp.gmail.com");
 
// create session
Session session = Session.getDefaultInstance(props);
session.setDebug(true);
 
// create content
MimeMultipart msgContent = new MimeMultipart("alternative");
 
// Text Mail
MimeBodyPart html = new MimeBodyPart();
// < -- we will send plain text, "text/html" is possible as well -->
html.setContent(content, "text/plain");
html.setHeader("MIME-Version", "1.0");
html.setHeader("Content-Type", "text/plain; charset=iso-8859-1");
msgContent.addBodyPart(html);
MimeMessage msg = new MimeMessage(session);
msg.setContent(content);
// set sender and recipient
msg.setFrom(new InternetAddress(from));
msg.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
msg.setSubject(subject);
 
// transport the message
// < -- we will send the message over smtps -->
SMTPSSLTransport transport = (SMTPSSLTransport)session.getTransport("smtps");
 
// connect to server
// < -- fill in gmail email address and password -->
transport.connect("smtp.gmail.com", "mail@gmail.com", "password");
 
// send the message
transport.sendMessage(msg, msg.getAllRecipients());
// close the connection
transport.close();
} catch> (Exception e) {
e.getStackTrace();
return;
}
}



Original Article (Connect)

Was this article helpful?http://www.involutionmedia.com/kbase/index.php

Was this article helpful?

Yes No

Category: Java

Last updated on November 29, 2010 with 5122 views