springboot实现发邮件功能-------未加定时器

在pom.xml中添加

<!-- 邮件 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-mail</artifactId>
		</dependency>

添加配置文件application.properties

#####qq\u90AE\u7BB1#####
#QQ\u90AE\u4EF6\u670D\u52A1\u5730\u5740
spring.mail.host=smtp.qq.com
#\u7528\u6237\u540D
[email protected]  
#\u5BC6\u7801\uFF08\u6388\u6743\u7801\uFF09
spring.mail.password=aktgxsvwwexedahj
#\u9ED8\u8BA4\u7F16\u7801UTF-8
spring.mail.default-encoding=UTF-8
#\u7AEF\u53E3\uFF0C\u8FD9\u91CC\u6DFB\u52A0587\u5373\u53EF
spring.mail.port=587
#\u90AE\u4EF6\u53D1\u9001\u4EBA
[email protected]

controller:

package com.heeexy.example.controller;

import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import com.heeexy.example.service.EmailService;

@RestController
@RequestMapping("/email")
public class EmailController {
	
	@Autowired
	private EmailService emailService;
	
	@Autowired
	 private TemplateEngine templateEngine;
	
	//发送简单邮件
	@Test
	public void sendSimpleMail() throws Exception {
	    emailService.sendSimpleEmail("[email protected]","this is simple mail"," hello LingDu");
	}
	
	//发送带html的邮件
	  @Test
	    public void sendHtmlMail() throws Exception {
	        String content="<html>\n" +
	                "<body>\n" +
	                "    <h3>hello world ! 这是一封Html邮件!</h3>\n" +
	                "</body>\n" +
	                "</html>";
	        emailService.sendHtmlEmail("[email protected]","this is html mail",content);
	    }
	  
	  //发送带附件的文件
	  @Test
	  public void sendAttachmentsMail() {
	      String filePath="f:\\pikaqiu.png";
	      emailService.sendAttachmentsEmail("[email protected]", "主题:带附件的邮件", "收到附件,请查收!", filePath);

	  }
	  
	  //发送带静态资源的文件
	  @Test
	  public void sendInlineResourceMail() {
	      String rscId = "001";
	      String content="<html><body>这是有图片的邮件:<img src=\'cid:" + rscId + "\' ></body></html>";
	      String imgPath = "f:\\pikaqiu.png";

	      emailService.sendInlineResourceEmail("[email protected]", "主题:这是有图片的邮件", content, imgPath, rscId);
	  }
	 
	  
	  //解析模板并发送
	//发送模版消息
	    @Test
	    public void sendTemplateMail() {
	        //创建邮件正文
	        Context context = new Context();
	        context.setVariable("username", "LingDu");
	        String emailContent = templateEngine.process("email", context);

	        System.out.println(emailContent);
	        emailService.sendHtmlEmail("[email protected]","主题:这是模板邮件",emailContent);
	    }



	

}


service:

package com.heeexy.example.service;

/**
 * 发送邮件服务
 * @author LingDu
 * 2017.8.18
 */
public interface EmailService {
    /**
     * 发送简单邮件
     * @param to
     * @param subject
     * @param content
     */
    public void sendSimpleEmail(String to, String subject, String content);
    /**
     * 发送html格式邮件
     * @param to
     * @param subject
     * @param content
     */
    public void sendHtmlEmail(String to, String subject, String content);
    /**
     * 发送带附件的邮件
     * @param to
     * @param subject
     * @param content
     * @param filePath
     */
    public void sendAttachmentsEmail(String to, String subject, String content, String filePath);
    /**
     * 发送带静态资源的邮件
     * @param to
     * @param subject
     * @param content
     * @param rscPath
     * @param rscId
     */
    public void sendInlineResourceEmail(String to, String subject, String content, String rscPath, String rscId);
}


serviceImpl:

package com.heeexy.example.service.impl;

import java.io.File;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

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 com.heeexy.example.service.EmailService;

@Component
public class EmailServiceImpl implements EmailService {

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

    @Autowired
    private JavaMailSender mailSender;//spring 提供的邮件发送类

    @Value("${mail.fromMail.addr}")
    private String from;

    @Override
    public void sendSimpleEmail(String to, String subject, String content) {
        SimpleMailMessage message = new SimpleMailMessage();//创建简单邮件消息
        message.setFrom(from);//设置发送人
        message.setTo(to);//设置收件人

        /* String[] adds = {"[email protected]","[email protected]"}; //同时发送给多人
        message.setTo(adds);*/

        message.setSubject(subject);//设置主题
        message.setText(content);//设置内容
        try {
            mailSender.send(message);//执行发送邮件
            logger.info("简单邮件已经发送。");
        } catch (Exception e) {
            logger.error("发送简单邮件时发生异常!", e);
        }
    }
   
    
    @Override
    public void sendHtmlEmail(String to, String subject, String content) {
        MimeMessage message = mailSender.createMimeMessage();//创建一个MINE消息

        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 sendAttachmentsEmail(String to, String subject, String content, String filePath) {
        MimeMessage message = mailSender.createMimeMessage();//创建一个MINE消息

        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);// 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 sendInlineResourceEmail(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));

            //添加内联资源,一个id对应一个资源,最终通过id来找到该资源
            helper.addInline(rscId, res);//添加多个图片可以使用多条 <img src='cid:" + rscId + "' > 和 helper.addInline(rscId, res) 来实现

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

    }

}

在templates下建立email.html:
 

<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8"/>
        <title>Title</title>
    </head>
    <body>
        <h4 th:text="|尊敬的:${username} 用户:|"></h4><br /><br />

       &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;恭喜您入住xxx平台VIP会员,您将享受xxx优惠福利,同时感谢您对xxx的关注与支持并欢迎您使用xx的产品与服务。<br />
       &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;...
    </body>
</html>

vue前台:
 

 <el-button type="primary" icon="edit"   v-if="hasPerm('sp:sendSimpleEmail')" @click="sendemail(scope.$index)">发邮件</el-button>


methods:{
    sendemail($index){
          var ids = [];
          sels.forEach(element => {
          ids.push(element.id);
         });

      var id = ids.join(",");

      this.$confirm("你确定要发邮件吗?", "提示")
        .then(() => {
          var url = this.HOST + "/sp/sendSimpleEmail";
          this.$axios
            .post(url, {
              id
            })
            .then(dara => {
              console.log(dara);
              this.getList();
              this.dialogFormVisible = false;
            });
        })
        .catch(() => { });
    }

}

后台运行结果: 

页面效果:

直接回复邮件效果:


 

参考文章:
https://blog.csdn.net/ZZ2713634772/article/details/79576930

https://blog.csdn.net/java_zhaoyu/article/details/82496205

https://blog.csdn.net/java_zhaoyu/article/details/82496205 

猜你喜欢

转载自blog.csdn.net/mqingo/article/details/85049436