原文: https://howtodoinjava.com/spring-boot2/send-email-with-attachment/
了解如何借助JavaMailSender在 spring boot 应用程序中发送电子邮件,以发送简单电子邮件以及带有附件的电子邮件。
1. Maven
在 Spring Boot 应用程序中,包括spring-boot-starter-mail依赖项。
pom.xml
<parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.1.8.RELEASE</version></parent><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-mail</artifactId></dependency></dependencies>
2. SMTP 配置
使用 spring boot,我们可以在application.properties文件中配置 SMTP 设置。
2.1. 邮箱
application.properties
debug=truespring.mail.host=smtp.gmail.comspring.mail.port=25spring.mail.username=admin@gmail.comspring.mail.password=xxxxxx# Other propertiesspring.mail.properties.mail.debug=truespring.mail.properties.mail.transport.protocol=smtpspring.mail.properties.mail.smtp.auth=truespring.mail.properties.mail.smtp.connectiontimeout=5000spring.mail.properties.mail.smtp.timeout=5000spring.mail.properties.mail.smtp.writetimeout=5000# TLS , port 587spring.mail.properties.mail.smtp.starttls.enable=true# SSL, post 465#spring.mail.properties.mail.smtp.socketFactory.port = 465#spring.mail.properties.mail.smtp.socketFactory.class = javax.net.ssl.SSLSocketFactory
为了能够使用两因素身份验证并关闭“允许不太安全的应用程序”选项,强烈建议使用应用程序密码代替 Gmail 密码。
如果您可以访问下面的 SMTP 服务器,请在下面自由使用。
2.2. Outlook
如果它是某些公司服务器,请从管理员那里查找此信息。
Outlook Configuration
spring.mail.host=smtp-mail.outlook.comspring.mail.port=587spring.mail.username=outlookuserid@outlook.comspring.mail.password=xxxxxxspring.mail.properties.mail.protocol=smtpspring.mail.properties.mail.tls=truespring.mail.properties.mail.smtp.auth=truespring.mail.properties.mail.smtp.starttls.enable=truespring.mail.properties.mail.smtp.ssl.trust=smtp-mail.outlook.com
2.3. AWS SES
从您的 AWS 设置页面中找到相关配置。阅读更多。
AWS SES Configuration
spring.mail.host=email-smtp.us-east-1.amazonaws.comspring.mail.port=465spring.mail.username=xxxxxxxxxxxspring.mail.password=xxxxxxxxxxxspring.mail.properties.mail.smtp.starttls.enable=truespring.mail.properties.mail.smtp.starttls.required=truespring.mail.properties.mail.smtp.ssl.enavle=truespring.mail.properties.mail.protocol=smtpsspring.mail.properties.mail.smtps.auth=true
3. 预先配置的电子邮件模板
我们可以创建电子邮件模板以供每次重用 – 我们必须定期或在任何特定事件或持续时间内发送电子邮件。 在给定的示例中,我们正在使用SimpleMailMessage创建一个非常简单的纯文本电子邮件。
EmailConfig.java
import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.mail.SimpleMailMessage;@Configurationpublic class EmailConfig{@Beanpublic SimpleMailMessage emailTemplate(){SimpleMailMessage message = new SimpleMailMessage();message.setTo("user@gmail.com");message.setFrom("admin@gmail.com");message.setSubject("Important email");message.setText("FATAL - Application crash. Save your job !!");return message;}}
4. 发送简单的电子邮件
为了发送不同类型的电子邮件,我们创建了一个EmailService类,该类可以采用在发送电子邮件之前在电子邮件中设置所需的参数。
EmailService.java
@Service("emailService")public class EmailService{@Autowiredprivate JavaMailSender mailSender;@Autowiredprivate SimpleMailMessage preConfiguredMessage;/*** This method will send compose and send the message* */public void sendMail(String to, String subject, String body){SimpleMailMessage message = new SimpleMailMessage();message.setTo(to);message.setSubject(subject);message.setText(body);mailSender.send(message);}/*** This method will send a pre-configured message* */public void sendPreConfiguredMail(String message){SimpleMailMessage mailMessage = new SimpleMailMessage(preConfiguredMessage);mailMessage.setText(message);mailSender.send(mailMessage);}}
5. 发送带有附件的电子邮件
使用MimeMessageHelper发送多媒体电子邮件,该电子邮件用于配置MimeMessage。 这些 mime 消息是富文本电子邮件。
Email with attachment
@Autowiredprivate JavaMailSender mailSender;public void sendMailWithAttachment(String to, String subject, String body, String fileToAttach){MimeMessagePreparator preparator = new MimeMessagePreparator(){public void prepare(MimeMessage mimeMessage) throws Exception{mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(to));mimeMessage.setFrom(new InternetAddress("admin@gmail.com"));mimeMessage.setSubject(subject);mimeMessage.setText(body);FileSystemResource file = new FileSystemResource(new File(fileToAttach));MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);helper.addAttachment("logo.jpg", file);}};try {mailSender.send(preparator);}catch (MailException ex) {// simply log it and go on...System.err.println(ex.getMessage());}}
6. 发送带有内嵌图像的电子邮件
富文本格式包括介于文本内容之间的媒体内容。 为此,我们必须使用MimeMessageHelper的addInline()方法。
Email with inline images
@Autowiredprivate JavaMailSender mailSender;public void sendMailWithInlineResources(String to, String subject, String fileToAttach){MimeMessagePreparator preparator = new MimeMessagePreparator(){public void prepare(MimeMessage mimeMessage) throws Exception{mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(to));mimeMessage.setFrom(new InternetAddress("admin@gmail.com"));mimeMessage.setSubject(subject);MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);helper.setText("<html><body><img src='cid:identifier1234'></body></html>", true);FileSystemResource res = new FileSystemResource(new File(fileToAttach));helper.addInline("identifier1234", res);}};try {mailSender.send(preparator);}catch (MailException ex) {// simply log it and go on...System.err.println(ex.getMessage());}}
7. Spring Boot 发送电子邮件演示
要使用上述配置发送电子邮件,请更新application.properties文件中的spring.mail.username和spring.mail.password属性。
现在执行EmailService的方法发送电子邮件。
Application.java
import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.CommandLineRunner;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplicationpublic class Application implements CommandLineRunner{@Autowiredprivate EmailService emailService;public static void main(String[] args) {SpringApplication.run(Application.class, args);}@Overridepublic void run(String... args){emailService.sendMail("lokeshgupta1981@gmail.com", "Hi", "Ho ho ho");emailService.sendPreConfiguredMail("Ho ho ho");}}
请给我发送有关通过 SpringBoot发送电子邮件的问题。
学习愉快!
