2004/09/15

JavaMail quick start

http://www.javaworld.com/javaworld/jw-10-2001/jw-1026-javamail_p.html

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

Author
Tony Loton

Summary
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");
}

System.exit(0);
}

/**
* "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);
//sender
msg.setFrom(new InternetAddress(from));
//receiver
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
//email subject
msg.setSubject(subject);
//email content
msg.setText(body);
// -- Set some other header information --
msg.setHeader("X-Mailer", "LOTONtechEmail");
//send date
msg.setSentDate(new Date());

//send it
Transport.send(msg);

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

}

No comments: