第一步:引入工具类
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;
/**
* 发送邮件的工具类
*/
public class MailUtils {
public static void sendMail(String email, String emailMsg) throws AddressException, MessagingException {
// 1.创建一个程序与邮件服务器会话对象 Session
Properties props = new Properties();
props.setProperty("mail.transport.protocol", "SMTP"); //需要开启163邮箱的这几个地方
props.setProperty("mail.host", "smtp.163.com");
// props.setProperty("mail.smtp.port", "465");
props.setProperty("mail.smtp.auth", "true");// 指定验证为true
// 创建验证器
Authenticator auth = new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("11@163.com", "11"); //指定你的客户端授权码 ,在163邮箱上进行设置
}
};
Session session = Session.getInstance(props, auth);
// 2.创建一个Message,它相当于是邮件内容
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("18337281624@163.com")); // 设置发送者邮箱
message.setRecipient(RecipientType.TO, new InternetAddress(email)); // 设置发送方式与接收者
message.setSubject("用户激活");
// message.setText("这是一封激活邮件,请<a href='#'>点击</a>");
message.setContent(emailMsg, "text/html;charset=utf-8");
// 3.创建 Transport用于将邮件发送
Transport.send(message);
}
public static void main(String[] args) throws AddressException, MessagingException {
MailUtils.sendMail("111@qq.com", "12345");
}
}
第二步: 开启邮箱的这几个地方


如果你是第一会让你发送一个短信 设置客户端授权码 好像是 ,
你设置一个授权码 用在· 下面的这个方法上
PasswordAuthentication("11@163.com", "11");
第三步:设置表单
有个邮箱输入 邮箱 和激活码 的文本框
第四步:直接在service中调用这个方法,然后就会在你接收的邮箱中发送激活码 也就是 下面的123456

执行结果:
