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

使用Slack API上传邮件格式文件失败,文件被识别为纯文本

问题解决:Slack API files.upload 识别邮件类型失败

问题根源

你的代码存在几个关键问题导致Slack无法正确识别邮件类型:

  • 参数拼写错误:tile应为title
  • 文件名无后缀:Slack会优先通过文件名后缀推断文件类型,缺少.eml后缀会让系统默认识别为文本
  • 内容格式不符合要求:content需要传入标准EML格式的邮件内容(符合RFC 5322规范,包含邮件头、正文等完整结构),而非单纯的HTML片段
  • request库使用不当:await与回调函数混用,且request已停止维护,建议替换为更现代的HTTP库

修正后的代码

const request = require("request");

function main() {
  request.post(
    {
      url: 'https://slack.com/api/files.upload',
      formData: {
        token: 'xoxb-token',
        title: 'Email', // 修正拼写错误
        filename: 'test_email.eml', // 添加.eml后缀
        filetype: 'email',
        channels: 'C012345ABCD',
        // 示例标准EML格式内容
        content: `From: sender@example.com
To: receiver@example.com
Subject: Test Email
Content-Type: text/html; charset=utf-8

<html>
<body>
<p>This is a test email content.</p>
</body>
</html>`
      }
    },
    function (err, response) {
      if (err) {
        console.error(err);
      } else {
        console.log(response.body);
      }
    }
  );
}

main();

关键说明

  1. 文件名后缀:添加.eml后缀是让Slack正确识别邮件类型的关键,即使设置了filetype,系统仍会参考文件名后缀做校验
  2. EML格式内容:必须包含完整的邮件头(From、To、Subject等)和符合规范的正文结构,Slack才能解析并显示邮件片段
  3. request库替代建议:由于request已废弃,推荐使用axios或原生fetch,示例用axios的写法如下:
const axios = require("axios");
const FormData = require("form-data");

async function main() {
  const form = new FormData();
  form.append('token', 'xoxb-token');
  form.append('title', 'Email');
  form.append('filename', 'test_email.eml');
  form.append('filetype', 'email');
  form.append('channels', 'C012345ABCD');
  form.append('content', `From: sender@example.com
To: receiver@example.com
Subject: Test Email
Content-Type: text/html; charset=utf-8

<html>
<body>
<p>This is a test email content.</p>
</body>
</html>`);

  try {
    const response = await axios.post('https://slack.com/api/files.upload', form, {
      headers: form.getHeaders()
    });
    console.log(response.data);
  } catch (err) {
    console.error(err);
  }
}

main();

内容的提问来源于stack exchange,提问作者Noaman Abdul Gaffar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 15:35:01