您的位置:首页 > 编程语言 > Java开发

java - HtmlEmail发送html邮件

2011-09-13 16:23 399 查看
之前没做过用JavaMail来发送邮件,在网上搜索点资料,自己写了2方法测试了下:
在自己的项目中,引入三个包 mail.jar ,commons-email-X.X.jar ,activation.jar。下载地址
http://u.115.com/file/bhaewa0d

下面是我的代码类:

public class EmailMain {

/**

* 方法测试一个简单拼凑的html

*/

public static void send() {

try {

HtmlEmail email = new HtmlEmail();

email.setHostName("smtp.163.com");// 发送方smtp

email.setAuthentication("username", "password");//发送方的邮箱用户名,密码

email.addTo("address", "username");//接受方的邮箱地址,邮箱用户名

email.setFrom("address@163.com", "username");//发送方的邮箱地址,邮箱用户名

email.setSubject("主题:该邮件包括html格式内容");

email.setCharset("UTF-8");// 编码格式

// 注意这里:embed 将帮助我们创建标签如:cid:xxx url

URL url = new URL("http://www.redbutton.cn/rb/images/3q.jpg");

String cid = email.embed(url, "Apache logo");

/**

* 我们看到HtmlEmail extends

* Email的,它依然有setMsg(),但是这里发送的邮件包括了插入在邮件内容中的图片,

* 所以不能在使用了setMsg(),而要以setHtmlMsg 或setTextMsg代码

**/

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");

// set mail

email.send();

} catch (Exception e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

/**

* 测试读取本地html页面,发送邮件(页面内容过多,最好用此方法)

*/

public static void sendFileContext() {

try {

HtmlEmail email = new HtmlEmail();

email.setHostName("smtp.163.com");// 发送方smtp

email.setAuthentication("username", "password");//发送方的邮箱用户名,密码

email.addTo("address", "username");//接受方的邮箱地址,邮箱用户名

email.setFrom("address@163.com", "username");//发送方的邮箱地址,邮箱用户名

email.setSubject("主题:该邮件包括html格式内容");

File file = new File(

"D:\\Documents and Settings\\wanghuijiao\\textSendEmail.jsp");

BufferedReader reader = null;

StringBuilder msg = new StringBuilder("");

try {

reader = new BufferedReader(new FileReader(file));

String tempString = null;

while ((tempString = reader.readLine()) != null) {

msg.append(tempString);

}

} catch (Exception e) {

}

String message = msg.toString();

message = new String(message.getBytes("utf-8"), "ISO-8859-1");// 处理中文乱码转码

email.setHtmlMsg(message);

email.send();

} catch (Exception e) {

e.printStackTrace();

}

}

public static void main(String[] arg) {

sendFileContext();

}

textSendEmail.jsp內容如下:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html> <body> <div id="zxgg_div" style="text-align: center;"> <h1>测试成功了,wowo?~~~~~~</h1>

<img id="gg_bb" src="http://www.redbutton.cn/rb/images/3q.jpg"/>

<a style="color:red" href="http://www.redbutton.cn/rb/contact.html">www.redbutton.cn</a>

</div> </body> </html>

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: