Email邮件设置 工具开发整理(网易邮箱、Mailgun为例) 上篇
说明:Email邮件 国内国外设置 以网易邮箱和Mailgun为例,并开发工具类。
一、国内 网易邮箱设置
1.设置STMP 服务
2.获取授权密码
授权密码为邮件stmp 服务密码 非网易邮箱密码
3.邮件代码示例
public static void main(String[] args) {
try {
String emailFrom = "";//发件人邮箱
String emailPwd = "";//密码
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.163.com");// 设置服务器地址
props.put("mail.store.protocol", "smtp");// 设置协议
props.put("mail.smtp.port", 25);// 设置端口
props.put("mail.smtp.auth", true);
Authenticator authenticator = new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(emailFrom, emailPwd);
}
};
Session session = Session.getDefaultInstance(props, authenticator);
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(emailFrom));
InternetAddress[] address = { new InternetAddress("****@qq.com") };//收件人邮箱
msg.setRecipients(Message.RecipientType.TO, address);
msg.setSubject("这是标题");
msg.setSentDate(new Date());
msg.setContent("<a href='http://www.baidu.com'>请点击激活</a>", "text/html;charset=utf-8");
Transport.send(msg);
}catch (Exception e){
e.printStackTrace();
}
}
二、国外 Mailgun 邮件设置
1.注册 Mailgun 增加子域
Mailgun 邮件发送需要域名解析,需要有自己域名。
2.获取解析内容
3.解析域名(阿里云为例)
4.获取发件人邮箱和密码
5.代码示例
public static void main(String[] args) {
try {
String emailFrom = "";//发件人邮箱
String emailPwd = "";//密码
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.mailgun.org");// 设置服务器地址
props.put("mail.store.protocol", "smtp");// 设置协议
props.put("mail.smtp.port", 25);// 设置端口
props.put("mail.smtp.auth", true);
Authenticator authenticator = new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(emailFrom, emailPwd);
}
};
Session session = Session.getDefaultInstance(props, authenticator);
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(emailFrom));
InternetAddress[] address = { new InternetAddress("****@qq.com") };//收件人邮箱
msg.setRecipients(Message.RecipientType.TO, address);
msg.setSubject("这是标题");
msg.setSentDate(new Date());
msg.setContent("<a href='http://www.baidu.com'>请点击激活</a>", "text/html;charset=utf-8");
Transport.send(msg);
}catch (Exception e){
e.printStackTrace();
}
}
注:邮件工具类 参考https://blog.csdn.net/qq_37184877/article/details/100512095