一、一般配置
发送邮件需要用到 mail包 maven 依赖如下:
<!-- https://mvnrepository.com/artifact/javax.mail/mail -->
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4</version>
</dependency>
SSL加密方式需要用到MailSSLSocketFactory类
<!-- https://mvnrepository.com/artifact/com.sun.mail/javax.mail -->
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>1.4.4</version>
</dependency>
获取配置文件:
//获取邮箱发送邮件的配置信息
public Properties getEmailProperties(){
Properties props = new Properties();
String host = evn.getProperty("email.host");
String protocol = evn.getProperty("email.protocol");
String port = evn.getProperty("email.port");
String from = evn.getProperty("email.from");
String pwd = evn.getProperty("email.password");
props.put("mail.smtp.host", host);//设置服务器地址
props.put("mail.store.protocol" , protocol);//设置协议
props.put("mail.smtp.port", port);//设置端口
props.put("from" , from);
props.put("pwd" , pwd);
props.put("mail.smtp.auth" , "true");
return props;
}
邮件发送代码类:
/**
*
* @file springBootExample.example.infrastructure
*
*/
package com.tyky.educloud.platform.util; /**
* @ClassName: SendEmail
* @Description: TODO(这里用一句话描述这个类的作用)
* @author hoojjack
* @date 2017年7月19日 下午3:23:42
*
*/
import java.util.Date;
import java.util.Properties; import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage; public class SendEmail { public static Properties props = new Properties(); public static void setProps(Properties props) {
SendEmail.props = props;
} public static Properties getProps() {
return props;
} /**
* 获取Session
*
* @return
*/
private static Session getSession(final String from, final String pwd) { Authenticator authenticator = new Authenticator() { @Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(from, pwd);
} };
Session session = Session.getDefaultInstance(props, authenticator); return session;
} public static void send(String content, String toEmail) throws AddressException, MessagingException {
Properties properties = getProps();
String from = properties.getProperty("from");
String pwd = properties.getProperty("pwd");
String subject = properties.getProperty("subject"); if (null == from || null == pwd) {
System.out.println("发送邮箱为空");
return;
}
if (null == subject) {
subject = "平台";
}
Session session = getSession(from, pwd);
// Instantiate a message
Message msg = new MimeMessage(session);
// Set message attributes
msg.setFrom(new InternetAddress(from));
InternetAddress[] address = { new InternetAddress(toEmail) };
msg.setRecipients(Message.RecipientType.TO, address);
msg.setSubject(subject);
msg.setSentDate(new Date());
msg.setContent(content, "text/html;charset=utf-8");
// Send the message
Transport.send(msg);
} public static String generateContent(String contentTitle, String url, String username, String email,
String validateCode) { // String validataCode = MD5Util.encode2hex(email); /// 邮件的内容
StringBuffer sb = new StringBuffer(contentTitle);
sb.append("<a href=\"" + url + "?username=");
sb.append(username);
sb.append("&email=");
sb.append(email);
sb.append("&validateCode=");
sb.append(validateCode);
sb.append("\">" + url + "?username=");
sb.append(username);
sb.append("&email=");
sb.append(email);
sb.append("&validateCode=");
sb.append(validateCode);
sb.append("</a>");
return sb.toString();
} }
邮件发送完整的代码:
/**
* @ClassName: SendEmail
* @Description: TODO(这里用一句话描述这个类的作用)
* @author hoojjack
* @date 2017年7月19日 下午3:23:42
*
*/
import java.util.Date;
import java.util.Properties; import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage; public class SendEmail { public static Properties props = new Properties(); public static void setProps(Properties props) {
SendEmail.props = props;
} public static Properties getProps() {
props.put("mail.smtp.host", "smtp.163.com");// 设置服务器地址
props.put("mail.store.protocol", "smtp.163.com");// 设置协议
props.put("mail.smtp.port", 25);// 设置端口
props.put("from", "XXX");
props.put("pwd", "XXX");
props.put("mail.smtp.auth", "true");
} /**
* 获取Session
*
* @return
*/
private static Session getSession(final String from, final String pwd) { Authenticator authenticator = new Authenticator() { @Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(from, pwd);
} };
Session session = Session.getDefaultInstance(props, authenticator); return session;
} public static void send(String content, String toEmail) throws AddressException, MessagingException {
Properties properties = getProps();
String from = properties.getProperty("from");
String pwd = properties.getProperty("pwd");
String subject = properties.getProperty("subject"); if (null == from || null == pwd) {
System.out.println("发送邮箱为空");
return;
}
if (null == subject) {
subject = "平台";
}
Session session = getSession(from, pwd);
// Instantiate a message
Message msg = new MimeMessage(session);
// Set message attributes
msg.setFrom(new InternetAddress(from));
InternetAddress[] address = { new InternetAddress(toEmail) };
msg.setRecipients(Message.RecipientType.TO, address);
msg.setSubject(subject);
msg.setSentDate(new Date());
msg.setContent(content, "text/html;charset=utf-8");
// Send the message
Transport.send(msg);
} public static String generateContent(String contentTitle, String url, String username, String email,
String validateCode) { // String validataCode = MD5Util.encode2hex(email); /// 邮件的内容
StringBuffer sb = new StringBuffer(contentTitle);
sb.append("<a href=\"" + url + "?username=");
sb.append(username);
sb.append("&email=");
sb.append(email);
sb.append("&validateCode=");
sb.append(validateCode);
sb.append("\">" + url + "?username=");
sb.append(username);
sb.append("&email=");
sb.append(email);
sb.append("&validateCode=");
sb.append(validateCode);
sb.append("</a>");
return sb.toString();
} }
以下是两种不同加密方式的代码,与上面默认25端口的方式差别较小,注意不同加密方式红色部分。
1. JavaMail – via TLS
package com.mkyong.common; import java.util.Properties; import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage; public class SendMailTLS { public static void main(String[] args) { final String username = "username@gmail.com";
final String password = "password"; Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587"); Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
}); try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("from-email@gmail.com"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("to-email@gmail.com"));
message.setSubject("Testing Subject");
message.setText("Dear Mail Crawler,"
+ "\n\n No spam to my email, please!"); Transport.send(message);
System.out.println("Done"); } catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}
2. JavaMail – via SSL
package com.mkyong.common; import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage; public class SendMailSSL {
public static void main(String[] args) {
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465"); Session session = Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("username","password");
}
}); try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("from@no-spam.com"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("to@no-spam.com"));
message.setSubject("Testing Subject");
message.setText("Dear Mail Crawler," +
"\n\n No spam to my email, please!"); Transport.send(message);
System.out.println("Done"); } catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}
注意:如果以上ssl不行可以尝试将ssl红色部分用以下代码替换:
MailSSLSocketFactory sf = null;
try {
sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
} catch (GeneralSecurityException e1) {
e1.printStackTrace();
}
props.put("mail.smtp.ssl.enable", "true");
props.put("mail.smtp.ssl.socketFactory", sf);