使用apache.commons.mail包发送邮件

使用apache包发邮件,首先需要包commons-email-1.0.jar,mail.jar,activation.jar

import org.apache.commons.mail.*;


public class Test {

/**
* @param args
*/
public static void main(String[] args) throws Exception{
Test as = new Test();
String host = "core.gov.cn";
String from = "service@core.gov.cn";
String username = "service@core.gov.cn";
String password = "1235";
// 接收者邮箱
String to = "334508748@qq.com";
String subject = "测试主题!";
String mailConent = "测试邮件";
// 调用发送附件邮件方法
as.sendAttachmentMail(host, from, username, password, to, subject,
mailConent);
}

public boolean sendAttachmentMail(String host, String from,
String username, String password, String to, String subject,
String mailConent) throws Exception {
// 创建附件对象
EmailAttachment attachment = new EmailAttachment();
/* 附件的地址 */
attachment.setPath("E://octavia_2013.pdf");
// 设定为附件
attachment.setDisposition(EmailAttachment.ATTACHMENT);
/* 附件的描述 */
attachment.setDescription("jPortMap项目设计附件文档");
/* 附件的名称,必须和文件名一致 */
attachment.setName("Eclipse中文教程.pdf");
/* new一个HtmlEmail发送对象 */
HtmlEmail email = new HtmlEmail();
email.setAuthentication(username, password);
email.setHostName(host);
email.addTo(to, from);
email.setFrom(from);
email.setSubject(subject);
// 注意,发送内容时,后面这段会让中文正常显示,否则乱码
email.setCharset("UTF-8");
email.setHtmlMsg("<html>这是封测试附件邮件</html>"); /* 邮件内容 */

// 添加附件对象
email.attach(attachment);
// 发送
email.send();
System.out.println("带附件的邮件发送成功!");
return true;
}

}



如需要报错
Exception in thread "main" java.lang.NoClassDefFoundError: com/sun/mail/util/LineInputStream
at javax.mail.internet.MimeUtility.<clinit>(MimeUtility.java:1161)
at javax.mail.internet.InternetAddress.setPersonal(InternetAddress.java:216)
at org.apache.commons.mail.Email.createInternetAddress(Email.java:422)
at org.apache.commons.mail.Email.addTo(Email.java:490)
at com.test.Test.sendAttachmentMail(Test.java:43)
at com.test.Test.main(Test.java:22)

解决方案:将Java EE 5 Library替换成J2EE 1.4 Library就行了
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值