今天下午突发奇想,复习了这么多天Java,用Java发送邮件怎么样?于是查了一下资料,把工具弄出来了。
在使用时需要导入JavaMail
工具类
package cn.limexc.mail;
import com.sun.mail.util.MailSSLSocketFactory;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.security.GeneralSecurityException;
import java.util.Properties;
/**
*
* @author LIMEXC
* @version V1.0.0
* @createDate 2020/12/15 19:38
* @since jdk1.8.0
*/
public class MailTool {
String toMail;
String subject;
String text;
String host = "mail.limexc.top";
String sendUser = "test@limexc.top";
String password ="此处密码";
public MailTool(String toMail, String subject, String text) {
this.toMail = toMail;
this.subject = subject;
this.text = text;
}
private Session getSysInfo(){
// 获取系统属性
Properties sysInfo = System.getProperties();
// 设置邮件服务器
sysInfo.setProperty("mail.smtp.host", host);
sysInfo.put("mail.smtp.auth", "true");
// // 关于QQ邮箱,还要设置SSL加密,加上以下代码即可
// MailSSLSocketFactory qq_ssl = null;
// try {
// qq_ssl = new MailSSLSocketFactory();
// } catch (GeneralSecurityException e) {
// e.printStackTrace();
// }
// qq_ssl.setTrustAllHosts(true);
// sysInfo.put("mail.smtp.ssl.enable", "true");
// sysInfo.put("mail.smtp.ssl.socketFactory", qq_ssl);
// 获取默认session对象
Session session = Session.getDefaultInstance(sysInfo,new Authenticator(){
public PasswordAuthentication getPasswordAuthentication()
{//发件人邮件用户名、授权码
return new PasswordAuthentication(sendUser, password);
}
});
return session;
}
public boolean sendMail(){
try{
// 创建默认的 MimeMessage 对象
MimeMessage message = new MimeMessage(getSysInfo());
// Set From: 头部头字段
message.setFrom(new InternetAddress(sendUser));
// Set To: 头部头字段
message.addRecipient(Message.RecipientType.TO, new InternetAddress(toMail));
// Set Subject: 头部头字段
message.setSubject(subject);
// 设置消息体
message.setText(text);
// 发送消息
Transport.send(message);
System.out.println("Sent message successfully....");
return true;
}catch (MessagingException mex) {
mex.printStackTrace();
return false;
}
}
}
使用方法
package cn.limexc.mail;
/**
* @author LIMEXC
* @CreateDate 2020/12/15 19:46
* @since jdk1.8.0
*/
public class Test {
public static void main(String[] args) {
MailTool aa = new MailTool("########@qq.com","Hello","封装完成");
aa.sendMail();
}
}
Comments | NOTHING