引入maven
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-email</artifactId>
<version>1.4</version>
</dependency>
发送邮件的测试类 TestCommonsEmail.java
package com.liqiye.test;
import org.apache.commons.mail.*;
import org.apache.log4j.Logger;
import org.junit.Test;
/**
* @author liqiye
* @description 测试 apache Common Email 发送邮件
* @date 2019/2/28
*/
public class TestCommonsEmail {
private static Logger log = Logger.getLogger(TestCommonsEmail.class.getClass());
// 发送普通文本邮件
@Test
public void sendTextEmail(){
SimpleEmail email = new SimpleEmail();
// 设置使用发电子邮件的邮件服务器,这里以qq邮箱为例(其它例如:【smtp.163.com】,【smtp.sohu.com】)
email.setHostName("smtp.qq.com");
try {
// email.setSmtpPort(465); // 可以自定义端口
email.setCharset("utf-8");
// 收件人邮箱
email.addTo("1159140456@qq.com");
// 邮箱服务器身份验证 发件人的邮箱和授权码,不是邮箱密码!
// 是在邮箱设置里,允许第三方客户端登录而获取的授权码,每个邮箱账号开启服务后获取的,可以一直使用
email.setAuthentication("1159140456@qq.com", "开启服务的密码");
// 发件人邮箱
email.setFrom("1159140456@qq.com");
// 邮件主题
email.setSubject("测试邮件2");
// 邮件内容
email.setMsg("测试内容");
// 发送邮件
email.send();
} catch (EmailException ex) {
ex.printStackTrace();
log.info("发送文本邮件错误");
}
}
// 发送附件邮件
@Test
public void sendFileEmail(){
try{
// 附件对象 封装好附件内容在放进 MultiPartEmail 邮件对象
EmailAttachment attachment = new EmailAttachment();
// 附件路径 可以是网络url ,这里的名字没用的,只是起读取文件的作用,收到的邮件附件名字不是这个
attachment.setPath("F:/截图.png");
attachment.setDisposition(EmailAttachment.ATTACHMENT);
// 附件的描述
attachment.setDescription("附件描述");
// 附件的名字,这里实际情况是获取读取文件的名字连同后缀名写进去
attachment.setName("截图.png");
// 附件email对象
MultiPartEmail email = new MultiPartEmail();
// 记得这不是邮箱密码,是在邮箱设置那里开启SMTP服务返回的密码
email.setAuthentication("1159140456@qq.com", "开启服务的密码");
// 记得不用邮箱类型这个值不一样
email.setHostName("smtp.qq.com");
// 收件人邮箱
email.addTo("1159140456@qq.com");
// 发件人邮箱
email.setFrom("1159140456@qq.com");
// 邮件主题
email.setSubject("测试邮件3");
// 邮件内容
email.setMsg("测试内容");
// 添加附件
email.attach(attachment);
// 发送邮件
email.send();
} catch (EmailException ex) {
ex.printStackTrace();
log.info("发送附件邮件错误");
}
}
// 发送html邮件 就是邮件内容以html格式写入,以html显示,邮件内容可以像html页面那样,有字体样式,有图片等
@Test
public void sendHTMLEmail(){
try {
HtmlEmail email = new HtmlEmail();
// 设置使用发电子邮件的邮件服务器,这里以qq邮箱为例(其它例如:【smtp.163.com】,【smtp.sohu.com】)
email.setHostName("smtp.qq.com");
email.setCharset("utf-8");
// 收件人邮箱
email.addTo("1159140456@qq.com");
// 发件人邮箱
email.setFrom("1159140456@qq.com");
email.setAuthentication("1159140456@qq.com", "开启服务的密码");
// 邮件主题
email.setSubject("测试邮件");
// 写入html格式的内容,一般可以结合富文本编辑器ckeditor来使用
email.setHtmlMsg("<html><span style=\"color: red\"><strong>邮件内容</strong></span></html>");
// 发送邮件
email.send();
} catch (EmailException ex) {
ex.printStackTrace();
log.info("发送文本邮件错误");
}
}
}