spring mvc发送邮件(文本,html,inline、附件)

2021-07-24 135点热度 0人点赞 0条评论

在之前的文章,介绍了如何使用纯Java、JavaMail来发送邮件(解决中文乱码,发送HTML邮件),详见:https://blog.terrynow.com/2021/03/30/java-mail-smtp-send-email/

SpringBoot下发送邮件的文章,请查看:https://blog.terrynow.com/2021/07/26/java-springboot-send-mail-example-include-html-inline-attachment/

本篇介绍如何使用SpringMVC发送邮件,因为Spring对邮件做了进一步的封装,所以发邮件相对来说更优雅和简介一些。

首先配置文件增加javaMailSender(JavaMailSenderImpl实现类)

application-context.xml 增加如下:

<!-- 增加mail.properties配置文件,例如smtp帐号密码等 -->
<context:property-placeholder location="classpath:jdbc.properties,classpath:mail.properties"/>

<!-- 发送邮件配置 -->
<bean id="javaMailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
    <property name="host" value="${mail.host}"/>
    <property name="javaMailProperties">
        <props>
            <prop key="mail.smtp.auth">true</prop>
            <prop key="mail.smtp.timeout">25000</prop>
        </props>
    </property>
    <property name="username" value="${mail.username}"/>
    <property name="password" value="${mail.password}"/>
    <property name="defaultEncoding" value="UTF-8"/>
</bean>

mail.properties如下(smtp发送邮件的帐号具体查看邮件供应商的smtp设置文档)

mail.host=smtp.example.com
[email protected]
mail.password=password
[email protected]
mail.fromName=ServiceBot

新建一个发邮件的工具类MailUtils.java

里面会注入刚才我们在application-context.xml的javaMailSender

@Component
public class MailUtils {
    @Autowired
    JavaMailSender javaMailSender;

    @Value("${mail.from}")
    private String mailFrom;
    @Value("${mail.fromName}")
    private String mailFromName;

    /**
     * 发送简单邮件
     *
     * @param toAddress 邮件接受者邮件地址
     * @param title     邮件主题
     * @param text      邮件文本内容
     */
    public void sendSimpleMail(String toAddress, String title, String text) {
        SimpleMailMessage message = new SimpleMailMessage();
//        message.setFrom(mailFrom);
        message.setFrom(mailFromName + " <" + mailFrom + ">");
        message.setTo(toAddress);
        message.setSubject(title);
        message.setText(text);
        javaMailSender.send(message);
    }

    /**
     * html邮件
     *
     * @param toAddress 邮件接受者邮件地址
     * @param title     邮件主题
     * @param html      邮件Html内容
     */
    public void sendHtmlMail(String toAddress, String toName, String title, String html) throws Exception {
        MimeMessage message = null;
        message = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setFrom(mailFrom, mailFromName);
        if (toName != null && toName.trim().length() > 0) {
            helper.setTo(new InternetAddress(toAddress, toName));
        } else {
            helper.setTo(toAddress);
        }
        helper.setSubject(title);
        helper.setText(html, true);

        javaMailSender.send(message);
    }
}

调用示例

这样我们就可以在Controller或者Service中,直接调用MailUtils发送邮件了:

@Autowired
MailUtils mailUtils;

public void test() {
    try {
        String html = "<body><div><h2>测试HTML内容</h2></div></body>";
        mailUtils.sendHtmlMail("[email protected]", "小张", "测试邮件主题", html);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

如果你要发送更复杂的内容,比如附件、inline的图片等等,那么可以直接@Autowired JavaMailSender javaMailSender; 直接操作javaMailSender:

@Autowired
JavaMailSender javaMailSender;

public void test() {
    //<img src='cid:test.jpg' />内嵌图片
    String html = "<body><div><h2>测试HTML内容</h2><img src='cid:test.jpg' width='120' height='120' style='border: none; width: 120px; height: 120px;' /></div></body>";
    message = javaMailSender.createMimeMessage();
    MimeMessageHelper helper = new MimeMessageHelper(message, true);
    helper.setFrom(mailFrom, mailFromName); //可以设置发件人的地址和昵称
    if (toName != null && toName.trim().length() > 0) {
        helper.setTo(new InternetAddress(toAddress, toName)); //可以设置收件人的地址和昵称
    } else {
        helper.setTo(toAddress);
    }
    helper.setSubject(title);//title主题
    helper.setText(html, true);

    helper.addInline("test.jpg", new File("xxx"));//发送HTML内嵌的图片
    helper.addAttachment(xxx);//发送附件

    javaMailSender.send(message);
}

admin

这个人很懒,什么都没留下

文章评论

*

code