我当前有一个Spring Boot Web应用程序,我想发送包含HTML的电子邮件,因此电子邮件看起来更令人愉悦。目前,我正在使用SimpleMailMessage。
我不想仅仅为了发送一封格式的电子邮件而实施模板引擎。
所有的帮助都非常感谢,谢谢。
如果您实际上使用了Spring Boot,那么发送消息的开始非常好。您的代码可以基于以下简单的内容松散:
@Component
public class EmailServiceImpl implements EmailService {
@Autowired
public JavaMailSender emailSender;
@Autowired
public MimeMessage mimeMessage;
public void sendMessage() {
helper.setTo("someone@abc.com");
helper.setSubject("This is the test message for testing gmail smtp server using spring mail");
helper.setFrom("abc@gmail.com");
mailSender.send(mimeMessage);
}
}
看起来包含您的模板的@Configuration
:
@Bean
@Scope("prototype")
public MimeMessage templateSimpleMessage(JavaMailSender mailSender) {
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "utf-8");
helper.setText("<h3>Hello World!</h3>");
return message;
}
只需在application.yml
中像配置您的邮件SMTP目标:
# application.yml
spring:
mail:
default-encoding: UTF-8
host: smtp.gmail.com
username: [email protected]
password: secret
port: 587
properties:
mail:
smtp:
auth: true
starttls:
enable: true
protocol: smtp
test-connection: false
如果要构造更高级的模板,请使用速度。请参阅示例。