You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在VueJS中使用EmailJS发送PDF附件?

VueJS + EmailJS 发送PDF附件失败的解决方案

问题分析

你当前的代码存在两个核心问题:

  1. 直接对File对象使用window.btoa():this.fileCV是File实例,直接转base64会得到[object File]的无效编码,并非文件实际内容的base64。
  2. 附件参数格式不符合EmailJS要求:EmailJS需要将附件放在attachments数组中,且每个附件需包含filename、content(纯base64编码,不含前缀)、type三个字段,而非单独传递base64字符串。

修正方案

1. 正确读取PDF文件为base64

使用FileReader异步读取File对象,获取包含文件内容的base64字符串。

2. 按照EmailJS规范传递附件参数

在emailjs.send()的参数中添加attachments数组,配置正确的附件信息。

完整修正代码

<template>
  <div>
    <input type="file" @change="onFileSelect" accept=".pdf" />
    <button @click="sendEmail">发送邮件</button>
  </div>
</template>

<script>
import emailjs from '@emailjs/browser'; // 确保已安装并导入EmailJS

export default {
  data() {
    return {
      selectedPdf: null
    };
  },
  methods: {
    onFileSelect(e) {
      this.selectedPdf = e.target.files[0];
    },
    async sendEmail() {
      if (!this.selectedPdf) {
        alert('请选择PDF文件');
        return;
      }

      // 转换文件为纯base64编码(去除data URL前缀)
      const fileBase64 = await this.fileToBase64(this.selectedPdf);
      const pureBase64 = fileBase64.split(',')[1];

      try {
        await emailjs.send(
          "service_bbo9xxx", 
          "template_3gxxx", 
          {
            from_name: "",
            to_name: "",
            message: "\"Content\"",
            user_email: "trungsoobin10@gmail.com",
            // 核心:配置attachments数组
            attachments: [
              {
                filename: this.selectedPdf.name,
                content: pureBase64,
                type: this.selectedPdf.type // 例如:application/pdf
              }
            ]
          }
        );
        console.log('邮件及附件发送成功');
      } catch (error) {
        console.error('发送失败:', error);
      }
    },
    // 工具方法:File转base64
    fileToBase64(file) {
      return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onload = () => resolve(reader.result);
        reader.onerror = (err) => reject(err);
        reader.readAsDataURL(file);
      });
    }
  }
};
</script>

额外注意事项

  • 确认你的EmailJS服务套餐支持发送附件(免费套餐可能有附件大小或数量限制)。
  • 无需在EmailJS模板中手动添加附件相关变量,EmailJS会自动解析attachments数组并添加附件到邮件中。
  • 确保传递的content是纯base64字符串,不要包含data:application/pdf;base64,前缀,否则EmailJS无法正确识别。

内容的提问来源于stack exchange,提问作者BinChanhKun

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 22:45:36