环境
1.编译工具:eclipse
2.运行环境:java1.8,tomcat9
3.需要导入的包:commons-email-1.5.jar、mail.jar、activation.jar
4.jar包下载路径:链接:https://pan.baidu.com/s/1krOeoLu-dXaX3b10md8aDQ
提取码:rktq
总结
通过对下面两种发送邮件方法的实现,推荐第二种。因为经过实践,发现第一种方法发送邮件,邮件会被放入垃圾邮箱中(阿里云个人邮箱),且第一种发送在部分邮箱中存在延迟的问题(163邮箱)。
经过测试发送者邮箱为QQ邮箱时:方法二可以给qq邮箱、163邮箱、阿里云个人邮箱发送
实现
在eclipse的WebContent/WEB-INF/lib中添加上述三个jar包,并加入到编译环境当中
工具类:
package net.common.util;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.SimpleEmail;
public class MailUtil {
/**
* 1.通过java.mail发送
* @param smtpHost 协议名称
* @param username 发送者邮箱
* @param password 授权码
* @param to 接收者邮箱
* @param title 标题
* @param content 内容
* @throws MessagingException
*/
public static void sendMailByJavaMail(String smtpHost, String username,
String password, String to, String title, String content)
throws MessagingException {
// 创建一个session
Session session = Session.getDefaultInstance(new Properties());
// 一条邮件(消息)
Message mailMessage = new MimeMessage(session);
// 设置发件人
mailMessage.setFrom(new InternetAddress(username));
// 设置邮件标题
mailMessage.setSubject(title);
// 设置邮件内容
mailMessage.setText(content);
Transport trans = null;
try {
trans = session.getTransport("smtp");
trans.connect(smtpHost, username, password);
trans.sendMessage(mailMessage, InternetAddress.parse(to));
} catch (MessagingException e) {
throw e;
} finally {
if (trans != null) {
try {
trans.close();
} catch (Exception e) {
}
}
}
}
/**
* 2.利用commons.mail发送
* @param smtpHost 简单邮件协议名称
* @param username 发送者邮箱
* @param password 密码
* @param to 接收者邮箱
* @param title 标题
* @param content 内容
* @throws EmailException
*/
public static void sendMailByCommonsEmail(String smtpHost, String username,
String password, String to, String title, String content)
throws EmailException {
SimpleEmail email = new SimpleEmail();
email.setHostName(smtpHost);
email.setAuthentication(username, password);
email.addTo(to);
email.setFrom(username);
email.setSubject(title);
email.setMsg(content);
email.send();
}
}
测试类
package net.smartschool.test;
import java.io.IOException;
import net.common.util.MailUtil;
public class T2 {
public static void main(String[] args) throws IOException {
try {
//方法一的实现
MailUtil.sendMailByJavaMail("smtp.qq.com","发送者邮箱","发送者邮箱的授权码","接受者邮箱","标题1","内容1");
//方法二的实现
MailUtil.sendMailByCommonsEmail ("smtp.qq.com","发送者邮箱","发送者邮箱的授权码","接受者邮箱","标题2","内容2");
//如果发送者是QQ邮箱,简单邮箱协议为smtp.qq.com,如果是163邮箱,协议为smtp.163.com
} catch (Exception e) {
e.printStackTrace();
}
}
}
关于如何开启POP3/SMTP服务参考:https://blog.csdn.net/Garnett_zk/article/details/100102381