使用commons mail時需要的jar包:
1,commons-email-1.1.jar
2,mail.jar
3,activation.jar
(在web應用里只需要commons-email包)
發送簡單的文字郵件:
SimpleEmail email = new SimpleEmail();

email.setHostName("smtp.sina.com");
email.setAuthentication("username", "password");//在郵件服務商處注冊的用戶名和密碼
email.addTo("mailTo@163.com");
email.setFrom("username@sina.com", "alias");

email.setCharset("UTF-8");//gbk或gb2312,只要支持中文就行
email.setSubject("title");
email.setMsg("content");
email.send();
發送帶附件的郵件:
// Create the attachment
EmailAttachment attachment = new EmailAttachment();
attachment.setPath("mypictures/john.jpg");
attachment.setDisposition(EmailAttachment.ATTACHMENT);
attachment.setDescription("Picture of John");
attachment.setName("John");

// Create the email message
MultiPartEmail email = new MultiPartEmail();
email.setHostName("mail.myserver.com");
email.setAuthentication("username", "password");
email.addTo("jdoe@somewhere.org", "John Doe");
email.setFrom("me@apache.org", "Me");
email.setCharset("UTF-8");
email.setSubject("The picture");
email.setMsg("Here is the picture you wanted");

// add the attachment
email.attach(attachment);

// send the email
email.send();
創建多個EmailAttachment對象,并調用MultiPartEmail.attach();就可以發送多個附件.
發送HTML格式的郵件:
發送html格式的郵件和簡單郵件的區別就在創建HtmlEmail對象
并用email.setHtmlMsg(String)或email.setMsg(String)把含有html標簽的字符串賦給email對象.
HtmlEmail對象還有一個setTextMsg(String)方法,這個方法參數里的html標簽會被當做普通字符處理,不會被解析成html元素.
更詳細內容可以看apache commons-email的用戶指南.