类似于python(基本原理可以参考这二篇文章)
https://blog.csdn.net/weixin_46098676/article/details/113750558
https://blog.csdn.net/weixin_46098676/article/details/113746671
废话不多说
可能有些人不知道在哪里下载jar,我这里在提一句吧,下面是maven的镜像仓库地址
下载地址:https://mvnrepository.com/
先需要导入二个jar包
activation-1.1.1
mail-1.4.7
代码如下:
Properties prop = new Properties();
MailSSLSocketFactory sf = new MailSSLSocketFactory();
prop.put("mail.transport.protocol", "smtp");// 邮件传输协议
prop.put("mail.smtp.host", "smtp.qq.com");// 主机名
prop.put("mail.smtp.auth", "true");
sf.setTrustAllHosts(true);
prop.put("mail.smtp.ssl.enable", "true");
prop.put("mail.smtp.ssl.socketFactory", sf);
//使用JAVAMail发送邮件的五个步骤
//1、创建定义整个应用程序锁需的环境信息的session对象
Session session = Session.getDefaultInstance(prop, new Authenticator() {
@Override
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("xxxxx@qq.com", "授权码");
}
});
//开启Session的debug模式,这样就可以查看到程序发送Email的运行状态
session.setDebug(true);
//2、通过session得到transport对象
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("xxxx@qq.com"));
//指明邮件的接收人
message.setRecipient(Message.RecipientType.TO, new InternetAddress("xxx@qq.com"));
//邮件标题
message.setSubject("简单邮件只有文本");
//邮件内容
message.setContent("<h1 style='color: red'>你好啊!Java发送邮件</h1>", "text/html;charset=utf-8");
//5、发送邮件
Transport ts = session.getTransport();
ts.connect("xxxx@qq.com", "授权码");
ts.sendMessage(message, message.getAllRecipients());
System.out.println("发送成功!");
//关闭资源
ts.close();