MailService.java 6.75 KB
package com.lhcredit.framework.web.service;

import com.lhcredit.common.utils.text.Convert;
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.Service;

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

/**
 * 通用邮件发送service
 * Created by LGJ
 */

@Service
public class MailService {
    private static final Logger log = LoggerFactory.getLogger(MailService.class);
    @Value("${spring.mail.username}")
    private String from;

    @Autowired
    private JavaMailSender mailSender;


    /**
     * 发送文本邮件
     *
     * @param to      接收人(多个收件人以英文分号;分隔)
     * @param subject 主题
     * @param content 邮件内容
     */
    public void sendSimpleMail(String to, String subject, String content) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setTo(Convert.toStrArray(";", to));
        message.setSubject(subject);
        message.setText(content);
        message.setFrom(from);
        mailSender.send(message);
    }

    /**
     * 发送HTML邮件
     *
     * @param to      接收人(多个收件人以英文分号;分隔)
     * @param subject
     * @param content
     */
    public void sendHtmlMail(String to, String subject, String content) throws MessagingException {
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
        helper.setFrom(from);
        helper.setTo(Convert.toStrArray(";", to));
        helper.setSubject(subject);
        helper.setText(content, true);
        mailSender.send(mimeMessage);
    }

    /**
     * 发送带附件的邮件
     *
     * @param to      接收人(多个收件人以英文分号;分隔)
     * @param subject
     * @param content
     */
    public void sendAttachmentMail(String to, String subject, String content, String filepath) throws MessagingException {
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setFrom(from);
        helper.setTo(Convert.toStrArray(";", to));
        helper.setSubject(subject);
        helper.setText(content, true);
        //文件流:获取本地文件
        FileSystemResource file = new FileSystemResource(new File(filepath));
        String filename = file.getFilename();
        //可以发送多个
        helper.addAttachment(filename, file);
        //进行发送
        mailSender.send(message);
    }

    /**
     * 发送图片邮件
     *
     * @param to      接收人(多个收件人以英文分号;分隔)
     * @param subject
     * @param content
     * @param rscPath
     * @param rscId
     * @throws Exception
     */
    public void sendImageMail(String to, String subject, String content, String rscPath, String rscId) throws MessagingException {
        log.info("发送静态邮件开始: {},{},{},{},{}", to, subject, content, rscPath, rscId);
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = null;
        helper = new MimeMessageHelper(message, true);
        helper.setFrom(from);
        helper.setTo(Convert.toStrArray(";", to));
        helper.setSubject(subject);
        helper.setText(content, true);
        FileSystemResource file = new FileSystemResource(new File(rscPath));
        helper.addInline(rscId, file);
        mailSender.send(message);
        log.info("发送静态图片邮件成功!");
    }
}
//    示例
//    public class TestSpringbootEmail {
//
//        @Resource
//        MailService mailService;
//
//        @Resource
//        TemplateEngine templateEngine;
//
//        /**
//         *  简单文本邮件发送
//         */
//        @Test
//        public void sendSimpleMailTest(){
//            mailService.sendSimpleMail("liguohui@163.com","简单文本邮件","这是我的第一封邮件,哈哈...");
//        }
//
//        /**
//         *  HTML邮件发送
//         *
//         * @throws Exception
//         */
//        @Test
//        public void sendHtmlMailTest() throws Exception{
//
//            String content = "<html>\n"+
//                    "<body>\n" +
//                    "<h1 style=\"color: red\"> hello world , 这是一封HTML邮件</h1>"+
//                    "</body>\n"+
//                    "</html>";
//
//
//            mailService.sendHtmlMail("liguohui@163.com","Html邮件发送",content);
//        }
//
//        /**
//         *  发送副本邮件
//         *
//         * @throws Exception
//         */
//        @Test
//        public void sendAttachmentMailTest() throws Exception{
//            String filepath = "/Users/fish/Desktop/linux 常用命令.pdf";
//
//            mailService.sendAttachmentMail("liguohui@163.com","发送副本","这是一篇带附件的邮件",filepath);
//
//        }
//
//        /**
//         *  发送图片邮件
//         *
//         * @throws Exception
//         */
//        @Test
//        public void sendImageMailTest() throws Exception{
//            //发送多个图片的话可以定义多个 rscId,定义多个img标签
//
//            String filePath = "/Users/fish/Desktop/test.png";
//            String rscId = "ligh001";
//            String content = "<html><body> 这是有图片的邮件: <img src=\'cid:"+rscId+"\'> </img></body></html>";
//
//            mailService.sendImageMail("liguohui@huluwa.cc","这是一个带图片的邮件",content,filePath,rscId);
//        }
//
//        /**
//         *  发送邮件模板
//         *
//         * @throws Exception
//         */
//        @Test
//        public void sendTemplateEmailTest() throws Exception {
//            Context context = new Context();
//            context.setVariable("id","006");
//            String emailContent = templateEngine.process("templates",context);
//            mailService.sendHtmlMail("lighAsqh@163.com","这是一个模板文件",emailContent);
//        }
//    }
//        html模板
//        <!DOCTYPE html>
//        <html lang="en" xmlns:th="http://www.thymeleaf.org">
//        <head>
//           <meta charset="UTF-8">
//           <title>邮件模板</title>
//        </head>
//        <body>
//          您好,感谢您的注册,这是一封验证邮件,请点击下面的连接完成注册,感谢您的支持
//          <a href="#" th:href="@{www.ityouknow.com/register/{id}(id=${id})}">激活账号</a>
//        </body>
//        </html>