1、pom,xml
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.7</version>
</dependency>
2 、properties.ini
#默认的smtp域名
smtpServer = smtp.mxhichina.com
# 端口:非加密25,ssl加密465
port= 465
#阿里邮箱账号
fromUser =test@test.com
#邮箱密码
fromUserPassword= ****
3.实体类
public class EmailInfo {
private String smtpServer;// SMTP服务器地址
private String port; // 端口
private String fromUser;// 登录SMTP服务器的用户名,发送人邮箱地址
private String fromUserPassword;// 登录SMTP服务器的密码
private String toUser; // 收件人
private String subject; // 邮件主题
private String content; // 邮件正文
public EmailInfo() { }
public EmailInfo(String toUser, String subject, String content) {
this.toUser = toUser;
this.subject = subject;
this.content = content;
this.smtpServer = PropKit.use("properties.ini").get("smtpServer");
this.port = PropKit.use("properties.ini").get("port");
this.fromUser = PropKit.use("properties.ini").get("fromUser");
this.fromUserPassword = PropKit.use("properties.ini").get("fromUserPassword");
}
}
4.邮箱发送工具类
public class EmaiSender {
public static void send(EmailInfo emailInfo){
try {
//设置SSL连接、邮件环境
Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
Properties props = System.getProperties();
props.setProperty("mail.smtp.host", emailInfo.getSmtpServer());
props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
props.setProperty("mail.smtp.socketFactory.fallback", "false");
props.setProperty("mail.smtp.port", emailInfo.getPort());
props.setProperty("mail.smtp.socketFactory.port", emailInfo.getPort());
props.setProperty("mail.smtp.auth", "true");
//建立邮件会话
Session session = Session.getDefaultInstance(props, new Authenticator() {
//身份认证
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(emailInfo.getFromUser(), emailInfo.getFromUserPassword());
}
});
//建立邮件对象
MimeMessage message = new MimeMessage(session);
//设置邮件的发件人、收件人、主题
message.setFrom(new InternetAddress(emailInfo.getFromUser()));
message.setRecipients(Message.RecipientType.TO, emailInfo.getToUser());
message.setSubject(emailInfo.getSubject());
//文本
Multipart multipart = new MimeMultipart();
// 创建一个包含HTML内容的MimeBodyPart
BodyPart html = new MimeBodyPart();
// 设置HTML内容
html.setContent(emailInfo.getContent(), "text/html; charset=utf-8");
multipart.addBodyPart(html);
// 将MiniMultipart对象设置为邮件内容
message.setContent(multipart);
message.setSentDate(new Date());
message.saveChanges();
//发送邮件
Transport.send(message);
} catch (Exception e) {
System.out.println(e.toString());
}
}
}