其他分享
首页 > 其他分享> > SpringBoot+Vue 批量发送邮件、工资条

SpringBoot+Vue 批量发送邮件、工资条

作者:互联网

SpringBoot+Vue 批量发送邮件、工资条

1.邮箱配置,开启SMTP服务,获取授权码

 

 

 

 2.springboot项目maven

 <!--邮箱-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
            <version>${email.version}</version>
        </dependency>

3.配置application.yml 

spring:下添加

#126邮箱SMTP服务器地址:smtp.126.com,端口号:465或者994
#163邮箱SMTP服务器地址:smtp.163.com,端口号:465或者994
#qq邮箱SMTP服务器地址:smtp.qq.com,端口号:465或587
#yeah邮箱SMTP服务器地址:smtp.yeah.net,端口号:465或者994
#邮件设置
mail:
  # 配置 SMTP 服务器地址
  host: smtp.qq.com
  # 发送者邮箱
  username: 1181055xxx@qq.com
  # 配置密码,注意不是真正的密码,而是刚刚申请到的授权码
  password: bzqieszypovyhjab
  #邮件标题,邮件发送方
  subject-from: xx财务
  # 端口号465或587
  port: 587
  # 默认的邮件编码为UTF-8
  default-encoding: UTF-8
  # 配置SSL 加密工厂
  properties:
    mail:
      smtp:
        socketFactoryClass: javax.net.ssl.SSLSocketFactory
        starttls:
          enable: true
          required: true
      ssl:
        enable: true
      # 表示开启 DEBUG 模式,这样,邮件发送过程的日志会在控制台打印出来,方便排查错误
      debug: false

 

4.测试发送方法

简单发送

  @GetMapping("/fa")
    public void sendSimpleEmail() {
        SimpleMailMessage message = new SimpleMailMessage();//创建简单邮件消息
        message.setFrom("1181055xxx@qq.com");//设置发送人
        message.setTo("160606xxx@qq.com");//设置收件人
        /* String[] adds = {"xxx@qq.com","yyy@qq.com"}; //同时发送给多人
        message.setTo(adds);*/
        message.setSubject("这是一封测试邮件");//设置主题
        message.setText("这是测试邮件的正文");//设置内容
        try {
            mailSender.send(message);//执行发送邮件
            log.info("简单邮件已经发送。");
        } catch (Exception e) {
            log.error("发送简单邮件时发生异常!", e);
        }
    }

HTML发送

 @GetMapping("/test")
    public void sendHtml() throws Exception {
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        //这里可以自定义发信名称比如:工资条
        helper.setFrom("1181055xxx@qq.com","工资条");
        helper.setTo("160606xxx@qq.com");
        helper.setSubject("这是一封测试邮件");
        helper.setText(
                "<html>\n" +
                        "<style>\n" +
                        "    .td{width:150px;height:70px}\n" +
                        "</style>\n" +
                        "<body>\n" +
                        "<table border=\"1\">\n" +
                        "    <tr>\n" +
                        "        <td style=\"text-align:center\" class=\"td\">序号</td>\n" +
                        "        <td style=\"text-align:center\" class=\"td\">姓名</td>\n" +
                        "        <td style=\"text-align:center\" class=\"td\">员工类别</td>\n" +
                        "    </tr>\n" +
                        "    <tr>\n" +
                        "        <td style=\"text-align:center\" class=\"td\">1</td>\n" +
                        "        <td style=\"text-align:center\" class=\"td\">2</td>\n" +
                        "        <td style=\"text-align:center\" class=\"td\">3</td>\n" +
                        "    </tr>\n" +
                        "</table>\n" +
                        "</body>\n" +
                        "</html>\n",true);
        mailSender.send(message);
    }

Thymeleaf发送

resources下创建tempales文件、创建email.html

<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <title>exchange</title>
</head>
<style>
    body {
        cursor: default;
    }
    .exchangeCode {
        color: #72cdff;
    }
</style>
<body>
<div>
    <label>ExchangeCode:</label>
    <div class="exchangeCode" th:text="${GoldCoinCode}"></div>
</div>
</body>
</html>
@GetMapping("/thyme")
    public void testSendHtmlMailThymeLeaf() throws MessagingException {
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
        helper.setSubject("测试发送Thymeleaf模板Email");
        helper.setFrom("1181055xxx@qq.com");
        helper.setTo("160606xxx@qq.com");
        Context context = new Context();
        context.setVariable("GoldCoinCode", "goldCoinCode");
        String process = templateEngine.process("emil.html", context);
        helper.setText(process,true);
        mailSender.send(mimeMessage);
    }

5.Controller层

 /**
     * 批量发送模板
     *
     * @return 模板
     */
    @GetMapping("/outputTemplate")
    public AjaxResult importTemplate() {
        ExcelUtil<EmailSalarySheetRequest> util = new ExcelUtil<>(EmailSalarySheetRequest.class);
        return util.importTemplateExcel("邮件导出模板");
    }

    /**
     * excel 批量发邮件
     *
     * @param file excel
     * @return TableDataInfo
     * @throws Exception Exception
     */
    @Log(title = "批量发送邮件", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('admin:send:email:batch')")
    @PostMapping("/inputTemplate")
    public AjaxResult importExpress(MultipartFile file) throws Exception {
        ExcelUtil<EmailSalarySheetRequest> excelUtil = new ExcelUtil<>(EmailSalarySheetRequest.class);
        List<EmailSalarySheetRequest> importExcel = excelUtil.importExcel(file.getInputStream());
        if (file.getOriginalFilename() == null) {
            return AjaxResult.success("excel-文件名不能为空");
        }
        if (file.getOriginalFilename().contains("邮件")) {
            return AjaxResult.success(emailService.sendEmailExcel(importExcel));
        } else {
            return AjaxResult.success("excel-文件选择不对");
        }
    }

6.业务层

Excel 表上传 转为发送邮件list对象,发送业务层处理发送邮件

 

VUE

index.vue

<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-download"
          size="mini"
          v-hasPermi="['admin:send:email:batch']"
          @click="handleImport"
        >批量发送邮件
        </el-button>
      </el-col>
    </el-row>
    <!-- 批量发送导入对话框 -->
    <el-dialog title="上传Excel" :visible.sync="batchOpen" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处,或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" slot="tip">
          <el-link type="info" style="font-size:12px" @click="outputTemplate">下载模板</el-link>
        </div>
        <div class="el-upload__tip" style="color:red" slot="tip">提示:仅允许导入“xls”或“xlsx”格式文件!并文件名包含邮件二字</div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" :disabled="flag" @click="submitFormExport">确 定</el-button>
        <el-button @click="cancel2">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {getToken} from "@/utils/auth";
  import {emailOutputTemplate} from "@/api/admin/email/sendEmail";

  export default {
    name: "SendEmail",
    components: {},
    data() {
      return {
        //设置按钮可选
        flag: false,
        // 遮罩层
        loading: true,
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        batchOpen: false,
        rules: {},
        // 用户导入参数
        upload: {
          // 是否显示弹出层(用户导入)
          batchOpen: false,
          // 弹出层标题(用户导入)
          title: "",
          // 是否禁用上传
          isUploading: false,
          // 设置上传的请求头部
          headers: {Authorization: "Bearer " + getToken()},
          // 上传的地址
          url: process.env.VUE_APP_BASE_API + "/admin/email/inputTemplate"
        },
      };
    },
    created() {
      this.getList();
      this.getDicts("zhongmubao_yes_or_no").then(response => {
        this.isDeletedOptions = response.data;
      });
    },
    methods: {
      getList() {
        this.loading = true;
        // listCustomerBallLibraryOperationRecord(this.queryParams).then(response => {
        //   this.customerBallLibraryOperationRecordList = response.rows;
        //   this.total = response.total;
        //   this.loading = false;
        // });
      },
      // 是否删除字典翻译
      isDeletedFormat(row, column) {
        return this.selectDictLabel(this.isDeletedOptions, row.isDeleted);
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 取消按钮
      cancel2() {
        this.batchOpen = false;
      },
      /** 提交按钮 */
      submitFormExport: function (response) {
        this.exportFlag = true;
        this.$refs.upload.submit();
      },
      /** 导出按钮操作 */
      handleExport() {
        const queryParams = this.queryParams;
        this.$confirm('是否确认导出所有批量发送肉丸肉串数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function () {
          return exportCustomerBallLibraryOperationRecord(queryParams);
        }).then(response => {
          this.download(response.msg);
        })
      },
      /** 上传按钮操作 */
      handleImport() {
        this.batchOpen = true;
      },
      outputTemplate() {
        emailOutputTemplate().then(response => {
          this.download(response.msg);
        });
      },
      // 文件上传中处理
      handleFileUploadProgress(event, file, fileList) {
        this.upload.isUploading = true;
      },
      // 文件上传成功处理
      handleFileSuccess(response, file, fileList) {
        this.upload.batchOpen = false;
        this.upload.isUploading = false;
        this.$refs.upload.clearFiles();
        this.$alert(response.msg+":发送"+response.data+"封邮件", "邮件发送结果", {dangerouslyUseHTMLString: true});
        if (response.msg.indexOf(".xlsx") !== -1) {
          this.download(response.msg);
        }
        if (response.data === true) {
          this.flag = false;
        }
      },
    }
  };
</script>

 

 

 

 

 

标签:工资条,false,SpringBoot,com,发送,Vue,true,response,邮件
来源: https://www.cnblogs.com/Runawayprogrammer/p/16473061.html