Read Email in C# via IMAP and POP3 (Outlook Example Included)

Read email in C# using IMAP and POP3 with Outlook example

Reading emails using C# is a common task in enterprise applications where automatic email processing is needed. For example, customer support systems retrieve tickets from email inboxes, financial platforms extract PDF invoices from attachments, and workflow tools react to notification emails. These applications require access to message content, metadata (sender, subject, timestamp), and attachments.

In this article, we’ll walk through how to read emails in C# using IMAP and POP3, and access Gmail or Outlook mailboxes securely with OAuth 2.0. We'll use Spire.Email for .NET, a library that simplifies email client implementation by providing a unified API for IMAP, POP3, and SMTP. It supports both OAuth and password-based authentication, and allows parsing full MIME messages including headers, bodies, and attachments.

This article covers:


Environment Setup

To follow this tutorial, you’ll need the following:

  • A .NET development environment (e.g., Visual Studio)
  • Spire.Email for .NET (Install via NuGet: Install-Package Spire.Email)
  • Access to a Gmail or Outlook account with OAuth 2.0 enabled

Spire.Email for .NET supports standard email protocols—IMAP, POP3, and SMTP—and provides built-in functionality for MIME parsing, attachments, HTML rendering, and encoding handling.

You can also try Free Spire.Email for .NET if your project is small or for evaluation.


Authenticate Email Access via OAuth

Modern email providers such as Gmail and Outlook require OAuth 2.0 for secure and token-based access to IMAP and POP3 services. Gmail still supports app passwords for POP3 in some cases, but OAuth is the preferred and more secure method.

Here’s how to use MSAL.NET to acquire an access token for Outlook:

var app = PublicClientApplicationBuilder
    .Create("your-client-id")
    .WithDefaultRedirectUri()
    .Build();

string[] scopes = new[] { "https://outlook.office365.com/IMAP.AccessAsUser.All" };

AuthenticationResult result = await app
    .AcquireTokenInteractive(scopes)
    .ExecuteAsync();

string accessToken = result.AccessToken;

For Gmail, you can use Google.Apis.Auth or any OAuth 2.0 compliant method to retrieve a token with the https://mail.google.com/ scope. This token can then be passed to Spire.Email for authentication.


Read Emails Using IMAP in C# from Outlook and Gmail

To read emails from Outlook or Gmail in C#, IMAP is a widely used protocol that allows access to mailbox folders, message flags, and full message content. With Spire.Email for .NET, you can use the ImapClient class to connect securely to IMAP servers using OAuth tokens.

The following C# example demonstrates how to read emails from Outlook's IMAP server:

using Spire.Email;
using Spire.Email.IMap;
using System.Text;

class Program
{
    static void Main()
    {
        ImapClient client = new ImapClient();

        // Connect to IMAP server (Outlook)
        client.Host = "outlook.office365.com";
        client.Port = 993;
        client.ConnectionProtocols = ConnectionProtocols.Ssl;

        // Use OAuth 2.0
        client.UseOAuth = true;
        client.Username = "your-email@outlook.com";
        client.AccessToken = "your-access-token";

        client.Connect();
        client.Login();

        // Retrieve message count in the Inbox
        int messageCount = client.GetMessageCount("Inbox");
        StringBuilder messageDetails = new StringBuilder();

        for (int i = 0; i <= messageCount; i++)
        {
            MailMessage message = client.GetFullMessage(i);
            messageDetails.AppendLine("Message: " + i);
            messageDetails.AppendLine("Subject: " + message.Subject);
            messageDetails.AppendLine("From: " + message.From.Address);
            messageDetails.AppendLine("Date: " + message.Date);
            messageDetails.AppendLine("Body (HTML): " + message.BodyHtml);
        }

        File.WriteAllText("MessageInfo.txt", messageDetails.ToString());
        client.Disconnect();
    }
}

Technical Details

  • ImapClient: Represents an IMAP client connection. It handles server communication and supports OAuth-based authentication via the UseOAuth property.
  • Host and Port: Set the server address and port number. For Outlook, you can use "outlook.office365.com" and port 993 with SSL.
  • AccessToken: Replace "your-access-token" with a valid token obtained via Microsoft or Google OAuth 2.0 flow.
  • GetMessageCount("Inbox"): Retrieves the number of emails in the specified folder.
  • GetFullMessage(i): Retrieves the full content of the message at the specified index as a MailMessage object.
  • MailMessage: Represents an email message. Properties like Subject, From, Date, and BodyHtml allow structured access to message details.

The following screenshot shows the extracted email subject, sender, and HTML body saved from Outlook using IMAP:

imap email extraction c# outlook example

By combining Spire.Email’s IMAP interface with OAuth security and flexible MIME parsing, you can reliably automate email reading in C# with full access to both content and context.

If you need examples of how to send emails, please refer to How to Send Emails Using C#.


Read Emails via POP3 in C#

If folder management and server-side search are not required, POP3 offers a simpler alternative to IMAP. The following example demonstrates how to read emails using POP3 with Spire.Email.

using Spire.Email;
using Spire.Email.Pop3;

Pop3Client popClient = new Pop3Client();
popClient.Host = "pop.gmail.com";
popClient.Port = 995;
popClient.EnableSsl = true;
popClient.Username = "your-address@gmail.com";
popClient.Password = "your-password";

// Or use OAuth
// popClient.UseOAuth = true;
// popClient.AccessToken = "your-access-token";

popClient.Connect();
popClient.Login();

for (int i = 1; i < popClient.GetMessageCount(); i++)
{
    MailMessage msg = popClient.GetMessage(i);
    Console.WriteLine("Message - " + i);
    Console.WriteLine("Subject: " + msg.Subject);
    Console.WriteLine("From: " + msg.From.Address);
}

popClient.Disconnect();

This screenshot displays the console output after fetching messages via POP3 from Gmail:

c# pop3 gmail email read output

Unlike IMAP, POP3 downloads messages but does not maintain folder structure or message states on the server. Choose POP3 for simple retrieval scenarios.


Advanced Email Parsing in C#: Extract Attachments and Plain Text

In many cases, it's necessary to extract the plain-text content of an email for further processing, or to retrieve attachments for downstream use such as storage, analysis, or forwarding. The following C# example demonstrates how to access and save both the plain-text body and attachments using the MailMessage object.

MailMessage message = client.GetFullMessage(index);

// Retrieve plain text content
string plainText = message.BodyText;

// Extract attachments
foreach (Attachment attachment in message.Attachments)
{
    string path = Path.Combine("Attachments", attachment.ContentType.Name);
    Directory.CreateDirectory("Attachments");
    using (var fileStream = new FileStream(path, FileMode.Create, FileAccess.Write))
    {
        attachment.Data.Position = 0;
        attachment.Data.CopyTo(fileStream);
    }
}

Notes:

  • Most emails contain both HTML and plain text bodies; use the format appropriate for your application.
  • To skip embedded images (like inline logos), check that attachment.ContentDisposition.DispositionType != "Inline".

Below is a sample output showing saved attachments and extracted plain text from the retrieved email:

extract email attachments plain text c# example

For more detailed operations such as managing email folders—creating, deleting, or moving messages—please refer to our guide on Email Folder Management in C#.


Summary

With Spire.Email for .NET, you can programmatically access Gmail or Outlook inboxes in C# using either IMAP or POP3. The library supports OAuth 2.0 authentication, parses both HTML and plain-text email bodies, and enables attachment extraction for downstream processing. Whether you're building an internal automation tool, an alerting system, or an email parser, Spire.Email provides the essential components for email integration in .NET applications.

If you'd like to explore all features without limitations, you can apply for a free temporary license.


Frequently Asked Questions

Can I use Spire.Email for sending emails too?

Yes. Spire.Email for .NET includes support for SMTP as well, allowing you to send HTML-formatted emails, add attachments, and configure encoding and headers.

Does Spire.Email work with other email providers?

Yes. As long as the provider supports standard IMAP, POP3, or SMTP protocols, and offers compatible authentication (OAuth or basic), it will work with Spire.Email.

How do I get the access token programmatically?

For Outlook, you can use Microsoft’s MSAL.NET; for Gmail, use Google.Apis.Auth or any other OAuth library that retrieves a valid token with mail access scopes. These tokens can then be passed to the email client for secure login.