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

如何使用download-email-attachments库获取并保存邮件发件人地址至JSON文件

How to Get Sender Address with download-email-attachments and Save to JSON

Hey there! I’ve worked with the download-email-attachments library before, so let’s walk through how to grab the sender’s email address and save it along with other mail info to a JSON file.

First off, the key detail you might be missing: when the library returns results after processing emails, each result includes a full email object (parsed using the mailparser package under the hood). This object has all the metadata you need, including the sender’s address.

Here’s a concrete code example:

const downloadAttachments = require('download-email-attachments');
const fs = require('fs');

// Configure your IMAP settings
const config = {
  imap: {
    user: 'your-email@domain.com',
    password: 'your-email-password',
    host: 'imap.domain.com',
    port: 993,
    tls: true
  },
  attachments: {
    directory: './downloaded-attachments'
  }
};

downloadAttachments(config, (error, results) => {
  if (error) {
    console.error('Error fetching emails:', error);
    return;
  }

  // Process each result to extract sender and other info
  const emailRecords = results.map(result => {
    // Grab the sender's email address (handle edge cases where from might be empty)
    const senderAddress = result.email.from?.[0]?.address || 'unknown-sender@example.com';
    
    return {
      senderAddress: senderAddress,
      senderName: result.email.from?.[0]?.name || 'Unknown Sender',
      subject: result.email.subject,
      date: result.email.date,
      attachments: result.attachments.map(att => ({
        fileName: att.fileName,
        filePath: att.filePath
      }))
    };
  });

  // Save the records to a JSON file
  fs.writeFileSync('email-metadata.json', JSON.stringify(emailRecords, null, 2));
  console.log('Email metadata saved to email-metadata.json');
});

Let’s break this down:

  • The results array contains an entry for each email with attachments. Each entry’s email property is a parsed mail object.
  • The from property of result.email is an array (since emails can have multiple senders in rare cases), so we access the first element’s address to get the sender’s email.
  • We add optional chaining (?.) and a fallback value to handle cases where the sender info might be missing or malformed.
  • We map through all results to build a structured object with sender details, subject, date, and attachment info, then write this to a JSON file with fs.writeFileSync.

If you ever need more metadata (like recipients, message ID, etc.), you can explore other properties of the result.email object—all follow the standard parsed mail structure from mailparser.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.27 21:44:06