使用commons mail時(shí)需要的jar包:
1,commons-email-1.1.jar
2,mail.jar
3,activation.jar
(在web應(yīng)用里只需要commons-email包)
發(fā)送簡(jiǎn)單的文字郵件:
SimpleEmail email = new SimpleEmail();

email.setHostName("smtp.sina.com");
email.setAuthentication("username", "password");//在郵件服務(wù)商處注冊(cè)的用戶名和密碼
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();
發(fā)送帶附件的郵件:
// 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();
創(chuàng)建多個(gè)EmailAttachment對(duì)象,并調(diào)用MultiPartEmail.attach();就可以發(fā)送多個(gè)附件.
發(fā)送HTML格式的郵件:
發(fā)送html格式的郵件和簡(jiǎn)單郵件的區(qū)別就在創(chuàng)建HtmlEmail對(duì)象
并用email.setHtmlMsg(String)或email.setMsg(String)把含有html標(biāo)簽的字符串賦給email對(duì)象.
HtmlEmail對(duì)象還有一個(gè)setTextMsg(String)方法,這個(gè)方法參數(shù)里的html標(biāo)簽會(huì)被當(dāng)做普通字符處理,不會(huì)被解析成html元素.
更詳細(xì)內(nèi)容可以看apache commons-email的用戶指南.