1.导入所需要的依赖
<dependency>
<groupId>javax.mail</groupId>
<artifactId>javax.mail-api</artifactId>
<version>1.5.6</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.simplejavamail/simple-java-mail -->
<dependency>
<groupId>org.simplejavamail</groupId>
<artifactId>simple-java-mail</artifactId>
<version>5.0.8</version>
</dependency>
2、了解邮件发送过程(了解相关协议SMTP和POP3等协议)
3、进行邮件服务器的相关设置(开启授权码登录)
nihai
4、编写客户端代码
/* 发送邮件*/
public void sendMail(String address) throws Exception {
Properties properties = new Properties();
// 开启debug调试,以便在控制台查看
properties.setProperty("mail.debug", "true");
// 设置邮件服务器主机名
properties.setProperty("mail.host", "smtp.126.com");
// 发送服务器需要身份验证
properties.setProperty("mail.smtp.auth", "true");
// 发送邮件协议名称
properties.setProperty("mail.transport.protocol", "smtp");
// 指定验证为true
properties.setProperty("mail.smtp.auth", "true");
properties.setProperty("mail.smtp.timeout","1000");
properties.setProperty("mail.smtp.port", "465");
//开 启 S S L 加 密,否 则 会 失 败
MailSSLSocketFactory sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
properties.put("mail.smtp.ssl.enable", "true");
properties.put("mail.smtp.ssl.socketFactory", sf);
//解决附件文件名过长的问题
properties.put("mail.mime.splitlongparameters", "false");
// 验证账号及密码,密码需要是第三方授权码
final Authenticator auth = new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("自己的邮箱地址", 授权码);
}
};
Session session=Session.getInstance(properties,auth);
/* 新建邮件 */
Message message=new MimeMessage(session);
message.setFrom(new InternetAddress("发件人邮箱"));
message.setRecipient(MimeMessage.RecipientType.TO,new InternetAddress(address));
message.setSubject("邮件发送测试");
message.setContent("<h1>邮件测试</h1>","text/html;charset=utf-8");
Transport transport = session.getTransport();
transport.connect("smtp.126.com","发件人邮箱","授权码");
Transport.send(message);
}
5、发送邮件
@Test
public void testMail(){
String mailAddress="*****@qq.com";
try {
sendMail(mailAddress);
} catch (Exception e) {
e.printStackTrace();
}
}
6、邮件发送成功
至此便实现了邮件的发送过程