最近项目中需要邮件报警,公司邮箱只能使用TLS方式登录,测试通过的代码如下:
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 = "youremail@163.com";
final String password = "password";
//收件箱
final String to = "receive@163.com";
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
//不做服务器证书校验
props.put("mail.smtp.ssl.checkserveridentity", "false");
//添加信任的服务器地址,多个地址之间用空格分开
props.put("mail.smtp.ssl.trust", "smtp.163.com");
props.put("mail.smtp.host", "smtp.163.com");
props.put("mail.smtp.port", "25");
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(username));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(to));
message.setSubject("Email Testing Subject");
message.setText("hello world!");
Transport.send(message);
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}
说明:本人使用的java mail版本为1.4.4,低版本的有可能测试不通过,请官网下载对应的Jar包进行测试;