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

前期工作请参考:

 

主要代码如下:

 

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 stubtry {// Create the email messageHtmlEmail 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 idURL url = new URL("http://www.apache.org/p_w_picpaths/asf_logo_wide.gif");String cid = email.embed(url, "Apache logo");// set the html messageemail.setHtmlMsg("The apache logo - ");// set the alternative messageemail.setTextMsg("Your email client does not support HTML messages");// send the emailemail.send();} catch (EmailException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (MalformedURLException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}