邮件发送
原生java-mail进行邮件发送; 前提:先登录邮箱,开启POP3/SMTP服务,使第三方可以使用授权码登录邮箱。
@Test
public void sendEmail(){
String account="19008239181@163.com";
String pwd="KXNZHOZDMLTVWHOZ";
//设置SMTP请求头
Properties properties = new Properties();
properties.put("mail.transport.protocol", "smtp");// 连接协议
properties.put("mail.smtp.host", "smtp.163.com");// QQ smtp.qq.com
properties.put("mail.smtp.port", 465);// 默认端口号 25
properties.put("mail.smtp.auth", "true");//服务端认证。
properties.put("mail.smtp.ssl.enable", "true");// 设置是否使用ssl安全连接 ---一般都使用
properties.put("mail.debug", "true");// 设置是否显示debug信息 true 会在控制台显示相关信息
String to="chengdujavasm@126.com";
//会话对象
Session s = Session.getDefaultInstance(properties);
try {
Message msg = new MimeMessage(s);
msg.setFrom(new InternetAddress(account));
msg.addRecipient(Message.RecipientType.TO,new InternetAddress(to));
msg.addRecipient(Message.RecipientType.CC,new InternetAddress(account));
msg.setSubject("今日新闻");
msg.setText("飓风来袭");
//邮差对象
Transport transport = s.getTransport();
transport.connect(account,pwd);
transport.sendMessage(msg,msg.getAllRecipients());
} catch (Exception e) {
e.printStackTrace();
}
}
spring封装的spring-mail组件; 项目开发中我们选择sprng中封装的mail组件,使用简单方便。
-
添加mail启动器
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency>
-
yml中配置登录邮箱,授权码,端口,ssl等。
spring: mail: protocol: smtp host: smtp.163.com port: 465 username: 1993