javax.mail实现收发邮件
添加依赖开通POP3/SMPT服务发送邮件更改端口
添加依赖
在pom.xml 文件里面添加依赖
<!--mail
-->
<dependency>
<groupId>org
.springframework
.boot
</groupId
>
<artifactId>spring
-boot
-starter
-mail
</artifactId
>
</dependency
>
开通POP3/SMPT服务
什么是POP3、SMTP?
1、什么是POP3:
POP3是Post Office Protocol3的简称,即邮局协议的第3个版本,它规定怎样将个人计算机连接到Internet的邮件服务器和下载电子邮件的电子协议。它是因特网电子邮件的第一个离线协议标准,POP3允许用户从服务器上把邮件存储到本地主机(即自己的计算机)上,同时删除保存在邮件服务器上的邮件,而POP3服务器则是遵循 POP3协议的接收邮件服务器,用来接收电子邮件的。
2、什么是SMTP:
SMTP 的全称是“Simple MailTransfer Protocol”,即简单邮件传输协议。它是一组用于从源地址到目的地址传输邮件的规范,通过它来控制邮件的中转方式。SMTP 协议属于 TCP/IP 协议簇,它帮助每台计算机在发送或中转信件时找到下一个目的地。SMTP 服务器就是遵循 SMTP 协议的发送邮件服务器。
(SMTP 认证,简单地说就是要求必须在提供了账户名和密码之后才可以登录 SMTP 服务器,这就使得那些垃圾邮件的散播者无可乘之机。增加 SMTP 认证的目的是为了使用户避免受到垃圾邮件的侵扰。)
开通服务使能够通过第三方发送邮件 记录下授权码
发送邮件
package com
.wff
.web
.exam
.jobinfo
.Utils
;
import javax
.mail
.*
;
import javax
.mail
.internet
.InternetAddress
;
import javax
.mail
.internet
.MimeMessage
;
import java
.util
.Properties
;
public class MailUtil {
private String email
;
private String Verificationcode
;
private int type
;
public MailUtil(String email
, String Verificationcode
, int type
) {
this.email
= email
;
this.Verificationcode
= Verificationcode
;
this.type
=type
;
}
public void sendemail() throws Exception
{
String from
= "wanting_jivi@163.com";
String host
= "smtp.163.com";
Properties properties
= System
.getProperties();
try{
Session session
= Session
.getDefaultInstance(properties
, new Authenticator() {
public PasswordAuthentication
getPasswordAuthentication() {
return new PasswordAuthentication("你的邮箱",
"你的授权码");
}
});
Message message
= new MimeMessage(session
);
message
.setFrom(new InternetAddress(from
));
message
.addRecipient(Message
.RecipientType
.TO
, new InternetAddress(email
));
String content
="";
if(type
==1){
message
.setSubject("注册账户");
content
= "<html><head></head><body><h3>【OfferComing】验证码:" +Verificationcode
+",如非本人操作,请忽略此消息,感谢配合,谢谢!</h3></body></html>";
}
else{
message
.setSubject("找回密码");
content
= "<html><head></head><body><h3>【OfferComing】验证码:" +Verificationcode
+",您正在重置密码,如非本人操作,请立即联系2246453301@qq.com。</h3></body></html>";
}
message
.setContent(content
, "text/html;charset=UTF-8");
Transport
.send(message
);
}catch (Exception e
){
throw new Exception(e
.getMessage());
}
}
}
更改端口
在本地测试的时候收发软件正常 但是发布到阿里云云服务器的时候就报错了 经过查询发现是阿里云服务器禁用了发送邮件的25短裤,所以需要把发送邮件的端口号改成465号端口
properties
.put("mail.smtp.port", "465");
properties
.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
properties
.setProperty("mail.smtp.socketFactory.fallback", "false");
properties
.setProperty("mail.smtp.socketFactory.port", "465");
properties
.setProperty("mail.smtp.host", host
);
properties
.setProperty("mail.smtp.auth", "true");
参考文章: 1.Javamail配置阿里云邮箱发送邮件 2.java实现邮件、手机短信的发送 3.java 发送邮箱25端口被禁用的解决方法