以前學習了發送文本郵件、帶附件郵件,如今來看看發送HTML郵件。html
前期工做請參考:使用JavaMail發送郵件之發送文本郵件java
主要代碼以下:apache
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(); } } }