Email.Attachments 2.0.0

dotnet add package Email.Attachments --version 2.0.0
                    
NuGet\Install-Package Email.Attachments -Version 2.0.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Email.Attachments" Version="2.0.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Email.Attachments" Version="2.0.0" />
                    
Directory.Packages.props
<PackageReference Include="Email.Attachments" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add Email.Attachments --version 2.0.0
                    
#r "nuget: Email.Attachments, 2.0.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package Email.Attachments@2.0.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=Email.Attachments&version=2.0.0
                    
Install as a Cake Addin
#tool nuget:?package=Email.Attachments&version=2.0.0
                    
Install as a Cake Tool

Email.Attachments (Gmail Provider)

NuGet Downloads License

Comprehensive .NET library for automated email attachment extraction and management from Gmail accounts. Built with enterprise-grade architecture, featuring a high-level use-case oriented API, pluggable storage backends, and rich date filtering capabilities.

Multi-Provider Architecture - v2.0 introduces provider-agnostic core with Gmail as the first supported provider. Future providers (Outlook, etc.) can be easily added.

✨ Features

  • 🎯 Use-Case Oriented API - Business-focused methods (FetchLastMonthEmailFilesAsync, FetchLastQuarterEmailFilesAsync, etc.)
  • 💾 Pluggable Storage - FileSystem, Azure Blob, AWS S3, or custom implementations
  • 📅 Rich Date Filtering - Absolute dates, relative periods, and time abstractions
  • Memory Efficient - Stream-based processing for large attachments
  • 🔐 OAuth 2.0 - Secure Gmail authentication with automatic token refresh
  • 🏗️ Full DI Support - Built on Microsoft.Extensions.Hosting
  • 📊 Rich Metadata - Batch statistics, vendor summaries, processing metrics

📦 Installation

dotnet add package Email.Attachments

NuGet Package Manager:

Install-Package Email.Attachments

🚀 Quick Start

1. Setup Configuration

Create appsettings.json:

{
  "googleCredentials": {
    "Values": {
      "credentialsLocation": "credentials.json",
      "tokenDestination": "token.json"
    }
  },
  "emailsAttachmentsDestination": {
    "Values": {
      "billing@vendor.com": "invoices"
    }
  },
  "storage": {
    "defaultStorageType": "FileSystem",
    "fileSystem": {
      "baseDirectory": "./attachments",
      "defaultNamingStrategy": "WithDateAndSender"
    }
  }
}

2. Register Gmail Services

using ExtractLoadInvoices;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

var builder = Host.CreateApplicationBuilder(args);

// Register Gmail provider services
builder.Services.AddGmailFilesDownloader(builder.Configuration);

var host = builder.Build();

3. Use High-Level API

using Email.Attachments.UseCases;

var manager = host.Services.GetRequiredService<IEmailFilesManager>();

// Download last month's attachments
var batch = await manager.FetchLastMonthEmailFilesAsync();

Console.WriteLine($"Downloaded {batch.Metadata.TotalAttachments} attachments");
Console.WriteLine($"Total size: {batch.Metadata.TotalSizeBytes / 1024.0 / 1024.0:F2} MB");

📚 Usage Examples

Download Last Week's Attachments

var batch = await manager.FetchLastWeekEmailFilesAsync(new FetchOptions
{
    AttachmentStrategy = AttachmentHandlingStrategy.PersistAndReference,
    NamingStrategy = FileNamingStrategy.WithDateAndSender
});

foreach (var emailFile in batch.EmailAttachments)
{
    Console.WriteLine($"{emailFile.SentDate:yyyy-MM-dd} | {emailFile.Sender}");
    foreach (var attachment in emailFile.Attachments)
    {
        Console.WriteLine($"  ✓ {attachment.StorageReference}");
    }
}

Generate Metadata Report (No Downloads)

var batch = await manager.FetchLastMonthEmailFilesAsync(new FetchOptions
{
    AttachmentStrategy = AttachmentHandlingStrategy.MetadataOnly
});

// Fast! Only fetches metadata, no file downloads
foreach (var vendor in batch.Metadata.InvoicesByVendor)
{
    Console.WriteLine($"{vendor.Key}: {vendor.Value} emails");
}

Custom Date Range

var period = TimePeriod.Custom(
    new DateTime(2024, 1, 1),
    new DateTime(2024, 3, 31),
    "Q1 2024");

var batch = await manager.FetchEmailFilesByPeriodAsync(period);

Vendor-Specific Download

var batch = await manager.FetchEmailFilesByVendorAsync(
    "billing@company.com",
    TimePeriod.LastQuarter());

🎯 Attachment Handling Strategies

Strategy Downloads? In Memory? Use Case
MetadataOnly Fast reports
LoadInMemory Immediate processing
PersistAndReference Long-term storage (recommended)
PersistAndLoad Process + archive

🏗️ Architecture

IEmailFilesManager (High-Level API - Provider Agnostic)
    ├─► Time period methods (FetchLastWeekEmailFilesAsync, FetchLastMonthEmailFilesAsync, etc.)
    ├─► Vendor operations (FetchEmailFilesByVendorAsync, FetchEmailFilesByVendorsAsync)
    └─► Custom queries (FetchEmailFilesByPeriodAsync)
         ↓
Uses provider-agnostic services:
    ├─► IEmailService (Gmail implementation: GmailService)
    ├─► IAttachmentPersistenceManager (Storage)
    └─► IAttachmentDownloader (Download & decode)

📧 Email Provider Support

Gmail (Current)

  • ✅ Fully supported
  • ✅ OAuth 2.0 authentication
  • ✅ Advanced query syntax
  • ✅ Label/folder support

Future Providers

  • 🔜 Microsoft Outlook/Exchange (planned)
  • 🔜 Custom IMAP providers (planned)

📅 Time Period Helpers

TimePeriod.LastWeek()      // Previous Monday-Sunday
TimePeriod.LastMonth()     // Previous calendar month
TimePeriod.LastQuarter()   // Previous Q1, Q2, Q3, or Q4
TimePeriod.LastYear()      // Previous calendar year
TimePeriod.LastNDays(30)   // Last 30 days
TimePeriod.Custom(start, end, description)

🔐 Google OAuth Setup

  1. Create a project in Google Cloud Console
  2. Enable Gmail API
  3. Create OAuth 2.0 credentials (Desktop app)
  4. Download credentials.json
  5. Place in your application directory

💾 Storage Providers

FileSystem (Built-in)

"storage": {
  "defaultStorageType": "FileSystem",
  "fileSystem": {
    "baseDirectory": "./attachments",
    "defaultNamingStrategy": "WithDateAndSender"
  }
}

Custom Provider

Implement IAttachmentPersistenceManager:

public class AzureBlobStorage : IAttachmentPersistenceManager
{
    // Your implementation
}

🎨 File Naming Strategies

  • Original - Keep original filename
  • WithTimestamp - invoice_20241215_143022.pdf
  • WithSender - vendorname_invoice.pdf
  • WithDateAndSender - 20241215_vendorname_invoice.pdf (recommended)

📊 Rich Metadata

batch.Metadata.TotalEmails
batch.Metadata.TotalAttachments
batch.Metadata.TotalSizeBytes
batch.Metadata.ProcessingTime
batch.Metadata.InvoicesByVendor  // Dictionary<vendor, count>

🔧 Requirements

  • .NET 10.0 or later
  • Google OAuth 2.0 credentials
  • Gmail account with API access enabled

📖 Documentation

🤝 Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

📄 License

This project is licensed under the MIT License - see the LICENSE file for details.

🙏 Acknowledgments

Built with:

📞 Support


Made with ❤️ by vpaulino

Product Compatible and additional computed target framework versions.
.NET net10.0 is compatible.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
2.0.0 139 1/2/2026
1.0.0 127 1/2/2026

Version 2.0.0 (Breaking Changes):
     - Multi-provider architecture with provider-agnostic core
     - Renamed AddEmailFilesDownloader() to AddGmailFilesDownloader()
     - Introduced provider-agnostic models (EmailMessage, EmailMessageDetails, etc.)
     - GmailEmailQuery for Gmail-specific queries
     - Cleaner service naming (GmailService instead of GmailServiceWrapper)
     - High-level APIs remain unchanged and provider-agnostic
     - Prepared for future Outlook/IMAP support