如何使用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
resultsarray contains an entry for each email with attachments. Each entry’semailproperty is a parsed mail object. - The
fromproperty ofresult.emailis an array (since emails can have multiple senders in rare cases), so we access the first element’saddressto 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
相关产品推荐
相关产品推荐

