JavaMail quick start


Spend some time to study this piece of information for a while, you can pick up the JavaMail API quickly.

Tony Loton

In this article, Tony Loton shows the first steps on the road to building Java-based email applications. If you fancy building your own email client to replace Microsoft Outlook, or a Web-based email system to rival Hotmail, this is the place to start. And for a different perspective on JavaMail's possibilities, Tony presents a novel talking-email client application

[Sample Code]

import javax.mail.*;
import javax.mail.internet.*;

import java.util.*;

* A simple email sender class.
public class SimpleSender {

* Main method to send a message given on the command line.
public static void main(String args[]) {
try {
String smtpServer = "so-net.net.tw";
String to = "email address1, email address2";
String from = "email address";
String subject = "test";
String body = "JavaMail Test";

send(smtpServer, to, from, subject, body);
catch (Exception ex) {
System.err.println("Usage: java com.lotontech.mail.SimpleSender"
" smtpServer toAddress fromAddress subjectText bodyText");


* "send" method to send the message.
public static void send(String smtpServer, String to, String from
, String subject, String body) {
try {

Properties props = System.getProperties();

// -- Attaching to default Session, or we could start a new one --
props.put("mail.smtp.host", smtpServer);
Session session = Session.getDefaultInstance(props, null);

//create new mail
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(from));
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
//email subject
//email content
// -- Set some other header information --
msg.setHeader("X-Mailer", "LOTONtechEmail");
//send date
msg.setSentDate(new Date());

//send it

System.out.println("Message sent OK.");
catch (Exception ex) {


No comments: