package service;
import com.sun.mail.util.MailSSLSocketFactory;
import javax.mail.Message;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
public class EmailBox {
//根据需要输入参数,我这里用到两个
public String mail(String a , String b) {
// JDK9以上或JDK6以下使用mail.jar包不加JAF的activation.jar包会抛出该错误!JDK6以上不需要加该jar包;
String email = a;
String num = b;
//随机数拼成验证码
// for (int i &#61; 0; i <6; i&#43;&#43;) {
// int n &#61; (int) (Math.random() * 10);
// num &#61; num &#43; Integer.toString(n);
// }
Properties prop &#61; new Properties();
开启debug调试&#xff0c;以便在控制台查看
// prop.setProperty("mail.debug", "true");
// 设置邮件服务器主机名&#xff0c;这里用QQ邮箱
prop.setProperty("mail.host", "smtp.qq.com");
// 发送服务器需要身份验证
prop.setProperty("mail.smtp.auth", "true");
// 发送邮件协议名称
prop.setProperty("mail.transport.protocol", "smtp");
try {
// 开启SSL加密&#xff0c;否则会失败
MailSSLSocketFactory sf &#61; new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
prop.put("mail.smtp.ssl.enable", "true");
prop.put("mail.smtp.ssl.socketFactory", sf);
// 创建session
Session session &#61; Session.getInstance(prop);
// 通过session得到transport对象
Transport ts &#61; session.getTransport();
// 连接邮件服务器&#xff1a;邮箱类型&#xff0c;帐号&#xff0c;授权码代替密码&#xff08;更安全&#xff09;
ts.connect("smtp.qq.com", "这里填写QQ帐号", "这里填写QQ安全登陆码");//后面的字符是授权码&#xff0c;用qq密码反正我是失败了&#xff08;用自己的&#xff0c;别用我的&#xff0c;这个号是我瞎编的&#xff0c;为了。。。。&#xff09;
// 创建邮件
MimeMessage message &#61; createSimpleMail(session, email, num);
// 发送邮件
ts.sendMessage(message, message.getAllRecipients());
ts.close();
return "发送成功&#xff01;";
} catch (Exception e) {
e.printStackTrace();
return "发送失败&#xff01;";
}
}
public static MimeMessage createSimpleMail(Session session, String email, String num)
throws Exception {
// 创建邮件对象
MimeMessage message &#61; new MimeMessage(session);
// 指明邮件的发件人
message.setFrom(new InternetAddress("这里填写我的QQ邮箱&#xff0c;例如xxxxxxxxx&#64;qq.com"));
// 指明邮件的收件人&#xff0c;现在发件人和收件人是一样的&#xff0c;那就是自己给自己发
message.setRecipient(Message.RecipientType.TO, new InternetAddress("这里填写你要发送的邮箱&#xff0c;如xxxxxxx&#64;qq.com"));
// 邮件的标题
message.setSubject("这里填写要发送的邮件标题");
// 邮件的文本内容
message.setContent("这里填写要发送的邮件内容" , "text/html;charset&#61;UTF-8");
// 返回创建好的邮件对象
return message;
}
}