之前学习了发送文本邮件、带附件邮件,现在来看看发送HTML邮件。

前期工作请参考:使用JavaMail发送邮件之发送文本邮件

 

主要代码如下:

 

import java.net.MalformedURLException;
import java.net.URL;
import org.apache.commons.mail.DefaultAuthenticator;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.HtmlEmail;
public class HtmlTest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
// Create the email message
HtmlEmail email = new HtmlEmail();
//邮件服务器
email.setHostName("smtp.126.com");
//端口号
email.setSmtpPort(25);
//用户名、密码
email.setAuthenticator(new DefaultAuthenticator("yuke198907@126.com", "密码你懂的"));
email.setSSLOnConnect(true);
//收件人
email.addTo("yuke@iisant.com", "yuke");
//发件人
email.setFrom("yuke198907@126.com", "yuke198907");
//标题
email.setSubject("Test email with inline p_w_picpath");
// embed the p_w_picpath and get the content id
URL url = new URL("http://www.apache.org/p_w_picpaths/asf_logo_wide.gif");
String cid = email.embed(url, "Apache logo");
// set the html message
email.setHtmlMsg("<html>The apache logo - <img src=\"cid:"+cid+"\"></html>");
// set the alternative message
email.setTextMsg("Your email client does not support HTML messages");
// send the email
email.send();
} catch (EmailException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}