1、开启POP3/SMTP/IMAP
一般在设置中就能找到,开启后会有一串英文记得保存(只能看到这一次1哦),后面会使用
网易邮箱为例:
qq邮箱为例:
2、代码实现
以网易邮箱为例
传的参数:MailUtils.sendMail(“接受验证码的邮箱”,验证码);
需要再pom下导入(maven工程),非maven去下载这两个jar包导入即可
<!--邮箱发送-->
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>1.6.2</version>
</dependency>
代码实现如下:
package com.ch.reggie.utils;
import com.sun.mail.util.MailSSLSocketFactory;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
/**
* 邮箱发送工具类
*/
public class MailUtils {
/**
* 发送验证码
*
* @param receiveMail
* @throws Exception
*/
public static void sendMail(String receiveMail,String verifyCode) {
Properties prop = new Properties();
// 开启debug调试,以便在控制台查看
prop.setProperty("mail.debug", "true");
// 设置邮件服务器主机名
prop.setProperty("mail.host", "smtp.163.com");
// 发送服务器需要身份验证
prop.setProperty("mail.smtp.auth", "true");
// 发送邮件协议名称
prop.setProperty("mail.transport.protocol", "smtp");
// 开启SSL加密,否则会失败
try {
MailSSLSocketFactory sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
prop.put("mail.smtp.ssl.enable", "true");
prop.put("mail.smtp.ssl.socketFactory", sf);
// 创建session
Session session = Session.getInstance(prop);
// 通过session得到transport对象
Transport ts = session.getTransport();
// 连接邮件服务器:邮箱类型,帐号,POP3/SMTP协议授权码 163使用:smtp.163.com,qq使用:smtp.qq.com
ts.connect("smtp.163.com", "1、开启了POP3/SMTP协议的邮箱号", "2、要你保存的那串英文");
// 创建邮件
Message message = createSimpleMail(session, receiveMail,verifyCode);
// 发送邮件
ts.sendMessage(message, message.getAllRecipients());
ts.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* @Method: createSimpleMail
* @Description: 创建一封只包含文本的邮件
*/
public static MimeMessage createSimpleMail(Session session, String receiveMail,String verifyCode) throws Exception {
// 创建邮件对象
MimeMessage message = new MimeMessage(session);
// 指明邮件的发件人
message.setFrom(new InternetAddress("3、发件人邮箱"));
// 指明邮件的收件人
message.setRecipient(Message.RecipientType.TO, new InternetAddress(receiveMail));
// 邮件的标题
message.setSubject("验证码");
// 邮件的文本内容
message.setContent("您的验证码:" + verifyCode + ",如非本人操作,请忽略!请勿回复此邮箱", "text/html;charset=UTF-8");
// 返回创建好的邮件对象
return message;
}
}