mashiguang

小马快跑

  BlogJava :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理 ::
  20 随笔 :: 0 文章 :: 60 评论 :: 0 Trackbacks

使用commons mail时需要的jar包:
1,commons-email-1.1.jar
2,mail.jar
3,activation.jar
(在web应用里只需要commons-email包)

发送简单的文字邮件:

SimpleEmail email = new SimpleEmail();

email.setHostName(
"smtp.sina.com");
email.setAuthentication(
"username""password");//在邮件服务商处注册的用户名和密码
email.addTo("mailTo@163.com");
email.setFrom(
"username@sina.com""alias");

email.setCharset(
"UTF-8");//gbk或gb2312,只要支持中文就行
email.setSubject("title");
email.setMsg(
"content");
email.send();

发送带附件的邮件:
// Create the attachment
EmailAttachment attachment = new EmailAttachment();
attachment.setPath(
"mypictures/john.jpg");
attachment.setDisposition(EmailAttachment.ATTACHMENT);
attachment.setDescription(
"Picture of John");
attachment.setName(
"John");

// Create the email message
MultiPartEmail email = new MultiPartEmail();
email.setHostName(
"mail.myserver.com");
email.setAuthentication(
"username""password");
email.addTo(
"jdoe@somewhere.org""John Doe");
email.setFrom(
"me@apache.org""Me");
email.setCharset(
"UTF-8");
email.setSubject(
"The picture");
email.setMsg(
"Here is the picture you wanted");

// add the attachment
email.attach(attachment);

// send the email
email.send();

创建多个EmailAttachment对象,并调用MultiPartEmail.attach();就可以发送多个附件.

发送HTML格式的邮件:

发送html格式的邮件和简单邮件的区别就在创建HtmlEmail对象
并用email.setHtmlMsg(String)或email.setMsg(String)把含有html标签的字符串赋给email对象.
HtmlEmail对象还有一个setTextMsg(String)方法,这个方法参数里的html标签会被当做普通字符处理,不会被解析成html元素.
更详细内容可以看apache commons-email的用户指南.

posted on 2007-11-01 16:51 mashiguang 阅读(1500) 评论(4)  编辑  收藏 所属分类: java web开发

评论

# re: apache commons-email 2007-11-01 16:54 mashiguang
在使用中碰到的问题:
发送HTML格式的邮件时同时发送附件的话,邮件内容会被当作附件处理,也就是说如果你发了两个附件和一篇HTML格式的正文,收件人会收到三个附件,前两个是正常的附件,HTML格式的正文变成了第三个附件,碰到同样问题的朋友请指点.   回复  更多评论
  

# re: apache commons-email 2007-12-20 15:02 fasdf
fasdfasdfasdfsadf  回复  更多评论
  

# re: apache commons-email 2008-01-02 15:21 ajax_milan
文中提到的发送中文的方法不行,建议使用如下方法:
1.去掉email.setCharset("UTF-8");
2.不使用email.setMsg("Here is the picture you wanted");
3.使用email.setContent("这是一个测试","text/plain;charset=GBK");  回复  更多评论
  

# re: apache commons-email[未登录] 2014-06-17 10:57 w
setMsg和setHtmlMsg有什么区别啊?  回复  更多评论
  


只有注册用户登录后才能发表评论。


网站导航: