package com.hzk.mail;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.commons.mail.EmailAttachment;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.HtmlEmail;
/***
* HtmlEmail 用于发送HTML格式的邮件。完全的兼容MultiPartEmail, 易于添加附件,同时也支持内嵌图像
* MultiPartEmail 用于发送带附件的或者内嵌形式的邮件
* @author Administrator
*
*/
public class MailTest2 {
public static void main(String[] args) {
try {
//Create the attachment 创建附件1
//System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
EmailAttachment attachment1 = new EmailAttachment();
attachment1.setURL(new URL("http://www.apache.org/images/asf_logo_wide.gif")); // 发送网络文件
attachment1.setDisposition(EmailAttachment.ATTACHMENT);
attachment1.setDescription("apache logo");
attachment1.setName("apache logo");
//Create the attachment 创建附件2
EmailAttachment attachment2 = new EmailAttachment(); //发送本地文件
attachment2.setPath("img/qq_znone.gif");//不支持png格式的图片
attachment2.setDisposition(EmailAttachment.ATTACHMENT);
attachment2.setDescription("qq znone logo");
attachment2.setName("qq znone logo");
//Create the mail message
HtmlEmail htmlEmail = new HtmlEmail();
htmlEmail.setHostName("smtp.163.com");//你的邮件服务器的地址
htmlEmail.setAuthentication("tjhouzhikai", "757583770");//如果你的邮件服务器设置了密码,请输入密码,否则此语句可以忽略
htmlEmail.addTo("china_houzhikai@163.com", null);//设置收件人,如果想添加多个收件人,将此语句多写几次即可。
//其中参数1,代表收件人邮件地址;
//参数2,用于收件人收到邮件时看到的收件人姓名
htmlEmail.setFrom("tjhouzhikai@163.com", "张三");//发件人
htmlEmail.setCharset("UTF-8");
htmlEmail.setSubject("带图片和附件的java测试");
htmlEmail.setMsg("hello wellcome");
URL url = new URL("http://www.apache.org/images/asf_logo_wide.gif");
String cid = htmlEmail.embed(url, "Apache logo");
String testEditor = "亲 你想登录qq空间吗?想的话就<a href='http://qzone.qq.com/'> 点击 </a>"+
"<br />"+
"<html>" +
"<img src=\"cid:"+cid+"\">" +
"<br />" +
"<iframe src='http://i.qq.com' height='100' scrolling='auto' width='50%' frameborder='1'></iframe>" +
"</html>";///关于iframe :出于安全考虑,大多邮箱是不支持iframe框架或javascript脚本内容的,也就是说,你就算成功把内容发给别人,对方邮箱不一定能把内容显示出来,例如发给qq、163、126等主流邮箱就不行,会显示空白。
htmlEmail.setHtmlMsg(testEditor);//testEditor 变量包含html内容
htmlEmail.attach(attachment1);//添加 --附件 1
htmlEmail.attach(attachment2);//添加 --附件 2
htmlEmail.send();//发送邮件
System.out.println("发送成功!");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (EmailException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
邮件箱截图如下:
=======================================================================================================================================