springboot发送邮件

这几天项目中有使用到邮箱绑定,看到springboot封装了发送邮件,故查询资料自己整理的笔记如下(附带源码):
对应的部分pom

  <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.5.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
 		<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>

创建发送邮件的接口:


/**
 * Created by 东东 on 2018/10/28.
 *
 * @Description 发送邮件部分接口
 */
public interface MailService {

    /**
     * @Description //TODO 发送简单的文本文件,to:收件人 subject:主题 content:内容
     * @Param [to, subject, content]
     **/
    public void sendSimpleMail(String to, String subject, String content);

    /**
     * @Description //TODO 发送html,to:收件人 subject:主题 content:内容
     * @Param [to, subject, content]
     **/
    public void sendHtmlMail(String to, String subject, String content);

    /**
     * @param to
     * @param subject
     * @param content
     * @param filePath
     * @throws MessagingException
     * @Description //TODO 发送一个带附件的邮件,to:收件人,subject:主题,content:主题,filePath:附件的路径
     */
    public void sendAttachmentMail(String to, String subject, String content, String filePath);
    
    public void sendInlineResourceMail(String to, String subject, String content, String rscPath);
}

对应的实现类:

/**
 * Created by 东东 on 2018/10/28.
 */
@Service
public class MailServiceImpl implements MailService {

    //这个是发送人的用户名,如13707259624@163.com
    @Value("${spring.mail.username}")
    private String from;

    //用来发送邮件
    @Autowired
    private JavaMailSender mailSender;

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public void sendSimpleMail(String to, String subject, String content) {
        SimpleMailMessage mailMessage = new SimpleMailMessage();
        mailMessage.setFrom(from);
        mailMessage.setTo(to);
        mailMessage.setSubject(subject);
        mailMessage.setText(content);
        mailSender.send(mailMessage);
    }

    @Override
    public void sendHtmlMail(String to, String subject, String content) {
        MimeMessage message = mailSender.createMimeMessage();
        try {
            MimeMessageHelper messageHelper = new MimeMessageHelper(message);

            messageHelper.setFrom(from);
            messageHelper.setTo(to);
            messageHelper.setSubject(subject);
            //将content里面的标签进行处理,否则为正常的文本处理
            messageHelper.setText(content, true);
        } catch (MessagingException e) {
            logger.error("something wrong...");
            e.printStackTrace();
        }
        mailSender.send(message);

    }

    @Override
    public void sendAttachmentMail(String to, String subject, String content, String filePath) {

        MimeMessage mimeMessage = mailSender.createMimeMessage();
        try {
            //带上附件传true,否则会报错.
            //Not in multipart mode - create an appropriate MimeMessageHelper via a constructor that takes a 'multipart' flag if you need to set alternative texts or add inline elements or attachments.
            MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true);
            messageHelper.setFrom(from);

            messageHelper.setTo(to);
            messageHelper.setSubject(subject);
            messageHelper.setText(content);

            //设置附件
            FileSystemResource fileSystemResource = new FileSystemResource(new File(filePath));
            String filename = fileSystemResource.getFilename();
            messageHelper.addAttachment(filename, fileSystemResource);
        } catch (MessagingException e) {
            logger.error("something wrong...");
            e.printStackTrace();
        }
        mailSender.send(mimeMessage);
    }

    @Override
    public void sendInlineResourceMail(String to, String subject, String content, String rscPath) {

        MimeMessage mimeMessage = mailSender.createMimeMessage();
        try {
            //带上附件传true,否则会报错.
            //Not in multipart mode - create an appropriate MimeMessageHelper via a constructor that takes a 'multipart' flag if you need to set alternative texts or add inline elements or attachments.
            MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true);
            messageHelper.setFrom(from);
            messageHelper.setTo(to);
            messageHelper.setSubject(subject);
            messageHelper.setText(content,true);
            //构造邮件内部的图片
            FileSystemResource file = new FileSystemResource(new File(rscPath));
            //对应的图片src路径,我就简单写一下。。。
            messageHelper.addInline("img", file);
        } catch (MessagingException e) {
            logger.error("something wrong...");
            e.printStackTrace();
        }
        mailSender.send(mimeMessage);
    }
}

对应的测试类:

/**
 * Created by 东东 on 2018/10/28.
 */
@RunWith(SpringRunner.class)
@SpringBootTest
public class MailSendTest {

    @Autowired
    private MailService mailService;

    @Autowired
    private TemplateEngine engine;

    @Test
    public void test01() {
        String to ="13707259624@163.com";
        String content = "大家好,这是一个简单的文本发送";
        //主题
        String subject = "来了,小老弟";

        mailService.sendSimpleMail(to,subject,content);

    }

    @Test
    public void test02() {
        String to ="13707259624@163.com";
        String content = "<html> <h1 style=\"color:red \" >大家好,这是一个简单的html发送</h1></html>";
        //主题
        String subject = "来了,小老弟";

        mailService.sendHtmlMail(to,subject,content);

    }

    @Test
    //发送html文件
    public void test03() {
        String to ="13707259624@163.com";
        //org.thymeleaf.context.Context;thymeleaf模板的context
        Context context = new Context();
        context.setVariable("id",1);
        String content = engine.process("MailTest", context);
        //主题
        String subject = "来了,小老弟";

        mailService.sendHtmlMail(to,subject,content);

    }

    @Test
    public void test04() {
        String to ="13707259624@163.com";
        String content = "大家好,这是一个简单的带附件发送";
        //主题
        String subject = "来了,小老弟";

        String filePath = "C:\\Users\\东东\\Downloads\\aaa.docx";
        mailService.sendAttachmentMail(to,subject,content,filePath);

    }

    @Test
    //发送图片
    public void test05() {
        String to ="13707259624@163.com";
        //src对应img
        String content = "<html><body>大家好,这是一个简单的图片发送:<img src=\'cid:img" + "\'></img></body></html>";
        //主题
        String subject = "来了,小老弟";
        //图片地址
        String filePath = "C:\\Users\\东东\\Pictures\\307826854021937449.jpg";
        mailService.sendInlineResourceMail(to,subject,content,filePath);
    }
}

都封装好了,使用起来比较简单=-=,自己看看就懂得了。。。后期还可以整合mq实现发邮件…有空整理一下.
源码地址:https://github.com/stackXu/Spring-Boot-Mail

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值