代码如下:
/**
* 邮件发送简单的内容
* @param hint
* @param msg
* @throws Exception
*/
public voidsendEmail(String subject,String text,InternetAddress[] toMailUsers,boolean isDebug) throws Exception {
if (toMailUsers == null || toMailUsers.length == 0) return;
final String sender = "xxx@163.com";
final String passwd = "xxxxxxxxxxx";
//环境参数配置
String host = "smtp.163.com";
Properties props = System.getProperties();
props.setProperty("mail.smtp.host", host);
props.setProperty("mail.debug", isDebug+"");
props.setProperty("mail.smtp.auth", "true");
// props.setProperty("mail.smtp.starttls.enable", "true");
// props.setProperty("mail.debug.quote", "true");
//
Authenticator auth = new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(sender, passwd);
}
};
//获取session
Session session = Session.getDefaultInstance(props, auth);
//信息流设置
MimeMessage message = new MimeMessage(session);
//发送者地址设置
message.setFrom(new InternetAddress(sender));
//接受方式设置
message.addRecipients(RecipientType.TO,toMailUsers);
//头部头字段
message.setSubject(subject);
//消息体
message.setText(text);
//发送
Transport.send(message);
logger.info("send to email["+StringUtils.join(toMailUsers, ";")+"] subject["+subject+"] text ["+text+"] successfully.");
}
注意:
1)163、qq等邮箱账号需要开通授权第三方授权码,配置的密码也是第三方授权码,不可直接使用登录密码
密码不对, 会有类似的报错
javax.mail.MessagingException: Exception reading response;
nested exception is:
java.net.SocketException: Connection reset
at com.sun.mail.smtp.SMTPTransport.readServerResponse(SMTPTransport.java:1611)
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1369)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:412)
at javax.mail.Service.connect(Service.java:310)
at javax.mail.Service.connect(Service.java:169)
at javax.mail.Service.connect(Service.java:118)
at javax.mail.Transport.send0(Transport.java:188)
at javax.mail.Transport.send(Transport.java:118)
2)公司内部使用的Foxmail可以直接使用登录密码发送