(十三)springboot发送e-mail

yux3344      2022-04-14     602

关键词:

一:添加mail依赖

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

  

二:添加邮件配置

打开application.properties

#邮箱配置
spring.mail.protocol=smtp
#这里换成自己的邮箱类型   例如qq邮箱就写smtp.qq.com
spring.mail.host=smtp.126.com
spring.mail.port=25
spring.mail.smtpAuth=true
spring.mail.smtpStarttlsEnable=true
#这里换成自己的邮箱类型   例如qq邮箱就写smtp.qq.com
spring.mail.smtpSslTrust=smtp.126.com 
#这里换成自己的邮箱账号
spring.mail.username=xxxxxx@126.com
#这里换成自己的邮箱密码或授权码   授权码获取可以百度
spring.mail.password=******

  

三:创建邮件实体类

package com.example.demo.model;

import java.util.Map;

public class Mail {

    /**
     * 发给多个人
     */
    private String[] to;

    /**
     * 抄送
     */
    private String[] cc;

    /**
     * 邮件标题
     */
    private String subject;

    /**
     * 邮件内容   简单文本 和附件邮件必填  其余的不需要
     */
    private String text;

    /**
     * 模板需要的数据   发送模板邮件必填
     */
    private Map<String,String> templateModel;

    /**
     * 选用哪个模板 发送模板邮件必填
     */
    private String templateName;

    public String[] getTo() {
        return to;
    }

    public void setTo(String[] to) {
        this.to = to;
    }

    public String getSubject() {
        return subject;
    }

    public void setSubject(String subject) {
        this.subject = subject;
    }

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }

    public Map<String, String> getTemplateModel() {
        return templateModel;
    }

    public void setTemplateModel(Map<String, String> templateModel) {
        this.templateModel = templateModel;
    }

    public String getTemplateName() {
        return templateName;
    }

    public void setTemplateName(String templateName) {
        this.templateName = templateName;
    }

    public String[] getCc() {
        return cc;
    }

    public void setCc(String[] cc) {
        this.cc = cc;
    }
}

  

四:创建邮件常量类

创建core→constant→MailConstant

package com.example.demo.core.constant;

public class MailConstant {

    /**
     * 注册的模板名称
     */
    public static final String RETGISTEREMPLATE = "register";

    /**
     * 模板存放的路径
     */
    public static final String TEMPLATEPATH = "src/test/java/resources/template/mail";
}

  

五:创建邮件业务类

MailService

package com.example.demo.service;

import com.example.demo.model.Mail;

import javax.servlet.http.HttpServletRequest;

public interface MailService {

    /**
     * 发送简单邮件
     * @param mail
     */
    void sendSimpleMail(Mail mail);

    /**
     * 发送带附件的邮件
     * @param mail
     * @param request
     */
    void sendAttachmentsMail(Mail mail, HttpServletRequest request);

    /**
     * 发送静态资源  一张照片
     * @param mail
     * @throws Exception
     */
    void sendInlineMail(Mail mail) throws Exception;

    /**
     * 发送模板邮件
     * @param mail
     */
    void sendTemplateMail(Mail mail);
}

  

MailServiceImpl

package com.example.demo.service.impl;

import com.example.demo.core.constant.MailConstant;
import com.example.demo.core.utils.UploadActionUtil;
import com.example.demo.model.Mail;
import com.example.demo.service.MailService;
import freemarker.template.Template;
import freemarker.template.TemplateExceptionHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
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 org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import javax.annotation.Resource;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.List;

@Service
public class MailServiceImpl implements MailService {

    private static final Logger logger = LoggerFactory.getLogger(MailServiceImpl.class);

    @Resource
    @Qualifier("javaMailSender")
    private JavaMailSender mailSender;

    @Value("${spring.mail.username}")
    private String from;

    @Resource
    private FreeMarkerConfigurer freeMarkerConfigurer;

    /**
     * 发送简单邮件
     */
    @Override
    public void sendSimpleMail(Mail mail){
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from);
        message.setTo(mail.getTo());
        message.setSubject(mail.getSubject());
        message.setText(mail.getText());
        message.setCc(mail.getCc());
        mailSender.send(message);
    }

    /**
     * 发送附件
     *
     * @throws Exception
     */
    @Override
    public void sendAttachmentsMail(Mail mail,HttpServletRequest request){
        try{
            MimeMessage mimeMessage = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
            helper.setFrom(from);
            helper.setTo(mail.getTo());
            helper.setSubject(mail.getSubject());
            helper.setText(mail.getText());
            List<String> list = UploadActionUtil.uploadFile(request);
            for (int i = 1,length = list.size();i<=length;i++) {
                String fileName = list.get(i-1);
                String fileTyps = fileName.substring(fileName.lastIndexOf("."));
                FileSystemResource file = new FileSystemResource(new File(fileName));
                helper.addAttachment("附件-"+i+fileTyps, file);
            }
            mailSender.send(mimeMessage);
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    /**
     * 发送静态资源  一张照片
     * @param mail
     * @throws Exception
     */
    @Override
    public void sendInlineMail(Mail mail){
        try{
            MimeMessage mimeMessage = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
            helper.setFrom(from);
            helper.setTo(mail.getTo());
            helper.setSubject(mail.getSubject());
            helper.setText("<html><body><img src=\"cid:chuchen\" ></body></html>", true);

            FileSystemResource file = new FileSystemResource(new File("C:\\Users\\Administrator\\Desktop\\设计图\\已完成\\微信图片_20180323135358.png"));
            // addInline函数中资源名称chuchen需要与正文中cid:chuchen对应起来
            helper.addInline("chuchen", file);
            mailSender.send(mimeMessage);
        }catch (Exception e){
            logger.error("发送邮件发生异常");
        }

    }

    /**
     * 发送模板邮件
     * @param mail
     */
    @Override
    public void sendTemplateMail(Mail mail){
        MimeMessage message = null;
        try {
            message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(mail.getTo());
            helper.setSubject(mail.getSubject());
            //读取 html 模板
            freemarker.template.Configuration cfg = getConfiguration();
            Template template = cfg.getTemplate(mail.getTemplateName()+".ftl");
            String html = FreeMarkerTemplateUtils.processTemplateIntoString(template, mail.getTemplateModel());
            helper.setText(html, true);
        } catch (Exception e) {
            e.printStackTrace();
        }
        mailSender.send(message);
    }

    private static freemarker.template.Configuration getConfiguration() throws IOException {
        freemarker.template.Configuration cfg = new freemarker.template.Configuration(freemarker.template.Configuration.VERSION_2_3_23);
        cfg.setDirectoryForTemplateLoading(new File(MailConstant.TEMPLATEPATH));
        cfg.setDefaultEncoding("UTF-8");
        cfg.setTemplateExceptionHandler(TemplateExceptionHandler.IGNORE_HANDLER);
        return cfg;
    }
}

  

六:创建ftl模板

这里我们创建一个注册的模板,其他模板大家可自行创建

在src/test/java/resources/template/mail目录下创建register.ftl

<html>
<head>
    <meta http-equiv="content-type" content="text/html;charset=utf8">
</head>
<body>
<div><span>尊敬的</span>${to}:</div>
<div>
    <span>欢迎您加入YUI,您的验证码为:
        <span style="color: red;">${identifyingCode}</span>
    </span>
</div>
<span style="margin-top: 100px">YUI科技</span>
</body>
</html>

  

七:创建MailController

package com.example.demo.controller;

import com.example.demo.core.constant.MailConstant;
import com.example.demo.core.ret.RetResponse;
import com.example.demo.core.ret.RetResult;
import com.example.demo.core.utils.ApplicationUtils;
import com.example.demo.model.Mail;
import com.example.demo.service.MailService;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/mail")
public class MailController {

    @Resource
    private MailService mailService;

    /**
     * 发送注册验证码
     * @param mail
     * @return 验证码
     * @throws Exception
     */
    @PostMapping("/sendTemplateMail")
    public RetResult<String> sendTemplateMail(Mail mail) throws Exception {
        String identifyingCode = ApplicationUtils.getNumStringRandom(6);
        mail.setSubject("欢迎注册初晨");
        mail.setTemplateName(MailConstant.RETGISTEREMPLATE);
        Map<String,String> map = new HashMap<>();
        map.put("identifyingCode",identifyingCode);
        map.put("to",mail.getTo()[0]);
        mail.setTemplateModel(map);
        mailService.sendTemplateMail(mail);

        return RetResponse.makeOKRsp(identifyingCode);
    }

    @PostMapping("/sendAttachmentsMail")
    public RetResult<String> sendAttachmentsMail(Mail mail,HttpServletRequest request) throws Exception {
        mail.setSubject("测试附件");
        mailService.sendAttachmentsMail(mail, request);
        return RetResponse.makeOKRsp();
    }
}

  

八:测试

输入localhost:8080/mail/sendTemplateMail

必填参数 to

 

如何发送html格式的e-mail

如何发送HTML格式的E-mail,我常收到一些别人发来的一些E-mail,打开后都是以网页的方式显示的,我想发送一个这样的E-mail给我的朋友,怎么试也不行,我试过用OutlookExpress来发,但发过去每一个图片都一个副件(别人发给我的就没有,不... 查看详情

使用smtplib发送e-mail

#!/usr/bin/envpythonimportsmtplibimportstringHOST="smtp.sina.cn"SUBJECT="Testmailfrompython"TO="[email protected]"FROM="[email protected]"text="pythonrulesthemall!!!"BODY=string.join((  查看详情

java发送邮件

目录01-准备jar包02-发送简单的E-mail03-发送HTML内容的E-mail04-发送带有附件的E-mail05-用户认证部分06-简单封装01-准备jar包使用Java应用程序发送E-mail十分简单,前提先是下载以下两个jar包javax.mailjavax.activation下载地址:https://pan.baidu.co... 查看详情

springboot入门二十三,整合redis

  项目基本配置参考文章SpringBoot入门一,使用myEclipse新建一个SpringBoot项目,使用MyEclipse新建一个SpringBoot项目即可,此示例springboot升级为2.2.1版本。1.pom.xml添加Redis支持<!--5.引入redis依赖--><dependency><groupId>org.springframe... 查看详情

企业级springboot教程(十三)springboot集成springcache

本文介绍如何在springboot中使用默认的springcache,声明式缓存Spring定义CacheManager和Cache接口用来统一不同的缓存技术。例如JCache、EhCache、Hazelcast、Guava、Redis等。在使用Spring集成Cache的时候,我们需要注册实现的CacheManager的Bean。Sprin... 查看详情

企业级springboot教程(十三)springboot集成springcache

本文介绍如何在springboot中使用默认的springcache,声明式缓存Spring定义CacheManager和Cache接口用来统一不同的缓存技术。例如JCache、EhCache、Hazelcast、Guava、Redis等。在使用Spring集成Cache的时候,我们需要注册实现的CacheManager的Bean。Sprin... 查看详情

springboot1.5.4整合druid(十三)

上一篇:springboot1.5.4整合mybatis(十二) 1      集成druid连接池springboot集成druid项目mybatis-spring-boot源码地址:https://git.oschina.net/wyait/springboot1.5.4.git 1.1 druid简介D 查看详情

springboot(十三):springboot整合rabbitmq

1.前言RabbitMQ是一个消息队列,说到消息队列,大家可能多多少少有听过,它主要的功能是用来实现应用服务的异步与解耦,同时也能起到削峰填谷、消息分发的作用。消息队列在比较主要的一个作用是用来做应用服务的解耦,... 查看详情

springboot系列(三十三):springboot如何手动连接库并获取指定表结构|超级详细,建议收藏

查看详情

java精选面试题之springboot三十三问

SpringBootSpringBoot是微服务中最好的Java框架.我们建议你能够成为一名SpringBoot的专家.问题一:SpringBoot、SpringMVC和Spring有什么区别?SpringFrameSpringFramework最重要的特征是依赖注入。所有SpringModules不是依赖注入就是IOC控制反转。当我们... 查看详情

springboot学习总结(十三)jpa事务

(一)java异常  Throwable这个Java类被用来表示任何可以作为异常被抛出来的类。Throwable对象可分为两种类型(指从Throwable继承而得到的类型):Error用来表示编译时和系统错误(除特殊情况外,一般不用关心);Exception是可以... 查看详情

springboot入门十三,添加rabbitmq

一.概念说明Broker:简单来说就是消息队列服务器实体。Exchange:消息交换机,它指定消息按什么规则,路由到哪个队列。Queue:消息队列载体,每个消息都会被投入到一个或多个队列。Binding:绑定,它的作用就是把exchange和queue... 查看详情

springboot实战(十三)之缓存

什么是缓存?引用下百度百科的解释:缓存就是数据交换的缓冲区(又称作Cache),当某一硬件要读取数据时,会首先从缓存中查找需要的数据,找到了则直接执行,找不到的话则从内存中查找。由于缓存的运行速度比内存快得多,故... 查看详情

(十三)如何实现事务(代码片段)

前面介绍了SpringBoot中的整合Mybatis并实现增删改查。不清楚的朋友可以看看之前的文章:https://www.cnblogs.com/zhangweizhong/category/1657780.html。SpringBoot整合完Mybatis,有个特别重要的功能之前忘记讲了:那就是SpringBoot如何实现事物控制... 查看详情

springboot(十三)cors方式实现跨域

什么是跨域?浏览器从一个域名的网页去请求另一个域名的资源时,域名、端口、协议任一不同,都是跨域。跨域资源访问是经常会遇到的场景,当一个资源从与该资源本身所在的服务器不同的域或端口请求一个资源时,资源便... 查看详情

rocketmq(十三)普通消息(代码片段)

1、消息发送分类Producer对于消息的发送方式也有多种选择,不同的方式会产生不同的系统效果。1.1、同步发送消息同步发送消息是指,Producer发出⼀条消息后,会在收到MQ返回的ACK之后才发下⼀条消息。该方式的消息... 查看详情

(十三)atp应用测试平台——springboot集成kafka案例实战(代码片段)

...:①削峰填谷②异步解耦。本节我们主要介绍一下如何在springboot项目中集成kafka消息中间键,实现简单的数据分发以及消费的案例。正文kafka集群搭建快速搭建一个kafka集群,我们这里以docker 查看详情

基于springboot搭建java项目(二十三)——springboot使用过滤器拦截器和监听器(代码片段)

SpringBoot使用过滤器、拦截器和监听器一、SpringBoot使用过滤器Springboot过滤器的使用(两种方式)使用springboot提供的FilterRegistrationBean注册Filter使用原生servlet注解定义Filter两种方式的本质都是一样的,都是去FilterRegistrat... 查看详情