1、引入的依赖:
import javax.mail.;*
import javax.mail.internet.;*
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
2、Controller代码:
try{
Properties props = new Properties(); //创建属性,确定链接地址
props.setProperty("mail.transport.protocol", "smtp"); // 使用的发送协议
//SMTP: Simple Mail Transfer Protocol,即简单邮件传输协议,发送邮件的协议,默认端口,25
//POP3: Post Office Protocol 3,即邮局协议,接收邮件的协议,默认端口,110
props.setProperty("mail.smtp.host", "smtp.exmail.qq.com"); // 指定smtp服务器,此处以腾讯企业邮箱为例(其他邮箱的host随便查都有,也可以在邮箱设置SMTP服务器栏里查看)
props.setProperty("mail.smtp.auth", "true"); //是否需要smtp验证
props.setProperty("mail.smtp.connectiontimeout", "10000"); //连接时间限制,默认无限
props.setProperty("mail.smtp.timeout", "5000"); //接受时间限制,默认无限
props.setProperty("mail.smtp.writetimeout", "5000"); //发送时间限制,默认无限
props.setProperty("mail.smtp.port", "25"); // 默认端口是25,部署后启用465端口 (服务器需要先开启端口)
//465端口是为SMTPS(SMTP-over-SSL)协议服务开放的,基于SSL安全协议
//SSL的非对称加密的高度安全可靠性,可防止邮件泄露。SMTPS和SMTP一样,只是更安全些
//防止发送者删除已发邮件
Session session = Session.getInstance(props); //环境信息,在session中设置账户信息,Transport发送邮件时会用
session.setDebug(true); //打印调试
Message message = new MimeMessage(session); //创建邮件
message.setSubject("主题名称占位");
message.setFrom(new InternetAddress("发件邮箱地址占位@qq.com", "发件人名称占位", "UTF-8"));
message.setReplyTo(new Address[]{new InternetAddress(邮件回复人邮件地址占位@qq.com")}); //设置邮件回复人
message.setRecipient(Message.RecipientType.TO, new InternetAddress("收件人邮箱地址占位@xx.com")); //接收者类型
//接收者类型可以是RecipientType.TO【接收人】,RecipientType.CC【抄送人】和RecipientType.BCC【秘密抄送人】
MimeMultipart msgMultipart = new MimeMultipart("mixed");//设置邮件内容,混合模式,整封邮件的MINE消息体
message.setContent(msgMultipart); //设置邮件的MINE消息体
message.setSentDate(new Date()); //设置发件时间
// 可以增加附件
// if (bytes != null && names != null) {
// for (int i = 0; i < bytes.length; i++) {
// MimeBodyPart attch = new MimeBodyPart(); // 创建附件
// msgMultipart.addBodyPart(attch); // 附件添加到MIME
// ByteArrayDataSource dataSource = new ByteArrayDataSource(bytes[i], "text/data"); //创建数据源
// attch.setDataHandler(new DataHandler(dataSource));
// attch.setFileName(names[i]);
// }
// }
message.setText("\n\t亲爱的用户:\n\n\t您好!您正在进行邮箱验证,本次请求的验证码为:" + 你所需要发送的验证码占位 + ",本验证码30分钟内有效,请勿泄露此验证码。如非本人操作,请忽略该邮件。(这是一封自动发送的邮件,请不要直接回复)\n\n\t"); //文本发送
// 可以是HTML发送
// MimeBodyPart htmlPart = new MimeBodyPart();
// msgMultipart.addBodyPart(htmlPart);
// htmlPart.setContent("您好!您正在进行邮箱验证,本次请求的验证码为:<span style=\"font-size:24px;color:#FFE500;\"> "+生成的验证码占位+"</span>", "text/html;charset=utf-8");
Transport transport = session.getTransport();
transport.connect("发件邮箱地址占位@qq.com", "发件邮箱授权码占位"); //发件地址和授权码(授权码每个类型的邮箱不同,具体怎么获取自行查询很简单)
transport.sendMessage(message, message.getAllRecipients());
transport.close();
} catch (Exception e){
e.printStackTrace();
}