<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.3.1</version>
<scope>compile</scope>
</dependency>
package ncc.email.email.Utils;
/*
注册得时候使用
步骤:
1 设置邮件发送的属性
2 设置主机地址
3 设置是否打开验证
4 创建链接
5 创建邮件
6 设置发送者
7 设置接受者
8 设置标题
9 设置正文
10 发送
*/
import org.junit.jupiter.api.Test;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
import java.util.Random;
public class SendMail {
public static String smtp_host = "smtp.163.com"; //网易
public static String username = "18154183997@163.com"; //邮箱
public static String password = "XXXXXXX"; //授权码(登录邮箱-->设置-->邮箱安全设置-->客户端授权密码),这里不是邮箱的密码,切记!
public static String from = "18154183997@163.com"; //来源邮箱,使用当前账号
public static String activeUrl = "http://localhost:8080/"; //激活地址
public static void sendMail(String to,String subject,String text) throws Exception {
//1 准备发送邮件需要的参数
Properties props = new Properties();
//设置主机地址 smtp.qq.com smtp.126.com smtp.163.com
props.put("mail.smtp.host", smtp_host);
//是否打开验证:只能设置true,必须打开
props.put("mail.smtp.auth", true);//添加这句 防止553得自我验证验证
props.setProperty("mail.smtp.auth", "true");
//2 连接邮件服务器(与服务器建立会话)
Session session = Session.getDefaultInstance(props);
//3 创建邮件信息
MimeMessage message = new MimeMessage(session);
//4 设置发送者
InternetAddress fromAddress = new InternetAddress(from);
message.setFrom(fromAddress);
//5 设置接收者
InternetAddress toAddress = new InternetAddress(to);
// to:直接接收者 cc:抄送 bcc暗送
message.setRecipient(MimeMessage.RecipientType.TO, toAddress);
//6 设置主题
message.setSubject(subject);
//7 设置正文
message.setText(text);
//设置HTML方式发送
message.setContent(text,"text/html;charset=utf-8");
//8 发送:
Transport transport = session.getTransport("smtp");//参数不能少,表示的是发送协议
//登录邮箱,此处的密码是授权码
transport.connect(username, password);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
}
// 随机验证码
public static String achieveCode() { //由于数字1 和0 和字母 O,l 有时分不清,所有,没有字母1 、0
String[] beforeShuffle= new String[] { "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F",
"G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "a",
"b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
"w", "x", "y", "z" };
StringBuffer sb = new StringBuffer();
Random rand=new Random();
for (int i = 0; i < 4; i++) {
sb.append(beforeShuffle[rand.nextInt(beforeShuffle.length)]); //随机获取4位
}
return sb.toString();
}
@Test
public void test() throws Exception {
//验证码发送到对方的邮箱,本地用session存储验证码,以待确认
String mesg="尊敬的用户:你好!n xxx.验证码为:" + SendMail.achieveCode()+" (有效期为一分钟)";
SendMail.sendMail("1114217951@qq.com","激活测试", mesg);
System.out.println("发送邮件成功");
}
}