学习在 Spring 中发送电子邮件 提供 JavaMailSender
接口。这是 通过 Gmail SMTP 服务器 发送电子邮件。我们将使用 javax.mail
maven 依赖项来发送电子邮件,同时在实现 JavaMailSender
接口。
按照maven project creation example创建一个新项目.现在将 Spring 依赖项与 javax.mail 一起导入。
<properties>
<spring.version>5.3.23</spring.version>
<email.version>1.6.2</email.version>
</properties>
<!-- Spring Context Support -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>${email.version}</version>
</dependency>
如果我们使用 Spring boot,那么我们可以通过简单地包含 spring 来帮助其自动配置功能-boot-starter-mail 启动器。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
入门模板将传递性地导入项目中所需的 jar。
[INFO] \- org.springframework.boot:spring-boot-starter-mail:jar:2.1.2.RELEASE:compile
[INFO] +- org.springframework:spring-context-support:jar:5.1.4.RELEASE:compile
[INFO] | \- org.springframework:spring-beans:jar:5.1.4.RELEASE:compile
[INFO] \- com.sun.mail:javax.mail:jar:1.6.2:compile
[INFO] \- javax.activation:activation:jar:1.1:compile
给定的是 JavaMailSender
的 Java 配置,它已被配置为使用 Gmail SMTP 设置,我们已经配置了一个示例电子邮件模板,该模板预先配置了发件人/收件人电子邮件和电子邮件文本。
我们可以根据需要进一步自定义配置。
import java.util.Properties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
@Configuration
public class EmailConfig
{
@Bean
public JavaMailSender getJavaMailSender()
{
JavaMailSender mailSender = new JavaMailSenderImpl();
mailSender.setHost("smtp.gmail.com");
mailSender.setPort(25);
mailSender.setUsername("admin@gmail.com");
mailSender.setPassword("password");
Properties props = mailSender.getJavaMailProperties();
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.debug", "true");
return mailSender;
}
@Bean
public SimpleMailMessage emailTemplate()
{
SimpleMailMessage message = new SimpleMailMessage();
message.setTo("somebody@gmail.com");
message.setFrom("admin@gmail.com");
message.setText("FATAL - Application crash. Save your job !!");
return message;
}
}
EmailService 类使用 applicationContext.xml 文件中配置的 beans 并使用它们发送消息。
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.stereotype.Service;
@Service("emailService")
public class EmailService
{
@Autowired
private JavaMailSender mailSender;
@Autowired
private SimpleMailMessage preConfiguredMessage;
/**
* This method will send compose and send a new message
* */
public void sendNewMail(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);
}
}
使用 JavaMailSender
接口的推荐方法是 MimeMessagePreparator
机制并使用 MimeMessageHelper
来填充消息。
@Autowired
private JavaMailSender mailSender;
public void sendMail() {
MimeMessagePreparator messagePreparator = new MimeMessagePreparator() {
public void prepare(MimeMessage mimeMessage) throws Exception {
MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true, "UTF-8");
message.setFrom("me@mail.com");
message.setTo("you@mail.com");
message.setSubject("Mail subject");
message.setText("some text <img src='cid:logo'>", true);
message.addInline("logo", new ClassPathResource("img/logo.gif"));
message.addAttachment("myDocument.pdf", new ClassPathResource("uploads/document.pdf"));
}
};
mailSender.send(messagePreparator);
}
我们可以将邮件属性配置到 application.properties 文件中,并使用 @Value 注释进行注入。
spring.mail.host=smtp.gmail.com
spring.mail.port=25
spring.mail.username=admin@gmail.com
spring.mail.password=password
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.transport.protocol=smtp
spring.mail.properties.mail.smtp.starttls.enable=true
#Timeouts
spring.mail.properties.mail.smtp.connectiontimeout=5000
spring.mail.properties.mail.smtp.timeout=5000
spring.mail.properties.mail.smtp.writetimeout=5000
如果您打算使用 Amazon SES 发送电子邮件,那么您可以使用以下属性:
spring.mail.host=email-smtp.us-west-2.amazonaws.com
spring.mail.username=username
spring.mail.password=password
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.transport.protocol=smtp
spring.mail.properties.mail.smtp.port=25
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
发送仅包含 HTML、没有附件或内联元素的简单邮件消息很容易。但是,内联元素和附件仍然是电子邮件客户端之间的主要兼容性问题。
请使用适当的 MULTIPART_MODE 并在将代码投入生产之前彻底测试代码。
要使用电子邮件附加文件,请使用 MimeMessageHelper
将文件附加到 MimeMessage
。
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());
}
}
有时,我们可能希望在电子邮件正文中附加内联资源,例如内联图像。使用指定的内容 ID 将内联资源添加到 MimeMessage。请务必先添加文本,然后再添加资源。如果您以相反的方式进行操作,则它不起作用。
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());
}
}
是时候测试 spring 邮件发送程序 代码了。我正在从测试代码发送两条消息。一个是在测试类本身中实例化和组合的,另一个是来自 applicationContext.xml
文件的预配置消息。
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
public class SpringEmailTest
{
public static void main(String[] args)
{
//Create the application context
ApplicationContext context = new FileSystemXmlApplicationContext
("classpath:com/howtodoinjava/core/email/applicationContext.xml");
//Get the mailer instance
EmailService mailer = (EmailService) context.getBean("emailService");
//Send a composed mail
mailer.sendMail("somebody@gmail.com", "Test Subject", "Testing body");
//Send a pre-configured mail
mailer.sendPreConfiguredMail("Exception occurred everywhere.. where are you ????");
}
}
上面的调用将发送电子邮件。
快乐学习!!
地址:https://www.cundage.com/article/send-email-with-spring-javamailsenderimpl-example.html