Java使用网易邮箱发送邮件
-
准备工作:开启 网易邮箱 STMP 模式
-
弄一个测试案例大家试一下吧!
public static void sendMail(String email, String emailMsg)
throws AddressException, MessagingException {
// 配置邮箱服务器
String host = "smtp.163.com";
String userName = "你的网易邮箱账号";
String authCode = "你的授权码";
// 设置属性
Properties props = new Properties();
props.put("mail.smtp.host", host);
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465"); // 使用SSL时使用465端口
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
// 创建会话
Session session = Session.getInstance(props, new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userName, authCode);
}
});
try {
// 创建邮件
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(userName)); // 设置发件人
message.addRecipient(Message.RecipientType.TO, new InternetAddress(email)); // 设置收件人->想要发送的邮箱账户
message.setSubject("邮件主题");
message.setContent(emailMsg, "text/html;charset=UTF-8"); // 设置邮件内容
// 发送邮件
Transport.send(message);
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
public static void main(String[] args) {
try {
sendMail2("XXX@qq.com", "这是一封测试邮件,请查收。");
} catch (AddressException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
}
}