<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;
}
因为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;
}
}