Files
nuttyreading-java/src/main/java/com/peanut/common/utils/MailUtil.java
2023-12-26 10:56:58 +08:00

49 lines
1.8 KiB
Java

package com.peanut.common.utils;
import javax.mail.Authenticator;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
public class MailUtil {
private final static String mailName = "fengzidushu@163.com";
private final static String mailToken = "GJIPUCQLQYTMDMPH";
public static R sendMail(String title,String content,String receiveAddress){
try {
//smtp服务器
Properties pros=new Properties();
pros.put("mail.smtp.host", "smtp.163.com");//主机名
pros.put("mail.smtp.port", "25");//主机端口号
pros.put("mail.smtp.auth", "true");//是否需要用户认证
pros.put("mail.smtp.starttls.enable", "true");//启用TLS加密
//创建会话
Session session=Session.getInstance(pros,new Authenticator(){
@Override
protected javax.mail.PasswordAuthentication getPasswordAuthentication(){
return new javax.mail.PasswordAuthentication(mailName, mailToken);
}
});
//设置debug模式便于调试
session.setDebug(true);
MimeMessage message=new MimeMessage(session);
//邮件标题
message.setSubject(title);
//邮件内容(文本)
message.setText(content,"utf-8");
//设置发送方地址
message.setFrom(new InternetAddress(mailName));
//设置收件方地址
message.setRecipient(MimeMessage.RecipientType.TO,new InternetAddress(receiveAddress));
//发送
Transport.send(message);
return R.ok();
}catch (Exception e) {
return R.error(e.getMessage());
}
}
}