一、添加依赖
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>1.6.2</version>
</dependency>
二、263邮箱
1,邮箱配置
public static void sendEmail(String host, int port, String userName, String password,
String toAddress, String subject, String message) throws MessagingException {
Properties properties = new Properties();
// 是否需要用户认证
properties.put("mail.smtp.auth", "true");
// 启用TlS加密
properties.put("mail.smtp.starttls.enable", "true");
// properties.put("mail.smtp.ssl.enable", "true");
properties.put("mail.smtp.host", host);
properties.put("mail.smtp.port", port);
Session session = Session.getInstance(properties, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userName, password);
}
});
session.setDebug(true);
MimeMessage mimeMessage = new MimeMessage(session);
mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(toAddress));
mimeMessage.setSubject(subject);
mimeMessage.setText(message);
Transport.send(mimeMessage);
}
2,发邮件
// 263邮箱客户端配置:https://www.263.net/success/mail/client/20160603/970.html 465
MailUtil.sendEmail("smtp.263.net",25,"liuxm@rootensoft.com","******"
,"15250480155@163.com","发送的主题2","发送的内容2");
3,结果
三、qq邮箱
如果发件人是qq邮箱,那么代码要做改变。主要不同的地方有三点:
- 属性里要添加scoketFactory.class
- 密码变成授权码
- MimeMessage钟添加From属性
1,发邮件代码
public static void sendEmail(String host, int port, String userName, String password,
String toAddress, String subject, String message) throws MessagingException {
Properties properties = new Properties();
// 是否需要用户认证
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.host", host);
properties.put("mail.smtp.port", port);
properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
Session session = Session.getInstance(properties, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userName, password);
}
});
session.setDebug(true);
MimeMessage mimeMessage = new MimeMessage(session);
mimeMessage.setFrom(new InternetAddress("309997751@qq.com"));
mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(toAddress));
mimeMessage.setSubject(subject);
mimeMessage.setText(message);
Transport.send(mimeMessage);
}
2,发送
MailUtil.sendEmail("smtp.qq.com",465,"309997751@qq.com","授权码"
,"15250480155@163.com","发送的主题4","发送的内容4");
3,结果