Spring boot 发送邮箱

一、简介

        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;
    @Resource
    private 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 it
        SimpleMailMessage 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;
    @Resource
    private JavaMailSender mailSender;

    public void setMailSender(JavaMailSender mailSender) {
        this.mailSender = mailSender;
    }

    @Override
    public 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;
    @Resource
    private 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 it

        MimeMessage 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;
    @Resource
    private 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 it

        MimeMessage 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;
    @Resource
    private 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 it

        MimeMessage 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。添加文本和资源的顺序非常重要。请务必先添加文本,然后再添加资源。如果您以相反的方式进行操作,则无法正常工作。

  • 10
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值