一、简介
Spring 提供了非常好用的 JavaMailSender 接口实现邮件发送。在 SpringBoot 的 Starter 模块中也为此提供了自动化配置。下面通过实例看看如何在 SpringBoot 中使用 JavaMailSender 发送邮件。
org.springframework.mail
是Spring Framework对邮件支持的基础包,发送邮件的核心接口MailSender
,SimpleMailMessage
封装了发送简单邮件的属性 ,这个包还包含检查异常的层次结构,这些层次结构在较低级别的邮件系统异常上提供了更高级别的抽象,而根异常是MailException
。
org.springframework.mail.javamail.JavaMailSender接口添加了专门的JavaMail功能,例如MIME消息支持到MailSender接口 (从其继承)。JavaMailSender还提供了一个名为org.springframework.mail.javamail.MimeMessagePreparator的回调接口,用于准备一个MimeMessage。
二、使用 SpringBoot 创建 Java Web 项目,添加邮件相关依赖包
在 SpringBoot 工程中的 pom.xml 中引入 spring-boot-starter-mail 依赖。
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-mail</artifactId>
</dependency>
三、使用
假设我们有一个名为OrderManager的业务类,如下面的示例所示:
public interface OrderManager {void placeOrder(Order order) throws MessagingException;
}
3、1MailSender和SimpleMailMessage的基本用法
public class SimpleOrderManager implements OrderManager {@Value("${spring.mail.from}")private String mailFrom;@Resourceprivate MailSender mailSender;public void placeOrder(Order order) {// Do the business calculations...// Call the collaborators to persist the order...// Create a thread safe "copy" of the template message and customize itSimpleMailMessage msg = new SimpleMailMessage();msg.setTo(order.getCustomer().getEmailAddress());msg.setFrom(mailFrom);msg.setText("Dear " + order.getCustomer().getFirstName()+ order.getCustomer().getLastName()+ ", thank you for placing order. Your order number is "+ order.getOrderNumber());try {this.mailSender.send(msg);} catch (MailException ex) {// simply log it and go on...System.err.println(ex.getMessage());}}}
3.2 JavaMailSender 和MimeMessagePreparator的用法
@Service
public class SimpleOrderManagerPreparator implements OrderManager {@Value("${spring.mail.from}")private String mailFrom;@Resourceprivate JavaMailSender mailSender;public void setMailSender(JavaMailSender mailSender) {this.mailSender = mailSender;}@Overridepublic void placeOrder(final Order order) {// Do the business calculations...// Call the collaborators to persist the order...MimeMessagePreparator preparator = new MimeMessagePreparator() {public void prepare(MimeMessage mimeMessage) throws Exception {mimeMessage.setRecipient(Message.RecipientType.TO,new InternetAddress(order.getCustomer().getEmailAddress()));mimeMessage.setFrom(new InternetAddress(mailFrom));mimeMessage.setText("Dear " + order.getCustomer().getFirstName() + " " +order.getCustomer().getLastName() + ", thanks for your order. " +"Your order number is " + order.getOrderNumber() + ".");}};try {this.mailSender.send(preparator);} catch (MailException ex) {// simply log it and go on...System.err.println(ex.getMessage());}}}
邮件代码可以作为一个切面,可以在OrderManager目标上的适当连接点处运行。
3.3 JavaMail MimeMessageHelper的使用
使用MimeMessageHelper可以代替基础的JavaMail API。
@Service
public class SimpleOrderManagerHelper implements OrderManager {@Value("${spring.mail.from}")private String mailFrom;@Resourceprivate JavaMailSender mailSender;public void placeOrder(Order order) throws MessagingException {// Do the business calculations...// Call the collaborators to persist the order...// Create a thread safe "copy" of the template message and customize itMimeMessage message = mailSender.createMimeMessage();MimeMessageHelper helper = new MimeMessageHelper(message);helper.setTo(order.getCustomer().getEmailAddress());helper.setFrom(mailFrom);helper.setText("Dear " + order.getCustomer().getFirstName()+ order.getCustomer().getLastName()+ ", thank you for placing order. Your order number is "+ order.getOrderNumber());try {this.mailSender.send(message);} catch (MailException ex) {// simply log it and go on...System.err.println(ex.getMessage());}}
}
3.4 发送附件
下面的示例将展示如何使用MimeMessageHelper发送带有单个JPEG图像附件的电子邮件:
@Service
public class SimpleOrderManagerAttachments implements OrderManager {@Value("${spring.mail.from}")private String mailFrom;@Resourceprivate JavaMailSender mailSender;public void placeOrder(Order order) throws MessagingException {// Do the business calculations...// Call the collaborators to persist the order...// Create a thread safe "copy" of the template message and customize itMimeMessage message = mailSender.createMimeMessage();MimeMessageHelper helper = new MimeMessageHelper(message, true);helper.setTo(order.getCustomer().getEmailAddress());helper.setFrom(mailFrom);helper.setText("Check out this image!");// let's attach the infamous windows Sample file (this time copied to c:/)FileSystemResource file = new FileSystemResource(new File("./sample.png"));helper.addAttachment("CoolImage.jpg", file);try {this.mailSender.send(message);} catch (MailException ex) {// simply log it and go on...System.err.println(ex.getMessage());}}
}
发送附件和内联资源
多部分电子邮件消息允许附件和内联资源。内联资源的示例包括要在邮件中使用但不想显示为附件的图像或样式表。
附件
下面的示例向您展示如何使用MimeMessageHelper发送带有单个JPEG图像附件的电子邮件:
3.5 内联资源
下面的示例将展示如何使用MimeMessageHelper发送带有内联映像的电子邮件:
@Service
public class SimpleOrderManagerInlineResources implements OrderManager {@Value("${spring.mail.from}")private String mailFrom;@Resourceprivate JavaMailSender mailSender;public void placeOrder(Order order) throws MessagingException {// Do the business calculations...// Call the collaborators to persist the order...// Create a thread safe "copy" of the template message and customize itMimeMessage message = mailSender.createMimeMessage();MimeMessageHelper helper = new MimeMessageHelper(message, true);helper.setTo(order.getCustomer().getEmailAddress());helper.setFrom(mailFrom);helper.setText("<html><body><img src='cid:identifier1234'></body></html>", true);// let's attach the infamous windows Sample file (this time copied to c:/)FileSystemResource res = new FileSystemResource(new File("./sample.png"));helper.addInline("identifier1234", res);try {this.mailSender.send(message);} catch (MailException ex) {// simply log it and go on...System.err.println(ex.getMessage());}}
}
通过使用指定的Content-ID 将内联资源添加到MimeMessage。添加文本和资源的顺序非常重要。请务必先添加文本,然后再添加资源。如果您以相反的方式进行操作,则无法正常工作。