我正在尝试在Spring Boot中发送带有文件附件的电子邮件。
这是基本的gmail SMTP服务器应用程序属性配置:
这是我的EmailService:
EmailService
当我通过传递mailMessageDto对象调用此方法时,没有引发异常。没有任何反应,没有发送电子邮件。
我已经在javaMailSender.send(messsage)代码行上调试了,一切似乎都很好。
更新
spring.mail.properties.mail.smtp.ssl.enable=false
应该为假,不是真的spring.mail.properties.mail.smtp.socketFactory.class = javax.net.ssl.SSLSocketFactory
答案 0 :(得分:1)
步骤1.在porm.xml中添加依赖项
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
第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
步骤3.在控制器中添加代码 masterconroller.java
@GetMapping("/sendmail")
@ResponseBody
String home() {
try {
masterServiceImpl.sendEmail("path");
return "Email Sent!";
} catch (Exception ex) {
return "Error in sending email: " + ex;
}
}
步骤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);
}
答案 1 :(得分:0)
我建议您通过提取添加附件的功能来将SRP应用于sendMessageWithAttachment()
方法:
private void addAttachments(MailMessageDto message, MimeMessageHelper helper) {
message.getFiles().forEach(file -> addAttachment(file, helper));
}
此方法streams用于所有文件,并使用addAttachment()
添加每个文件:
private void addAttachment(File file, MimeMessageHelper helper) {
String fileName = file.getName();
try {
helper.addAttachment(fileName, file);
log.debug("Added a file atachment: {}", fileName);
} catch (MessagingException ex) {
log.error("Failed to add a file atachment: {}", fileName, ex);
}
}
这将为每个失败的附件记录一个错误。您可以尝试这种方法吗?