快速搭建一个邮箱微服务

1. 

获取授权码 

 实战:

①引入依赖

②添加配置

③核心代码

引入依赖:

<!--发送邮件的依赖 用的是 springframework 框架的,但是依赖还是要引入 ,因为 发送邮件的JavaMailSenderImpl  就在这里 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>

添加配置:

# 邮件发送
# SMTP服务器地址
spring.mail.host=smtp.126.com
# 登录账号
spring.mail.username=Guoyiguang2
#spring.mail.username=Guoyiguang
# 登录授权码或者密码
spring.mail.password=ZYCFWACYWJIYLZHI
#spring.mail.password=AAAAAA
# #邮件发信人(即真实邮箱)
spring.mail.properties.from=Guoyiguang2@126.com
#spring.thymeleaf.cache=false
#spring.thymeleaf.prefix=classpath:/views/
# 限制单个文件大小
spring.servlet.multipart.max-file-size=10MB
# 限制请求总量
spring.servlet.multipart.max-request-size=50MB

配置类:

package com.mail.config;

import lombok.Data;
import org.apache.tomcat.util.digester.DocumentProperties;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;


/**
 * @author guoyiguang    
 * @description $
 * @date 2021/12/28$
 */
@ConfigurationProperties(prefix = "spring.mail")
@Component
@Data
public class MailProperties {
    private static final Charset DEFAULT_CHARSET = StandardCharsets.UTF_8;
    private String host;
    private Integer port;
    private String username;
    // ① 授权码 ② 后者 发件人邮箱登录密码也可
    private String password;
    private String protocol = "smtp";
    // 发件人真实邮箱
    @Value("${spring.mail.properties.from}")
    private String from;
    private Charset defaultEncoding = DEFAULT_CHARSET;
    private Map<String, String> properties = new HashMap<>();
}
package com.mail.config;

import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.mail.javamail.JavaMailSenderImpl;

import java.util.Properties;

/**
 * @author guoyiguang  生成 JavaMailSenderImpl bean 交给 spring 管理
 * @description $
 * @date 2021/12/28$
 */
@Configuration
@ConditionalOnProperty(prefix = "spring.mail", name = "host")
class MailSenderPropertiesConfiguration {
    private final MailProperties properties;
    MailSenderPropertiesConfiguration(MailProperties properties) {
        this.properties = properties;
    }
    @Bean
    @ConditionalOnMissingBean
    public JavaMailSenderImpl mailSender() {
        JavaMailSenderImpl sender = new JavaMailSenderImpl();
        sender.setHost(properties.getHost());
        // sender.setPort(PORT);
        sender.setUsername(properties.getUsername());
        sender.setPassword(properties.getPassword());
        sender.setDefaultEncoding("Utf-8");
        Properties p = new Properties();
        //p.setProperty("mail.smtp.timeout", timeout);
        p.setProperty("mail.smtp.auth", "false");
        p.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        p.setProperty("from",properties.getFrom());
        // 设置发件人属性值
        sender.setJavaMailProperties(p);

        return sender;
    }


}

核心代码:

实体类:

package com.mail.entity;

import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;

/**
 * @author guoyiguang
 * @description $
 * @date 2021/12/28$
 */
@Data
public class MailReq {

    private String id;
    private String from;
    private String to;
    private String subject;
    private String text;
    private LocalDateTime sentDate;
    private String cc;
    private String bcc;
    private String status;
    private String error;
    @JsonIgnore
    private MultipartFile[] multipartFiles;
}
package com.mail.service.impl;

import com.mail.entity.MailReq;
import com.mail.service.MailService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailAuthenticationException;
import org.springframework.mail.MailParseException;
import org.springframework.mail.MailPreparationException;
import org.springframework.mail.MailSendException;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import javax.mail.internet.AddressException;
import javax.mail.internet.ParseException;
import java.time.LocalDateTime;
import java.util.Date;

/**
 * @author guoyiguang
 * @description $
 * @date 2021/12/28$
 */
@Service
@Slf4j
public class MailServiceImpl implements MailService {


    @Autowired
    private JavaMailSenderImpl mailSender;

    public MailReq sendMail(MailReq mailReq) {

        if (StringUtils.isEmpty(mailReq.getTo())) {
            throw new RuntimeException("邮件收信人不能为空");
        }
        if (StringUtils.isEmpty(mailReq.getSubject())) {
            throw new RuntimeException("邮件主题不能为空");
        }
        if (StringUtils.isEmpty(mailReq.getText())) {
            throw new RuntimeException("邮件内容不能为空");
        }
        try {
            sendMimeMail(mailReq);
            return  mailReq ;
        } catch (Exception e) {
            log.error("发送邮件失败:", e);
            mailReq.setStatus("fail");
            mailReq.setError(e.getMessage());
            return mailReq;
        }

    }


    private void sendMimeMail(MailReq mailReq) {
        try {
            MimeMessageHelper messageHelper = new MimeMessageHelper(mailSender.createMimeMessage(), true);
            mailReq.setFrom(mailSender.getJavaMailProperties().getProperty("from"));
            messageHelper.setFrom(mailSender.getJavaMailProperties().getProperty("from"));
            messageHelper.setTo(mailReq.getTo().split(","));
            messageHelper.setSubject(mailReq.getSubject());
            messageHelper.setText(mailReq.getText());
            if (!StringUtils.isEmpty(mailReq.getCc())) {
                messageHelper.setCc(mailReq.getCc().split(","));
            }
            if (!StringUtils.isEmpty(mailReq.getBcc())) {
                messageHelper.setCc(mailReq.getBcc().split(","));
            }
            if (mailReq.getMultipartFiles() != null) {
                for (MultipartFile multipartFile : mailReq.getMultipartFiles()) {
                    messageHelper.addAttachment(multipartFile.getOriginalFilename(), multipartFile);
                }
            }
            if (StringUtils.isEmpty(mailReq.getSentDate())) {
                mailReq.setSentDate(LocalDateTime.now());
                messageHelper.setSentDate(new Date());
            }
            mailSender.send(messageHelper.getMimeMessage());
            mailReq.setStatus("ok");
            log.info("发送邮件成功:{}->{}", mailReq.getFrom(), mailReq.getTo());
        }
        catch (MailPreparationException mse) {
            log.error("发送邮件失败 , MailPreparationException:{}"    , mse.getMessage());
        }
        catch (MailParseException mse) {
            log.error("发送邮件失败 , MailParseException:{}"   , mse.getMessage());
        }
        catch (MailAuthenticationException mse) {
            //535 Error: authentication failed 发送人账号,密码,或者授权码 错误
            if ( mse.getMessage().contains("authentication failed")){
                log.error("发送邮件失败 ------>>>>>> 发送人邮箱认证失败! ");
            }else{
                log.error("发送邮件失败 , MailAuthenticationException:{}"   , mse.getMessage());
            }
        }
        catch (MailSendException mse) {

            // javax.mail.SendFailedException: Invalid Addresses;
            log.error("发送邮件失败 , MailSendException:{}" , mse.getMessage());
            if (mse.getMessage().contains("Invalid Addresses")){
                // 入库
                log.error("发送邮件失败 , MailSendException:{}" ,"目标地址无效");
            }
        }
        catch (ParseException  mse) {
            if(mse instanceof  AddressException){
                log.error("发送邮件失败 ,目标地址不合法, AddressException:{}" + mse.getMessage());
            }else{
                log.error("发送邮件失败 , ParseException:" + mse);
            }

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }




}

测试controller:

package com.mail.controller;


import com.mail.entity.MailReq;
import com.mail.service.MailService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/*****
 * @Author:
 * @Description:
 ****/
@RestController
@RequestMapping(value = "/mail")
@CrossOrigin
@Slf4j
public class MailController {



    @Autowired
    MailService mailService ;




    /**
     * 功能描述 说明:   multipartFiles 前端传 多个 文件,后台 用 MultipartFile[] 接受
     * @author guoyiguang
     * @date 2021/12/28
     * @param
     * @return
     */
    @PostMapping(value = "/sendAttachmentMail")
    public MailReq sendAttachmentMail(String to, String subject, String text, MultipartFile[] multipartFiles) throws Exception {
        MailReq MailReq = new MailReq();
        MailReq.setTo(to);
        MailReq.setSubject(subject);
        MailReq.setText(text);
        if (multipartFiles.length > 0){
            MailReq.setMultipartFiles(multipartFiles);
        }

        MailReq mailReq1 = mailService.sendMail(MailReq);
        return mailReq1;
    }




}

 

登录qq邮箱:发现收到了正确的消息

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值