使用阿里云邮件推送发送邮件

Posted by 石玉军 on 2018-07-26
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
public class MailUtil {
private final org.slf4j.Logger log = LoggerFactory.getLogger(WebConfigurer.class);

static final Properties props = new Properties();

static {
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.host", "smtpdm.aliyun.com");
props.put("mail.smtp.port", 80);
props.put("mail.user", "发送者邮箱");
props.put("mail.password", "在阿里云邮件控制台配置的密码");

}
/*
*发送方法
*/
public static void sendMail(String toEmail, String title, String msg) throws Exception {

Authenticator authenticator = new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
String userName = props.getProperty("mail.user");
String password = props.getProperty("mail.password");
return new PasswordAuthentication(userName, password);
}
};

Session mailSession = Session.getInstance(props, authenticator);

MimeMessage message = new MimeMessage(mailSession);
try {

InternetAddress from = new InternetAddress(props.getProperty("mail.user"));
message.setFrom(from);
Address[] a = new Address[1];
a[0] = new InternetAddress(props.getProperty("mail.user"));
message.setReplyTo(a);
InternetAddress to = new InternetAddress(toEmail);
message.setRecipient(MimeMessage.RecipientType.TO, to);
message.setSubject(title);
message.setContent(msg, "text/html;charset=UTF-8");
Transport.send(message);
} catch (MessagingException e) {
e.printStackTrace();
throw e;
}
}
}

`