Pat*_*ick 2 java email spring spring-boot
我正在尝试在 Spring Boot 中发送带有文件附件的电子邮件。
这是一个基本的 gmail SMTP 服务器应用程序属性配置:
这是我的电子邮件服务:
EmailService
Run Code Online (Sandbox Code Playgroud)
当我使用传递的 mailMessageDto 对象调用此方法时,没有抛出异常。什么都没有发生,没有发送电子邮件。
我已经调试了 javaMailSender.send(message) 代码行,一切似乎都很好。
更新
spring.mail.properties.mail.smtp.ssl.enable=false
Run Code Online (Sandbox Code Playgroud)
应该是假不是真的 spring.mail.properties.mail.smtp.socketFactory.class=javax.net.ssl.SSLSocketFactory
步骤 1. 在 porm.xml 中添加依赖项
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
Run Code Online (Sandbox Code Playgroud)
步骤2.在application.properties中添加配置代码
spring.mail.host=smtp.gmail.com
spring.mail.port=465
spring.mail.username=username
spring.mail.password=password
spring.mail.protocol=smtps
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.connectiontimeout=5000
spring.mail.properties.mail.smtp.timeout=5000
spring.mail.properties.mail.smtp.writetimeout=5000
spring.mail.properties.mail.smtp.starttls.enable=true
Run Code Online (Sandbox Code Playgroud)
步骤 3. 在控制器 masterconroller.java 中添加代码
@GetMapping("/sendmail")
@ResponseBody
String home() {
try {
masterServiceImpl.sendEmail("path");
return "Email Sent!";
} catch (Exception ex) {
return "Error in sending email: " + ex;
}
}
Run Code Online (Sandbox Code Playgroud)
步骤 4. 在 MasterServiceImpl.java 中添加代码
@Autowired
private JavaMailSender javaMailSender;
public void sendEmail(String path) throws Exception{
MimeMessage message = javaMailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setTo("xyz@gmail.com");
helper.setText("<html><body><h1>hello Welcome!</h1><body></html>", true);
FileSystemResource file = new FileSystemResource(new File(path));
helper.addAttachment("testfile", file);
helper.addAttachment("test.png", new ClassPathResource("test.jpeg"));
helper.setSubject("Hi");
javaMailSender.send(message);
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
9778 次 |
最近记录: |