Spring Boot 学习笔记 6 : spring-boot-starter-mail

  1. 在 pom.xml 文件中添加依赖:

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-mail</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
  2. 使用 163 邮箱发送邮件,在 application.properties 文件中添加配置:

    
    #server
    
    server.port=80
    
    #spring.mail
    
    spring.mail.host=smtp.163.com
    spring.mail.username=smileorsilence@163.com
    spring.mail.password=授权码
    spring.mail.receiver=收件人
    
    #spring.mail.properties
    
    spring.mail.properties.mail.smtp.auth=true
    spring.mail.properties.mail.smtp.timeout=30000
    
    #spring.thymeleaf
    
    spring.thymeleaf.prefix=classpath:/templates/
    spring.thymeleaf.suffix=.html
    spring.thymeleaf.mode=LEGACYHTML5
    spring.thymeleaf.encoding=utf-8
    spring.thymeleaf.cache=false
  3. 编写配置类:

    package com.springboot.config.mail;
    
    import lombok.Data;
    import org.springframework.boot.context.properties.ConfigurationProperties;
    
    import java.nio.charset.Charset;
    import java.util.HashMap;
    import java.util.Map;
    
    /**
     * @author smileorsilence
     * @date 2018/04/10
     */
    @Data
    @ConfigurationProperties(prefix = "spring.mail")
    public class MailProperties {
    
        /**
         * 邮件服务器主机名
         * 163邮箱 : smtp.163.com
         * QQ邮箱 : smtp.qq.com
         */
        private String host;
    
        /**
         * 邮件服务器端口号
         * 默认25
         */
        private Integer port = 25;
    
        /**
         * 邮箱用户名
         */
        private String username;
    
        /**
         * 邮箱第三方授权码
         */
        private String password;
    
        /**
         * 邮件传输协议
         * 默认smtp
         */
        private String protocol = "smtp";
    
        /**
         * 邮件编码
         * 默认UTF-8
         */
        private Charset charset = Charset.forName("UTF-8");
    
        private Map<String, String> properties;
    
        public MailProperties() {
            this.properties = new HashMap();
        }
    
    }
    package com.springboot.config.mail;
    
    import lombok.extern.slf4j.Slf4j;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.context.properties.EnableConfigurationProperties;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.mail.javamail.JavaMailSender;
    import org.springframework.mail.javamail.JavaMailSenderImpl;
    
    import java.util.Properties;
    
    /**
     * @author smileorsilence
     * @date 2018/04/10
     */
    @Slf4j
    @Configuration
    @EnableConfigurationProperties(MailProperties.class)
    public class MailConfiguration {
    
        @Autowired
        private MailProperties mailProperties;
    
        @Bean
        public JavaMailSender javaMailSender() {
            JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();
            javaMailSender.setHost(mailProperties.getHost());
            javaMailSender.setPort(mailProperties.getPort().intValue());
            javaMailSender.setUsername(mailProperties.getUsername());
            javaMailSender.setPassword(mailProperties.getPassword());
            javaMailSender.setProtocol(mailProperties.getProtocol());
            javaMailSender.setDefaultEncoding(mailProperties.getCharset().name());
    
            Properties properties = new Properties();
            if (!mailProperties.getProperties().isEmpty()) {
                properties.putAll(mailProperties.getProperties());
            }
            javaMailSender.setJavaMailProperties(properties);
    
            log.info("mailProperties : {}", mailProperties);
            return javaMailSender;
        }
    }
  4. 编写Service接口:

    package com.springboot.service;
    
    /**
     * @author smileorsilence
     * @date 2018/04/10
     */
    public interface MailService {
    
        void sendSimpleMail(String to, String subject, String content);
    
        void sendAttachmentMail(String to, String subject, String content, String fileName);
    
        void sendTemplateMail(String to, String subject, String templateName);
    }
  5. 编写Service实现类:

    package com.springboot.service.impl;
    
    import com.springboot.service.MailService;
    import lombok.extern.slf4j.Slf4j;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.core.io.ClassPathResource;
    import org.springframework.mail.MailException;
    import org.springframework.mail.SimpleMailMessage;
    import org.springframework.mail.javamail.JavaMailSender;
    import org.springframework.mail.javamail.MimeMessageHelper;
    import org.springframework.stereotype.Service;
    import org.thymeleaf.context.Context;
    import org.thymeleaf.spring4.SpringTemplateEngine;
    
    import javax.mail.MessagingException;
    import javax.mail.internet.MimeMessage;
    
    /**
     * @author smileorsilence
     * @date 2018/01/24
     */
    @Slf4j
    @Service
    public class MailServiceImpl implements MailService {
    
        @Autowired
        private JavaMailSender javaMailSender;
    
        @Autowired
        private SpringTemplateEngine templateEngine;
    
        /**
         * 图片路径
         */
        private static final String IMAGE_PATH = "static/images/";
    
        /**
         * 邮件模板路径
         */
        private static final String TEMPLATE_PATH = "mail/";
    
        @Value("${spring.mail.username}")
        private String from;
    
        @Override
        public void sendSimpleMail(String to, String subject, String content) {
            log.info("{} sendSimpleMail to {}, subject : {}, content : {}", from, to, subject, content);
    
            SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom(from);
            message.setTo(to);
            message.setSubject(subject);
            message.setText(content);
    
            log.info("{} sendSimpleMail begin", from);
            try {
                javaMailSender.send(message);
            } catch (MailException e) {
                log.warn("sendSimpleMail MailException : {}", e.getMessage());
            }
            log.info("{} sendSimpleMail finish", from);
        }
    
        @Override
        public void sendAttachmentMail(String to, String subject, String content, String imageName) {
            log.info("{} sendAttachmentMail to {}, subject : {}, content : {}, imageName : {}", from, to, subject, content, imageName);
    
            MimeMessage message = javaMailSender.createMimeMessage();
            try {
                MimeMessageHelper helper = new MimeMessageHelper(message, true);
                helper.setFrom(from);
                helper.setTo(to);
                helper.setSubject(subject);
                helper.setText(content);
    
    //            File image = new File(IMAGE_PATH + imageName);
                ClassPathResource image = new ClassPathResource(IMAGE_PATH + imageName);
                helper.addAttachment(imageName, image);
            } catch (MessagingException e) {
                log.warn("sendAttachmentMail MessagingException : {}", e.getMessage());
            }
    
            log.info("{} sendAttachmentMail begin", from);
            try {
                javaMailSender.send(message);
            } catch (MailException e) {
                log.warn("sendAttachmentMail MailException : {}", e.getMessage());
            }
            log.info("{} sendAttachmentMail finish", from);
        }
    
        @Override
        public void sendTemplateMail(String to, String subject, String templateName) {
            log.info("{} sendTemplateMail to {}, subject : {}, templateName : {}", from, to, subject, templateName);
    
            MimeMessage message = javaMailSender.createMimeMessage();
            try {
                MimeMessageHelper helper = new MimeMessageHelper(message, true);
                helper.setFrom(from);
                helper.setTo(to);
                helper.setSubject(subject);
    
    //            ClassPathResource backgroundImage = new ClassPathResource(IMAGE_PATH + "peachblossom.jpg");
    //            helper.addInline("backgroundImage", backgroundImage);
    
                Context context = new Context();
                context.setVariable("receiver", to);
                String content = templateEngine.process(TEMPLATE_PATH + templateName, context);
                helper.setText(content);
            } catch (MessagingException e) {
                log.warn("sendTemplateMail MessagingException : {}", e.getMessage());
            }
    
            log.info("{} sendTemplateMail begin", from);
            try {
                javaMailSender.send(message);
            } catch (MailException e) {
                log.warn("sendTemplateMail MailException : {}", e.getMessage());
            }
            log.info("{} sendTemplateMail finish", from);
        }
    }
  6. 编写Junit单元测试:

    package com.springboot.service.impl;
    
    import com.springboot.service.MailService;
    import lombok.extern.slf4j.Slf4j;
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.boot.test.context.SpringBootTest;
    import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
    
    /**
     * @author smileorsilence
     * @date 2018/04/10
     */
    @Slf4j
    @RunWith(SpringJUnit4ClassRunner.class)
    @SpringBootTest
    public class MailServiceImplTest {
    
        @Autowired
        private MailService mailService;
    
        @Value("${spring.mail.receiver}")
        private String to;
    
        @Test
        public void sendSimpleMail() throws Exception {
            String subject = "sendSimpleMail";
            String content = "更无柳絮因风起,唯有葵花向日倾";
            mailService.sendSimpleMail(to, subject, content);
            log.info("test sendSimpleMail to {}", to);
        }
    
        @Test
        public void sendAttachmentMail() throws Exception {
            String subject = "sendAttachmentMail";
            String content = "况是青春日将暮,桃花乱落如红雨";
            mailService.sendAttachmentMail(to, subject, content, "peachblossom.jpg");
            log.info("test sendAttachmentMail to {}", to);
        }
    
        @Test
        public void sendTemplateMail() throws Exception {
            String subject = "sendTemplateMail";
            String templateName = "mail";
            mailService.sendTemplateMail(to, subject, templateName);
            log.info("test sendTemplateMail to {}", to);
        }
    }
  7. 登录163邮箱并启用授权码:

    启用授权码

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值