import javax.activation.DataHandler;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.util.Properties;
import javax.mail.Address;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
public class SendMail {
public static void main(String[] args) {
sendMail("test@qq.com", "邮件标题","邮件内容");
}
public static boolean sendMail(String to, String title, String content) {
try {
System.out.println("========================>初始化邮箱配置,收件人:"+to);
System.out.println("========================>初始化邮箱配置,邮件标题:"+title);
System.out.println("========================>初始化邮箱配置,邮件内容:"+content);
String host = "smtp...";
String hostPort = "25/465/...";
String sender = "测试邮件";
String senderUser = "收件人";
//smtp登录授权码
String senderPwd = "";
// 初始化邮箱服务器参数
Properties props = new Properties();
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", hostPort);
props.put("mail.smtp.auth", "true");
//SSL启用
//props.put("mail.smtp.socketFactory.port", hostPort);
//props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
//debug启用
//props.put("mail.debug", "true");
// 进行邮件服务器用户认证
Authenticator auth = new EmailAutherticator(senderUser, senderPwd);
// 设置session,和邮件服务器进行通讯。
Session session = Session.getDefaultInstance(props, auth);
// 初始化邮件
MimeMessage message = new MimeMessage(session);
// 初始化邮件发件人
Address addressFrom = new InternetAddress(senderUser, sender, "UTF-8");
// 设置邮件发送人
message.setFrom(addressFrom);
// 初始化邮件收件人
Address addressTo = new InternetAddress(to);
// 设置邮件收件人
message.addRecipient(Message.RecipientType.TO, addressTo);
// 设置邮件主题
message.setSubject(title, "UTF-8");
// 正文
BodyPart bodyPart = new MimeBodyPart();
// 正文网页格式
bodyPart.setDataHandler(new DataHandler(content, "text/html;charset=UTF-8"));
// related意味着可以发送html格式的邮件
Multipart multipart = new MimeMultipart("related");
multipart.addBodyPart(bodyPart);
// 设置邮件正文
message.setContent(multipart);
// 发送邮件
Transport.send(message);
System.out.println("========================>邮件发送结束:"+to);
return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
// 邮箱用户名和密码认证器(认证类)
private static class EmailAutherticator extends Authenticator {
private String username;
private String password;
public EmailAutherticator() {
super();
}
public EmailAutherticator(String user, String pwd) {
super();
username = user;
password = pwd;
}
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
}
}
java smtp邮件发送
最新推荐文章于 2024-03-06 18:34:29 发布