springboot实现发送邮件附带附件

说明:实现发送邮件附带邮件供用户下载

引入依赖

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

控制层代码

package com.mindskip.xdd.controller.student;

import cn.hutool.core.util.ObjectUtil;
import com.mindskip.xdd.base.RestResponse;
import com.mindskip.xdd.base.SystemCode;
import com.mindskip.xdd.service.MailService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 邮件
 *
 * @author Gin
 */
@Api(tags = "下载学习资料")
@RestController
@RequiredArgsConstructor
@RequestMapping(value = "/api/student/mail")
public class SendEmailController {

    private final MailService mailService;

    /**
     * 发送邮件
     */
    @ApiOperation("发送邮件")
    @GetMapping(value = "/send")
    public RestResponse sendEmail(@ApiParam("邮箱地址") @RequestParam(value = "mail", required = true) String mail) {

        if (StringUtils.isEmpty(mail)) {
            return RestResponse.fail(SystemCode.ParameterValidError.getCode(), SystemCode.ParameterValidError.getMessage());
        }

        String regEx = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(mail);
        if (!m.matches()) {
            return RestResponse.fail(SystemCode.ParameterValidError.getCode(), "邮箱格式不正确~ 请重新输入");
        }

        File file = null;
        try {
            file = ResourceUtils.getFile("/usr/local/xdd/web/file/downFile.zip");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        if (ObjectUtil.isNull(file)) {
            return RestResponse.fail(SystemCode.InnerError.getCode(), SystemCode.InnerError.getMessage());
        }

        Map<String, String> map = new HashMap<>();
        map.put("fileName", file.getPath());
        map.put("recipients", mail);
        return mailService.sendEmail(map) ? RestResponse.ok("发送成功~ 请前往邮箱下载!") : RestResponse.fail(SystemCode.InnerError.getCode(), "系统错误~ 请稍后再试");
    }
}

这边的路劲地址是项目部署到服务器的地址,要测试的话就把文件放在resources下面测试一下

业务层代码

package com.mindskip.xdd.service.impl;

import com.mindskip.xdd.service.MailService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.internet.MimeMessage;
import java.io.File;
import java.util.Map;

/**
 * @Author Gin
 * @Date 2021/1/20 15:56
 * @Package com.mindskip.xdd.service.impl
 * @Version 1.0
 * @description 发送邮箱业务层
 */
@Service
@RequiredArgsConstructor
public class MailServiceImpl implements MailService {

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

    private final JavaMailSender javaMailSender;

    /**
     * 发送邮件
     */
    @Override
    public boolean sendEmail(Map<String, String> map) {

        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper messageHelper;

        try {

            messageHelper = new MimeMessageHelper(mimeMessage, true,"utf-8");  //设置一下编码,不然预览会出现乱码现象
            messageHelper.setFrom(from); //是从yml获取的发邮件的账户
            messageHelper.setTo(map.get("recipients"));
            messageHelper.setText("设置的文件名字");

            // 携带附件
            FileSystemResource file = new FileSystemResource(map.get("fileName"));
            String fileName = map.get("fileName").substring(map.get("fileName").lastIndexOf(File.separator));
            messageHelper.addAttachment(fileName, file);

            javaMailSender.send(mimeMessage);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

        return true;
    }
}

yml里面的配置

  mail: # 
    host: smtp.qq.com #发送邮件服务器
    username: 715022455@qq.com #发送邮件的邮箱地址
    password: ownlwpciztyjbbhc #客户端授权码,不是邮箱密码,这个在qq邮箱设置里面自动生成的
    properties.mail.smtp.port: 465 #端口号465587
    from: 715022455@qq.com # 发送邮件的地址,和上面username一致
    properties.mail.smtp.starttls.enable: true
    properties.mail.smtp.starttls.required: true
    properties.mail.smtp.ssl.enable: true
    default-encoding: utf-8

大家可以多多学习交流一下

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值