SpringCloud框架实现邮箱功能----实测成功

在现有公司项目解决之后,将项目中的一些心得记录下来和初入IT行业的童鞋们一起学习,这是第一次写博客,希望我的心得对你们有所帮助,共同进步!
在这里插入图片描述在这里插入图片描述以上是一个普通邮件的发送结果的演示,接下来直接进入我们的正文。
首先,需要在pom文件中添加对邮件的jar依赖

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

其次就是对yml文件对邮箱服务器进行配置

spring:
  mail:
    host: 公司邮件服务
    username: 发送方的邮箱
    password: 邮箱的授权密码
    port: 端口号

注意:这里的服务器可以找项目负责人寻求,如果需要其他配置,那我就其他前辈的代码copy过来给小伙伴们参考。

spring:
	mail:
	    host: 你的邮件服务
	    username: 发送方的邮箱
	    password: 邮箱的授权密码
	    port: 465 # 这个端口根据实际情况配置,一般都是465
	    protocol: smtp # 这里应该是不用改的,我没试过其他的配置
	    test-connection: false
	    default-encoding: UTF-8
	    properties:
	      mail:
	        debug: true
	        smtp:
	          auth: true
	          connectiontimeout: 10000   #设置连接超时时间
	          timeout: 10000
	          writetimeout: 10000
	          socketFactory:
	            class: javax.net.ssl.SSLSocketFactory
	            port: 465
	          starttls:
	            enable: true
	            required: true

接下来,老板~上代码(童鞋们都饥渴难耐了)
第一步:定义一个Service接口和一个MailSendDTO文件

package com.galaxy.platform.eapro.dto;

import lombok.Data;

@Data
public class MailSendDTO {
    private String to;
    private String subject;
    private String content;
}


import java.util.Map;

/**
 * @author liuzy
 * @date 2020/5/20
 */

public interface MailService {
    /**
     * 发送普通邮件
     *
     * */
    void sendSimpleMailMessage(MailSendDTO mailSendDTO);

    /**
     * 发送 HTML 邮件
     *
     * @param to      收件人
     * @param subject 主题
     * @param content 内容
     */
    void sendMimeMessage( String to, String subject, String content);

    /**
     * 发送带附件的邮件
     *
     * @param to       收件人
     * @param subject  主题
     * @param content  内容
     * @param filePath 附件路径
     */
    void sendMimeMessage( String to, String subject, String content, String filePath);

    /**
     * 发送带静态文件的邮件
     *
     * @param to       收件人
     * @param subject  主题
     * @param content  内容
     * @param rscIdMap 需要替换的静态文件
     */
    void sendMimeMessage( String to, String subject, String content, Map<String, String> rscIdMap);
}

第二步:Service接口实现方法

package com.galaxy.platform.eapro.service.impl;
import com.galaxy.platform.eapro.dto.MailSendDTO;
import com.galaxy.platform.eapro.service.MailService;
import org.apache.log4j.Logger;
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;
import java.util.Map;
@Service
public class MailServiceImpl implements MailService {
    private Logger logger = Logger.getLogger(this.getClass());

    @Autowired
    private JavaMailSender mailSender;

    @Value("${spring.mail.username}")
    private String sender;
    @Override
    public void sendSimpleMailMessage(MailSendDTO mailSendDTO) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(sender);
        message.setTo(mailSendDTO.getTo());
        message.setSubject(mailSendDTO.getSubject());
        message.setText(mailSendDTO.getContent());
        try{
            mailSender.send(message);
            logger.info("send success......");
        }catch (Exception ex){
            logger.error("发送简单邮件时发生异常!",ex);
        }
    }


    @Override
    public void sendMimeMessage(String to, String subject, String content) {
        MimeMessage message = mailSender.createMimeMessage();
        try {
            //true表示需要创建一个multipart message
            MimeMessageHelper helper = new MimeMessageHelper(message,true);
            helper.setFrom(sender);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content,true);
            mailSender.send(message);
            logger.info("send success......");
        } catch (MessagingException ex) {
            logger.error("发送MimeMessage时发生异常!",ex);
        }
    }

    @Override
    public void sendMimeMessage(String to, String subject, String content, String filePath) {
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = null;
        try {
            helper = new MimeMessageHelper(message,true);
            helper.setFrom(sender);
            helper.setTo(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);
            logger.info("send success......");
        } catch (MessagingException ex) {
            logger.error("发送带附件的MimeMessage时发生异常!",ex);
        }
    }

    @Override
    public void sendMimeMessage(String to, String subject, String content,
                               Map<String, String> rscIdMap) {
        MimeMessage message = mailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message,true);
            helper.setFrom(sender);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content,true);
            for (Map.Entry<String,String> entry:rscIdMap.entrySet()){
                FileSystemResource file = new FileSystemResource(new File(entry.getValue()));
                helper.addInline(entry.getKey(),file);
            }
            mailSender.send(message);
            logger.info("send success......");
        } catch (MessagingException ex) {
            logger.error("发送带静态文件的MimeMessage时发生异常!",ex);
        }
    }
}

第三步:创建一个ResponseDTO文件,用于返回数据状态

package com.galaxy.platform.eapro.dto;
public class ResponseDTO {
    private String code;
    private String msg;
    private Object data;

    public ResponseDTO() {
    }
    public ResponseDTO(String code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    public ResponseDTO(String code, Object data, String msg) {
        this.code = code;
        this.msg = msg;
        this.data = data;
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public Object getData() {
        return data;
    }

    public void setData(Object data) {
        this.data = data;
    }
}

第四步:定义controller接口,供前端人员调用

package com.galaxy.platform.eapro.controller;

import com.galaxy.framework.core.constant.CommonConstant;
import com.galaxy.platform.eapro.dto.MailSendDTO;
import com.galaxy.platform.eapro.dto.ResponseDTO;
import com.galaxy.platform.eapro.service.MailService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author liuzy
 * @date 2020/5/20
 */

@RestController
@RequestMapping(value = CommonConstant.ROOT_CONTEXT+"/mail")
@Api(value = "邮件系统")
public class MailController {
    private Logger logger = Logger.getLogger(this.getClass());
    String regx = ".+@.+\\.[a-z]+";

    @Autowired
    MailService mailService;

    @PostMapping(value = "/send")
    @ApiOperation(value = "发送普通邮件")
    public ResponseDTO sendRegularMail(@RequestBody MailSendDTO mailSendDTO){
        Pattern PATTERN = Pattern.compile(regx);
        Matcher matcher = PATTERN.matcher(mailSendDTO.getTo());
        if (!matcher.matches()){
            logger.error("邮箱格式不合法");
        }
        mailService.sendSimpleMailMessage(mailSendDTO);
        logger.info("MailController send success......");

        return new ResponseDTO("200",null,"success");
    }

    @PostMapping(value = "/sendHTMLMail")
    @ApiOperation(value = "发送HTML邮件")
    public ResponseDTO sendHTMLMail( String to, String subject, String content){
        Pattern PATTERN = Pattern.compile(regx);
        Matcher matcher = PATTERN.matcher(to);
        if (!matcher.matches()){
            logger.error("邮箱格式不合法");
        }
        mailService.sendMimeMessage(to,subject,content);
        logger.info("MailController send success......");

        return new ResponseDTO("200",null,"success");
    }

    @PostMapping(value = "/sendAttachmentEmail")
    @ApiOperation(value = "发送附件邮件")
    public ResponseDTO sendAttachmentEmail(String to, String subject, String content, String filePath){
        Pattern PATTERN = Pattern.compile(regx);
        Matcher matcher = PATTERN.matcher(to);
        if (!matcher.matches()){
            logger.error("邮箱格式不合法");
        }
        mailService.sendMimeMessage(to,subject,content,filePath);
        logger.info("MailController send success......");

        return new ResponseDTO("200",null,"success");
    }

    @PostMapping(value = "/sendStaticEmail")
    @ApiOperation(value = "发送静态邮件")
    public ResponseDTO sendStaticEmail(String from, String to, String subject, String content, Map<String, String> rscIdMap){
        Pattern PATTERN = Pattern.compile(regx);
        Matcher matcher = PATTERN.matcher(to);
        if (!matcher.matches()){
            logger.error("邮箱格式不合法");
        }
        mailService.sendMimeMessage(to,subject,content,rscIdMap);
        logger.info("MailController send success......");

        return new ResponseDTO("200",null,"success");
    }
}

第五步:config配置

package com.galaxy.platform.eapro.configuration;

import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

/**
 * @author liuzy
 * @date 2020/5/20
 */
@Configuration
@EnableSwagger2
public class SwaggerConfiguration {
    public Docket createRestApi(){
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                //指定当前包路径
                .apis(RequestHandlerSelectors.basePackage("com.galaxy"))
                .paths(PathSelectors.any())
                .build();
    }

    /**
     * 构建api文档的详细信息函数
     * */
    private ApiInfo apiInfo(){
        return new ApiInfoBuilder()
                /**
                 * 页面标题
                 * */
                .title("Spring Boot Swagger2 RESTful API")
                /**
                 * 创建人
                 * */
                .contact(new Contact("liuzy","1926153649@qq.com",""))
                /**
                 * 版本号
                 * */
                .version("1.0")
                /**
                 * 描述
                 * */
                .description("API描述")
                .build();
    }
}

最后就是运行Application运行文件

import com.galaxy.framework.oauth2.feign.EnableOAuth2ClientFeign;
import com.galaxy.framework.security.access.EnableSecurityAccess;
import org.springframework.boot.SpringApplication;

import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cloud.client.SpringCloudApplication;
import org.springframework.cloud.netflix.feign.EnableFeignClients;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableOAuth2Client;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@SpringCloudApplication
@EnableOAuth2Client
@EnableResourceServer
@EnableOAuth2ClientFeign
@EnableSecurityAccess
@ComponentScan("com.galaxy")
@EnableFeignClients("com.galaxy")
@EnableCaching
@EnableSwagger2
public class EAProApplication {
    public static void main(String[] args) {
        SpringApplication.run(EAProApplication.class, args);
    }
}

以上的部分注解是公司自定义注解
注意:一定要记得配置邮件服务器,刚开始我一直纠结为啥我的一直报以下错误
在这里插入图片描述最后看了好多遍才发现,在Nacos(我的yml定义的位置)中没有提交,浪费我一下午时间,还好最后解决了。童鞋们,以上就是我现有的项目分享的心得,这个邮箱功能的全代码都在这,希望对你有所帮助,请留下你的小心心给个鼓励!!!(这里只提供全代码,复制即可,原创博客复制时请注明文章来源,谢谢)

展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 数字20 设计师: CSDN官方博客
应支付0元
点击重新获取
扫码支付

支付成功即可阅读