记录下,后续需进行后台错误消息的日志的邮件发送。
1.qq邮箱 需要设置
打开邮箱点击设置:
2.java上导个包
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.7</version>
</dependency>
上代码:
import java.security.Security;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class MailTest {
public static void main(String[] args) {
try {
//设置SSL连接、邮件环境
Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
Properties props = System.getProperties();
props.setProperty("mail.smtp.host", "smtp.qq.com");
props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
props.setProperty("mail.smtp.socketFactory.fallback", "false");
props.setProperty("mail.smtp.port", "465");
props.setProperty("mail.smtp.socketFactory.port", "465");
props.setProperty("mail.smtp.auth", "true");
//建立邮件会话
Session session = Session.getDefaultInstance(props, new Authenticator() {
//身份认证
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("23858****0@qq.com", "nfk********be"); //账户 授权码
}
});
//建立邮件对象
MimeMessage message = new MimeMessage(session);
//设置邮件的发件人、收件人、主题
//附带发件人名字
message.setFrom(new InternetAddress("23858****0@qq.com"));
message.setRecipients(Message.RecipientType.TO, "5402*****4@qq.com");
message.setSubject("通过javamail发出!!!");
//文本部分
message.setContent("文本邮件测试", "text/html;charset=UTF-8");
message.saveChanges();
//发送邮件
Transport.send(message);
} catch (Exception e) {
e.printStackTrace();
}
}
}