Java SpringBoot实现邮件发送

依赖



    org.springframework.boot
    spring-boot-starter-mail




    org.thymeleaf
    thymeleaf

邮件模板




    
    邮件
    


[[${email.date}]] 农安试验场原始数据上传情况
TEVG System 空间总数据量 Summe:[[${email.amount}]] [[${email.date}]]
VDS Nr. 日期Date-时间Time 文件夹大小 Size/M 迁移状态 Upload Status
[[${data.code}]] [[${data.date}]] [[${data.folderSize}]] [[${data.migrations}]]

邮件接口

public interface SmtpMailService {
    /**
     * 发送文本邮件
     *
     * @param to      收件人地址
     * @param subject 邮件主题
     * @param content 邮件内容
     * @param cc      抄送地址
     */
    void sendSimpleMail(List to, String subject, String content, List cc);

    /**
     * 发送HTML邮件
     *
     * @param to      收件人地址
     * @param subject 邮件主题
     * @param content 邮件内容
     * @param cc      抄送地址
     * @throws MessagingException 邮件发送异常
     */
    void sendHtmlMail(List to, String subject, String content, List cc);

    /**
     * 发送带附件的邮件
     *
     * @param to       收件人地址
     * @param subject  邮件主题
     * @param content  邮件内容
     * @param filePath 附件地址
     * @param cc       抄送地址
     * @throws MessagingException 邮件发送异常
     */
    void sendAttachmentsMail(List to, String subject, String content, List filePath, List cc);

    /**
     * 发送正文中有静态资源的邮件
     *
     * @param to      收件人地址
     * @param subject 邮件主题
     * @param content 邮件内容
     * @param rscPath 静态资源地址
     * @param rscId   静态资源id
     * @param cc      抄送地址
     * @throws MessagingException 邮件发送异常
     */
    void sendResourceMail(List to, String subject, String content, String rscPath, String rscId, List cc);

邮件接口实现

@Service
public class SmtpMailServiceImpl implements SmtpMailService {

    @Autowired
    private IVwEmailServerService vwEmailServerService;

    private String from;

    /**
     * 发送文本邮件
     *
     * @param to      收件人地址
     * @param subject 邮件主题
     * @param content 邮件内容
     * @param cc      抄送地址
     */
    @Override
    public void sendSimpleMail(List to, String subject, String content, List cc) {
        JavaMailSenderImpl jms = getMailSender();
        MimeMessage mimeMessage = jms.createMimeMessage();
        MimeMessageHelper helper;

        try {
            helper = new MimeMessageHelper(mimeMessage, true);
            for (String addressee : to) {
                helper.setFrom(from);
                helper.setTo(addressee);
                helper.setSubject(subject);
                helper.setText(content);
                if (!cc.isEmpty()) {
                    helper.setCc(cc.toString());
                }
                jms.send(mimeMessage);
            }
        } catch (MessagingException e) {
            System.out.println(e);
        }


    }

    /**
     * 发送HTML邮件
     *
     * @param to      收件人地址
     * @param subject 邮件主题
     * @param content 邮件内容
     * @param cc      抄送地址
     */
    @Override
    public void sendHtmlMail(List to, String subject, String content, List cc) {
        JavaMailSenderImpl jms = getMailSender();
        MimeMessage mimeMessage = jms.createMimeMessage();
        MimeMessageHelper helper;

        try {
            helper = new MimeMessageHelper(mimeMessage, true);
            for (String addressee : to) {
                helper.setFrom(from);
                helper.setTo(addressee);
                helper.setSubject(subject);
                helper.setText(content, true);
                if (!cc.isEmpty()) {
                    String[] sup = cc.toArray(new String[cc.size()]);
                    helper.setCc(sup);
                }
                jms.send(mimeMessage);
            }
        } catch (MessagingException e) {
            System.out.println(e);
        }


    }

    /**
     * 发送带附件的邮件
     *
     * @param to       收件人地址
     * @param subject  邮件主题
     * @param content  邮件内容
     * @param filePath 附件地址
     * @param cc       抄送地址
     */
    @Override
    public void sendAttachmentsMail(List to, String subject, String content, List filePath, List cc) {
        JavaMailSenderImpl jms = getMailSender();
        MimeMessage mimeMessage = jms.createMimeMessage();
        MimeMessageHelper helper;

        try {
            helper = new MimeMessageHelper(mimeMessage, true);
            for (String address : to) {
                helper.setFrom(from);
                helper.setTo(address);
                helper.setSubject(subject);
                helper.setText(content, true);
                if (!cc.isEmpty()) {
                    helper.setCc(cc.toString());
                }
                for (String attachment : filePath) {
                    FileSystemResource file = new FileSystemResource(new File(attachment));
                    String fileName = attachment.substring(filePath.lastIndexOf(File.separator));
                    helper.addAttachment(fileName, file);
                }

                jms.send(mimeMessage);
            }
        } catch (MessagingException e) {
            System.out.println(e);
        }


    }

    /**
     * 发送正文中有静态资源的邮件
     *
     * @param to      收件人地址
     * @param subject 邮件主题
     * @param content 邮件内容
     * @param rscPath 静态资源地址
     * @param rscId   静态资源id
     * @param cc      抄送地址
     */
    @Override
    public void sendResourceMail(List to, String subject, String content, String rscPath, String rscId, List cc) {
        JavaMailSenderImpl jms = getMailSender();
        MimeMessage mimeMessage = jms.createMimeMessage();
        MimeMessageHelper helper;
        try {
            helper = new MimeMessageHelper(mimeMessage, true);
            for (String address : to) {

                helper.setFrom(from);
                helper.setTo(address);
                helper.setSubject(subject);
                helper.setText(content, true);
                if (!cc.isEmpty()) {
                    helper.setCc(cc.toString());
                }
                FileSystemResource res = new FileSystemResource(new File(rscPath));
                helper.addInline(rscId, res);

                jms.send(mimeMessage);
            }
        } catch (MessagingException e) {
            System.out.println(e);
        }


    }

    public JavaMailSenderImpl getMailSender() {
        List list = vwEmailServerService.selectVwEmailServerList(new VwEmailServer());
        VwEmailServer emailServer = list.get(0);

        JavaMailSenderImpl jms = new JavaMailSenderImpl();
        //邮件服务器主机
        jms.setHost(emailServer.getHost());
        //邮件服务器端口
        jms.setPort(emailServer.getPort());
        //邮箱账号
        jms.setUsername(emailServer.getUsername());
        //邮箱密码
        jms.setPassword(emailServer.getPassword());
        //邮件协议 这里用的 smtp
        jms.setProtocol(emailServer.getProtocol());
        //编码
        jms.setDefaultEncoding(emailServer.getEncoding());
        Properties p = new Properties();
        p.setProperty("mail.smtp.auth", "true");
        p.setProperty("mail.smtp.starttls.enable", "true");
        p.setProperty("mail.smtp.starttls.required", "true");
        p.setProperty("mail.smtp.ssl.enable", "false");
        //这里填发送邮箱对应的SMTP地址 ,忽略证书,信任域名
        p.setProperty("mail.smtp.ssl.trust", emailServer.getHost());
        p.setProperty("mail.display.sendmail", "邮件发送");
        jms.setJavaMailProperties(p);

        from = emailServer.getUsername();

        return jms;
    }

}

邮件发送

public class SendEmail {

    @Autowired
    private TemplateEngine templateEngine;

    @Autowired
    private IVwEmailService vwEmailService;

    @Autowired
    private ISysFileInfoService sysFileInfoService;

    @Autowired
    private SmtpMailService smtpMailService;

    /**
     * 发送文本邮件
     * 含抄送人
     *
     * @param subject 邮件主题
     * @param content 邮件内容
     * @throws Exception 邮件发送异常
     */
    public void sendTextEmailByCC(String subject, String content) throws Exception {
        //收件人
        List to = vwEmailService.selectEmailByReceivingType(ReceivingType.RECIPIENT.getCode());

        //抄送人
        List cc = vwEmailService.selectEmailByReceivingType(ReceivingType.CC_TO.getCode());

        smtpMailService.sendSimpleMail(to, subject, content, cc);

    }

    /**
     * 发送HTML模板邮件
     * 含抄送人
     *
     * @throws Exception 邮件发送异常
     */
    public void sendHtmlEmailByCC() throws Exception {
        //收件人
        List to = vwEmailService.selectEmailByReceivingType(ReceivingType.RECIPIENT.getCode());

        //抄送人
        List cc = vwEmailService.selectEmailByReceivingType(ReceivingType.CC_TO.getCode());

        //获取邮件vo
        FromEmailVo vo = getfromEmailVo();
        // 通过 Context 构造模版中变量需要的值
        Context context = new Context();
        context.setVariable("email", vo);
        //模版进行渲染
        String emailTemplate = emailTemplate(context);

        smtpMailService.sendHtmlMail(to, DateUtils.datePath() + " 农安试验场原始数据上传情况", emailTemplate, cc);

    }

    /**
     * 发送附件邮件
     * 含抄送人
     *
     * @param subject    邮件主题
     * @param content    邮件内容
     * @param attachment 附件
     * @throws Exception 邮件发送异常
     */
    public void sendAttachmentByCC(String subject, String content, List attachment) throws Exception {
        //收件人
        List to = vwEmailService.selectEmailByReceivingType(ReceivingType.RECIPIENT.getCode());

        //抄送人
        List cc = vwEmailService.selectEmailByReceivingType(ReceivingType.CC_TO.getCode());

        smtpMailService.sendAttachmentsMail(to, subject, content, attachment, cc);
    }

    /**
     * 获取封装的邮件vo
     *
     * @return
     */
    public FromEmailVo getfromEmailVo() throws Exception {
        String uploadPath = RuoYiConfig.getUploadPath();
        List sysFileInfos = sysFileInfoService.selectFileName();
        List gpsList = new ArrayList<>();
        Long amount = 0L;
        for (SysFileInfo fi : sysFileInfos) {
            File file = new File(uploadPath + File.separator + fi.getExperimentName() + File.separator + "log" + File.separator + fi.getFileTime());
            //判断当天是否上传过数据
            if (file.exists() && file.isDirectory()) {
                //获取文件夹大小
                long totalSizeOfFilesInDir = getTotalSizeOfFilesInDir(file);
                Double fileSizeMb = YmlUtil.getFileSizeMb(totalSizeOfFilesInDir);
                amount += totalSizeOfFilesInDir;

                EmailDataVo vo = new EmailDataVo();
                vo.setCode(fi.getExperimentName());
                vo.setCodeUrl(fi.getExperimentName() + "/" + "log");
                vo.setGpsUrl(fi.getExperimentName() + "/" + "log" + "/" + fi.getFileTime());
                vo.setDate(fi.getFileTime());
                vo.setFolderSize(fileSizeMb);
                gpsList.add(vo);
            }
        }

        FromEmailVo vo = new FromEmailVo();
        //字节转换
        String fileSize = YmlUtil.getFileSizeString(amount);
        vo.setAmount(fileSize);
        vo.setDate(DateUtils.datePath());

        List list = new ArrayList<>();

        for (EmailDataVo gp : gpsList) {
            EmailDataVo ed = new EmailDataVo();
            ed.setCode(gp.getCode());
            //外部链接
            ed.setCodeUrl("https://www.baidu.com");
            ed.setDate(gp.getDate());
            //外部链接
            ed.setDateUrl("https://www.baidu.com");
            ed.setTrace(gp.getTrace());
            ed.setFolderSize(gp.getFolderSize());
            ed.setMigrations("迁移完成 Upload Finished");
            list.add(ed);
        }

        vo.setList(list);

        return vo;
    }

    /**
     * 返回文件或文件夹大小
     *
     * @param file
     * @return
     */
    private long getTotalSizeOfFilesInDir(File file) {
        if (file.isFile()) {
            return file.length();
        }
        final File[] children = file.listFiles();
        long total = 0;
        if (children != null) {
            for (final File child : children) {
                total += getTotalSizeOfFilesInDir(child);
            }

        }
        return total;
    }

    /**
     * html模板转字符串
     *
     * @param context
     * @return
     */
    public String emailTemplate(Context context) {
        // 使用TemplateEngine 对模版进行渲染(Thymeleaf 模版默认位置是 resources/templates)
        String template = "template/email-template.html";
        return templateEngine.process(template, context);
    }

}

结果Java SpringBoot实现邮件发送_第1张图片

你可能感兴趣的:(java,spring,boot)