Fork me on GitHub

springboot-mail发邮件,不需要邮件服务器

很简单 步骤走起->

1.需要一个邮箱账号,我以163邮箱为例,先开启第三方服务后获得密码,后面用来邮箱登录

2.加入mail 依赖

 

3.properties配置账号和第三方服务密码(不是邮箱密码,是第一步中的密码)

4.简单看下项目结构:

5.直接上serviceImpl

package com.idress.inter.impl;

import com.idress.inter.MailService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;

@Component
public class MailServiceImpl implements MailService {

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

    @Autowired
    private JavaMailSender mailSender;

    @Value("${spring.mail.from.addr}")
    private String from;//由谁发出邮件 is my

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

        try {
            mailSender.send(message);
            logger.info("简单邮件已经发送。");
        } catch (Exception e) {
            logger.error("发送简单邮件时发生异常!", e);
        }

    }

    //发送html格式邮件
    @Override
    public void sendHtmlMail(String to, String subject, String content) {
        MimeMessage message = mailSender.createMimeMessage();
        try {
            //true表示需要创建一个multipart message
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);

            mailSender.send(message);
            logger.info("html邮件发送成功");
        } catch (MessagingException e) {
            logger.error("发送html邮件时发生异常!", e);
        }
    }

    //发送带附件的邮件
    @Override
    public void sendAttachmentsMail(String to, String subject, String content, String filePath) {
        MimeMessage message = mailSender.createMimeMessage();

        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);

            FileSystemResource file = new FileSystemResource(new File(filePath));
            String fileName = filePath.substring(filePath.lastIndexOf(File.separator));
            helper.addAttachment(fileName, file);

            mailSender.send(message);
            logger.info("带附件的邮件已经发送。");
        } catch (MessagingException e) {
            logger.error("发送带附件的邮件时发生异常!", e);
        }
    }

    /**
     * 嵌入静态资源的邮件
     */
    @Override
    public void sendInlineResourceMail(String to, String subject, String content, String rscPath, String rscId) {
        MimeMessage message = mailSender.createMimeMessage();

        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);

            FileSystemResource res = new FileSystemResource(new File(rscPath));
            helper.addInline(rscId, res);

            mailSender.send(message);
            logger.info("嵌入静态资源的邮件已经发送。");
        } catch (MessagingException e) {
            logger.error("发送嵌入静态资源的邮件时发生异常!", e);
        }
    }

 

6.junt测试走起

package com.idress;

import com.idress.inter.MailService;
import com.sun.xml.internal.bind.CycleRecoverable;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.core.env.Environment;
import org.springframework.test.context.junit4.SpringRunner;
import org.thymeleaf.context.Context;
import org.thymeleaf.spring4.SpringTemplateEngine;

@RunWith(SpringRunner.class)
@SpringBootTest
public class Sb10MailApplicationTests {

   @Autowired
   private MailService mailService;

   @Test
   public void contextLoads() {
      mailService.sendSimpleMail("2473538988@qq.com","恭喜你的简历被我们查看"," 请您....");
   }

   @Test
   public void testHtmlMail() throws Exception{
      for (int i = 0; i < 25; i++) {

         String content = "<html>\n" +
               "<body>\n" +
               "    <h3>hello world ! 这是一封Html邮件!</h3>\n" +
               "</body>\n" +
               "</html>";
         mailService.sendHtmlMail("whatarey0206@qq.com", "test simple mail", content);
      }

   }
   //发送待附件的邮件
   @Test
   public void sendAttachmentsMail() {
         String filePath = "E:\\img01.PNG";
         mailService.sendAttachmentsMail("2633992679@qq.com", "主题:带附件的邮件", "有附件,请查收!", filePath);
   }

   @Test
   public void sendInlineResourceMail() {
      String rscId = "neo006";
      String content="<html><body>这是有图片的邮件:<img src='cid:" + rscId + "' ></body></html>";
      String imgPath = "E:\\img01.PNG";

      mailService.sendInlineResourceMail("1544303828@qq.com", "主题:这是有图片的邮件", content, imgPath, rscId);
   }

   //使用邮件模板

   @Autowired
   private SpringTemplateEngine templateEngine;

   @Test
   public void sendTemplateMail() {
      //创建邮件正文
      Context context = new Context();
      context.setVariable("id", "006");
      String emailContent = templateEngine.process("emailTemplate", context);

      mailService.sendHtmlMail("1544303828@qq.com","主题:这是模板邮件",emailContent);
   }
}

7.邮箱模板(thymeleaf)

 转载http://www.ityouknow.com/springboot/2017/05/06/springboot-mail.html

一位大神 纯洁的微笑

posted @ 2018-08-31 15:03  youxiu326  阅读(742)  评论(0编辑  收藏  举报