// 获取系统属性
Properties properties = System.getProperties();
// 设置邮件服务器
properties.setProperty("mail.smtp.host", mailHost);
properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
properties.put("mail.smtp.socketFactory.port", "465");
properties.put("mail.smtp.port", "465");
//SSLSocketFactory类的端口
properties.put("mail.smtp.auth", "true");
// 获取默认session对象
Session session = Session.getDefaultInstance(properties, new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(fromMail, password); // 发件人邮件用户名、密码
}
});
// 创建默认的 MimeMessage 对象
MimeMessage message = new MimeMessage(session);
// Set From: 头部头字段
message.setFrom(new InternetAddress(fromMail));
// Set To: 头部头字段
message.addRecipient(Message.RecipientType.TO, new InternetAddress(toMail));
// Set Subject: 头部头字段
message.setSubject(mailTitle);
// 设置消息体
BodyPart html = new MimeBodyPart();
Multipart mainPart = new MimeMultipart();
// 设置HTML内容
html.setContent(mailContent, "text/html; charset=utf-8");
mainPart.addBodyPart(html);
// 将MiniMultipart对象设置为邮件内容
message.setContent(mainPart);
// 发送消息
Transport.send(message);
发送普通文本内容的时候可直接message.stContent(contentStr);
但是如果发送的是带有html标签并且希望阅读邮件的时候能被解析为html页面则需要使用如下代码设置邮件内容
BodyPart html = new MimeBodyPart();
Multipart mainPart = new MimeMultipart();
// 设置HTML内容
html.setContent(mailContent, "text/html; charset=utf-8");
mainPart.addBodyPart(html);
// 将MiniMultipart对象设置为邮件内容
message.setContent(mainPart);