亲测可用
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
/**
* @program: xinhu-wealth-witcast
* @Date: 2021/3/15 15:55
* @Author: Mr.zhuhaoyu
* @Description:
*/
public class EmaillDemo implements Runnable{
private String email;// 收件人邮箱
public EmaillDemo(String email) {
this.email = email;
}
public void run() {
// 1.创建连接对象javax.mail.Session
// 2.创建邮件对象 javax.mail.Message
// 3.发送一封激活邮件
String from = "xxxxx";// 发件人电子邮箱
String host = "xxxx"; // foxmail服务器地址
Properties properties = System.getProperties();// 获取系统属性
String password = "xxxx";
properties.setProperty("mail.smtp.host", host);// 设置邮件服务器
properties.setProperty("mail.smtp.auth", "true");// 打开认证
properties.setProperty("mail.smtp.port", "25"); //设置端口
try {
// 1.获取默认session对象
Session session = Session.getDefaultInstance(properties, new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(from, password); // 发件人邮箱账号、密码
}
});
// 2.创建邮件对象
Message message = new MimeMessage(session);
// 2.1设置发件人
message.setFrom(new InternetAddress(from));
// 2.2设置接收人
message.addRecipient(Message.RecipientType.TO, new InternetAddress(email));
// 2.3设置邮件主题
message.setSubject("模拟邮件");
// 2.4设置邮件内容
String content = "<html><head></head><body><h1>"
+ "模拟邮件 Over"
+ "</h1></href></h3></body></html>";
message.setContent(content, "text/html;charset=UTF-8");
// 3.发送邮件
Transport.send(message);
System.out.println("邮件成功发送!");
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new EmaillDemo("xxxx@163.com").run();
}
}