采用Hutool工具实现发送邮件,可以访问Hutool官网
引言:从零开始,实现一个基本功能,邮件发送
第一步:打开idea,新建maven工程,引入依赖,如下:
<dependencies>
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>1.6.2</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.26</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.7.22</version>
</dependency>
</dependencies>
第二步,创建一个邮箱对象,如下
@Data
@NoArgsConstructor
@AllArgsConstructor
public class EmailInfo {
/**
* 邮箱账户
*/
private String emailAccount;
/**
* 邮箱密码
*/
private String emailPassword;
/**
* 发件人名称
*/
private String senderName;
/**
* 发件服务器
*/
private String sendServer;
/**
* 发件服务器是否遵循安全协议(0,不是 1是,默认0)
*/
private Integer sendServerIsSSL = 0;
/**
* 发件服务器端口(一般是若sendServerIsSSL = 1,端口则是25,若不是,则为465)
*/
private Integer sendPort;
}
最后开始写一个main程序测试。前提是需要登陆相关邮箱,开通相关服务,这里以qq邮箱为例,登录qq邮箱,然后打开设置
进入之后,继续进入,一直下拉到最下面
找到下图这里,然后开通,smtp协议,会给你一个授权码,作为你的密码,然后才能发的,否则会报未授权的错误
开通后,要注意上面邮箱实体类中的提示取值哦。
因为qq是遵循安全协议的ssl = 1,所以设置的端口选择:465
最终的程序,大家自行提取里面的方法
public class SendEmailDemo {
public static void main(String[] args) {
EmailInfo info = new EmailInfo();
info.setEmailAccount("你得邮箱");
info.setEmailPassword("开通smtp协议的授权码,后面有教程");
info.setSendPort(465);
info.setSendServer("smtp.qq.com"); //遵循stmp的服务协议的服务器,可以百度,很多的
info.setSenderName("发送人名称");
info.setSendServerIsSSL(1);
MailAccount account = getMailAccount(info);
MailUtil.send(account,info.getEmailAccount(),"邮件服务测试","邮件服务测试成功",false);
}
/**
* 获取邮箱参数对象
*
* @param emailInfo
* @return
*/
private static MailAccount getMailAccount(EmailInfo emailInfo) {
MailAccount account = new MailAccount();
if (ObjectUtil.isNotEmpty(emailInfo.getSenderName())) {
StringBuilder sb = new StringBuilder();
sb.append(emailInfo.getSenderName())
.append('<')
.append(emailInfo.getEmailAccount())
.append('>');
account.setFrom(sb.toString());
} else {
account.setFrom(emailInfo.getEmailAccount());
account.setUser(emailInfo.getEmailAccount());
}
account.setPass(emailInfo.getEmailPassword());
account.setHost(emailInfo.getSendServer());
account.setPort(emailInfo.getSendPort());
account.setAuth(true);
account.setSocketFactoryClass("javax.net.ssl.SSLSocketFactory");
account.setSocketFactoryFallback(true);
account.setSocketFactoryPort(emailInfo.getSendPort());
if (emailInfo.getSendServerIsSSL() == 0) {
account.setSslEnable(false);
} else {
account.setSslEnable(true);
}
account.setTimeout(3000);
return account;
}
}