一.进入发送者邮箱设置参数,这里以qq邮箱为例:
开启服务:
需要发送验证码:
授权码就是登入邮箱的密码:
导入邮件Jar包:
自己网上下载
邮件发送工具包 MailUtils.java
package com.common.utils;
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;
/**
*
* @ClassName: MailUtils
* @Description: 发送邮件辅助类
* @date 2018年09月5日 下午4:17:25
*
*/
public class MailUtils {
public static void main(String[] args) {
try {
//接收者的邮箱账号,与发送的内容
sendMail(" ******@qq.com","这是一封激活邮件,请<a href='https://www.baidu.com'>
点击</a>");
} catch (AddressException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
*
* @Title: sendMail
* @Description: 实现发送邮件
* @param email:接收邮件的地址
* @param emailMsg:发送邮件的内容
* @throws AddressException
* @throws MessagingException
*/
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");
//qq邮箱设置
props.setProperty("mail.host", "smtp.qq.com");
props.setProperty("mail.smtp.auth", "true");// 指定验证为true
// 创建验证器
Authenticator auth = new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
//自己的邮箱账号和密码(发送者){qq邮箱开启pop3/smtp时会给你一个授权码此授权码就是你登
入邮箱的密码}
return new PasswordAuthentication("qq账号@开始后面都不要,很纯的qq号即可", "qq邮箱开
启pop3/smtp时会给你一个授权码");//授权码
}
};
Session session = Session.getInstance(props, auth);
// 2.创建一个Message,它相当于是邮件内容
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("******@qq.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);
}
}
邮件接收成功: