准备:qq邮箱、邮箱授权码
邮箱授权码生成方式:
进去qq邮箱网页版,设置->账户-> POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服务,开启所有服务后生成授权码。
至此准备工作完成。
下面上代码:
pom.xml文件中添加以下依赖:
<!--邮箱支持 https://mvnrepository.com/artifact/com.sun.mail/javax.mail -->
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>1.6.1</version>
</dependency>
代码很简单,直接封装成一个工具类,提供一个发送的方法即可
import com.sun.mail.util.MailSSLSocketFactory;
import javax.mail.*;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.security.GeneralSecurityException;
import java.util.Properties;
public class SendEmailUtil {
private static String account = "发送者@qq.com";//发送邮件的邮箱
private static String auth_code = "ohtafslvpdlvbifg";//邮箱授权码
/**
* 发送邮件
*
* @param receiver 接收邮件的邮箱
* @param title 邮件的标题
* @param content 邮件的内容 支持html代码串
* @throws GeneralSecurityException
* @throws MessagingException
*/
public static void send(String receiver, String title, String content) {
//创建新线程来发送邮件,避免阻塞主线程(发送比较耗时,使用主线程会需要几秒的等待,体验不好)
new Thread(new Runnable() {
@Override
public void run() {
try {
//创建一个配置文件并保存
Properties properties = new Properties();
properties.setProperty("mail.host", "smtp.qq.com");
properties.setProperty("mail.transport.protocol", "smtp");
properties.setProperty("mail.smtp.auth", "true");
//QQ存在一个特性设置SSL加密
MailSSLSocketFactory sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
properties.put("mail.smtp.ssl.enable", "true");
properties.put("mail.smtp.ssl.socketFactory", sf);
//创建一个session对象
Session session = Session.getDefaultInstance(properties, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(account, auth_code);
}
});
//开启debug模式
session.setDebug(true);
//获取连接对象
Transport transport = session.getTransport();
//连接服务器
transport.connect("smtp.qq.com", account, auth_code);
//创建邮件对象
MimeMessage mimeMessage = new MimeMessage(session);
//邮件发送人
mimeMessage.setFrom(new InternetAddress(account));
//邮件接收人
mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(receiver));
//邮件标题
mimeMessage.setSubject(title);
//邮件内容
mimeMessage.setContent(content, "text/html;charset=UTF-8");
//发送邮件
transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
//关闭连接
transport.close();
} catch (GeneralSecurityException e) {
e.printStackTrace();
} catch (AddressException e) {
e.printStackTrace();
} catch (NoSuchProviderException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
}
}
}).start();
}
//发送测试
public static void main(String[] args) {
SendEmailUtil.send("接收者@qq.com", "邮箱主题", "邮件内容<p>Hello</p><a href='http://fx7.top'>Hello 人家故里</a>");
}
}
优化:可将邮箱和授权码等常修改的字符串放到配置一个配置文件中,取消发送方法的static属性,将类交给spring来管理