使用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 = "[email protected]";
String username = "[email protected]";
String password = "1235";
// 接收者邮箱
String to = "[email protected]";
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("这是封测试附件邮件"); /* 邮件内容 */

// 添加附件对象
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.(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就行了

你可能感兴趣的:(使用apache.commons.mail包发送邮件)