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

如何在Node.js中从URL下载PDF文件并直接存入变量?

直接将PDF文件存入变量并通过Nodemailer发送的方案

当然可以,完全不用把文件存到本地文件夹,直接把文件内容以Buffer形式存在变量里就行,还能节省磁盘IO开销。下面给你两种常用的实现方式:

方法一:使用 axios 获取文件Buffer

先确保安装了 axios:

npm install axios

代码示例(结合Nodemailer完整流程):

const axios = require('axios');
const nodemailer = require('nodemailer');

// 配置Nodemailer传输器(以SMTP为例,根据你的实际邮箱服务商修改)
const transporter = nodemailer.createTransport({
  host: 'smtp.example.com',
  port: 587,
  secure: false,
  auth: {
    user: '你的邮箱地址',
    pass: '邮箱授权码/密码'
  }
});

async function sendPdfAsAttachment(pdfUrl, recipientEmail) {
  try {
    // 从URL获取PDF二进制数据
    const response = await axios.get(pdfUrl, {
      responseType: 'arraybuffer' // 指定响应类型为二进制数组
    });
    const pdfBuffer = Buffer.from(response.data, 'binary');

    // 组装邮件参数
    const mailOptions = {
      from: '你的邮箱地址',
      to: recipientEmail,
      subject: '请查收PDF附件',
      text: '附件为你需要的PDF文件',
      attachments: [
        {
          filename: 'target.pdf', // 附件显示的文件名
          content: pdfBuffer, // 直接传入Buffer变量
          contentType: 'application/pdf' // 指定文件MIME类型
        }
      ]
    };

    // 发送邮件
    const sendResult = await transporter.sendMail(mailOptions);
    console.log('邮件发送成功,消息ID:', sendResult.messageId);
  } catch (err) {
    console.error('处理出错:', err);
  }
}

// 调用示例
sendPdfAsAttachment('https://example.com/your-target.pdf', '收件人邮箱@xxx.com');

方法二:使用 node-fetch 获取文件Buffer

如果习惯用 node-fetch,同样可以实现:
先安装依赖:

npm install node-fetch

代码示例:

const fetch = require('node-fetch');
const nodemailer = require('nodemailer');

// 配置Nodemailer传输器
const transporter = nodemailer.createTransport({
  host: 'smtp.example.com',
  port: 587,
  secure: false,
  auth: {
    user: '你的邮箱地址',
    pass: '邮箱授权码/密码'
  }
});

async function sendPdfAsAttachment(pdfUrl, recipientEmail) {
  try {
    const response = await fetch(pdfUrl);
    if (!response.ok) {
      throw new Error(`请求PDF失败,状态码:${response.status}`);
    }
    // 将响应转为Buffer
    const pdfBuffer = await response.buffer();

    const mailOptions = {
      from: '你的邮箱地址',
      to: recipientEmail,
      subject: '请查收PDF附件',
      text: '附件为你需要的PDF文件',
      attachments: [
        {
          filename: 'target.pdf',
          content: pdfBuffer,
          contentType: 'application/pdf'
        }
      ]
    };

    const sendResult = await transporter.sendMail(mailOptions);
    console.log('邮件发送成功,消息ID:', sendResult.messageId);
  } catch (err) {
    console.error('处理出错:', err);
  }
}

// 调用示例
sendPdfAsAttachment('https://example.com/your-target.pdf', '收件人邮箱@xxx.com');

关键说明

  • 核心逻辑是通过HTTP请求直接拉取文件的二进制数据,转为Node.js的Buffer类型存在变量中
  • Nodemailer的attachments配置里,直接把content字段设为这个Buffer即可,无需指定本地文件路径
  • 请根据实际情况修改SMTP配置、邮箱信息、文件名等参数

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 17:10:16