`

commons-email笔记

阅读更多
使用Apache Commons-email发送电子邮件

所需要的jar包
  • commons-emai-1.2.jar
  • commons-logging-1.1.1.jar
  • mail.jar


如果JDK版本过低还需要
  • activation.jar


发送简单邮件
@Test
public void sendSimpleMail() throws Exception {  
	SimpleEmail email = new SimpleEmail();  
	email.setHostName("smtp.gmail.com"); // 发送服务器  
	email.setAuthentication("gaowm0207@gmail.com", "password"); // 发送邮件的用户名和密码  
	email.addTo("459978392@qq.com", "a"); // 接收邮箱  
	email.setFrom("gaowm0207@163.com", "a"); // 发送邮箱  
	email.setSubject("测试主题");// 主题  
	email.setMsg("这里是邮件内容"); // 内容  
	email.setSmtpPort(465); // 端口  
	email.setSSL(true); // gmail需要设置SSL安全设置  
	email.setCharset("GBK"); // 编码  
	email.send();  
}

谷歌邮件服务的发送邮件端口不是默认的25,而是465,所以需要在代码中设置

发送带有附件的邮件
@Test
public void sendMutiMail() throws Exception{  
	EmailAttachment attachment = new EmailAttachment();  
	attachment.setDisposition(EmailAttachment.ATTACHMENT);  
	attachment.setDescription("python resource");  
	attachment.setPath("src/com/beckham/common/email/附件.txt");
        //attachment.setURL(new URL("http://xxx/a.gif"));//远程文件  
	attachment.setName(MimeUtility.encodeText("附件.txt")) ; //设置附件的中文编码  
        
	MultiPartEmail email = new MultiPartEmail();  
	email.setHostName("smtp.163.com"); // 发送服务器  
	email.setAuthentication("gaowm0207@163.com", "password"); // 发送邮件的用户名和密码  
	email.addTo("459978392@qq.com", "a"); // 接收邮箱  
	email.setFrom("gaowm0207@163.com", "a"); // 发送邮箱  
	email.setSubject("测试主题");// 主题  
	email.setMsg("这里是邮件内容"); // 内容  
	email.setCharset("GBK"); // 编码  
	// 添加附件  
	email.attach(attachment);  
	  
	// 发送邮件  
	email.send();  
  
} 


发送Html格式的邮件
public void sendHtmlMail() throws Exception {
HtmlEmail email = new HtmlEmail();
email.setHostName("mail.fastunit.com");
email.setAuthentication("support@fastunit.com", "***");
email.setCharset("UTF-8");
email.addTo("fastunit.com@hotmail.com");
email.setFrom("support@fastunit.com", "support");
email.setSubject("subject中文");
email.setHtmlMsg("<b>msg中文</b>");
email.send();
}


官方演示
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics