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.

C# send email with Spire.Email – HTML formatting, SMTP setup, attachments, and multiple recipients

Sending emails from a C# application is a common task in business and enterprise development. Whether you're delivering a project update, sending alerts, or automating reporting workflows, reliable email functionality is essential.

In this article, we’ll walk through how to send emails in C# using Spire.Email for .NET, a powerful component that simplifies SMTP communication and email formatting. We'll explore SMTP configuration, Gmail integration, HTML and plain-text content, file attachments, and multiple recipients.


Table of Contents


1. Project Setup

To begin, create a .NET project (Console App or ASP.NET) and add the Spire.Email for .NET package.

Install via NuGet:

Install-Package Spire.Email

Or manually download the Spire.Email package and reference the Spire.Email.dll from your local installation package.


2. Send a Basic Email via SMTP in C#

The example below shows how to use Spire.Email to send a plain-text email through an SMTP server.

using Spire.Email;
using Spire.Email.Smtp;

// Configure the SMTP client
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.example.com";
smtp.Port = 587;
smtp.Username = "your@example.com";
smtp.Password = "your_password";
smtp.ConnectionProtocols = ConnectionProtocols.StartTls;

// Create maill addresses
MailAddress sender = new MailAddress("your@example.com", "Sender Name");
MailAddress recipient = new MailAddress("recipient@example.com", "Recipient Name");
MailMessage message = new MailMessage(sender, recipient);

// Set the email content
message.Subject = "Test Email";
message.BodyText = "This is a plain-text test email.";

// Send the email
smtp.SendOne(message);

Explanation:

  • Uses MailAddress and MailMessage from Spire.Email
  • Establishes a secure SMTP connection using ConnectionProtocols.StartTls

The screenshot below shows the actual email received using the above SMTP code.

C# plain-text email sent using Spire.Email via SMTP


3. Send HTML Email with Attachments via Gmail SMTP in C#

The following C# code example demonstrates how to send an HTML-formatted email using Gmail SMTP, including multiple recipients, a file attachment, and plain-text fallback for clients that do not support HTML.

using Spire.Email;
using Spire.Email.Smtp;

// Create MailAddress objects
MailAddress from = new MailAddress("your@gmail.com", "Your Name");
MailAddress to1 = new MailAddress("user1@example.com", "User One");
MailAddress to2 = new MailAddress("user2@example.com", "User Two");

// Create a mail message
MailMessage message = new MailMessage(from, to1);
message.To.Add(to2);
message.Cc.Add(new MailAddress("cc@example.com", "CC Person"));
message.Bcc.Add(new MailAddress("bcc@example.com"));

// Set the body HTML and text for the message
message.Subject = "Monthly Report - June 2025";
message.BodyHtml = "<h2 style='color:#2E86C1;'>Report Summary</h2><p>Please see the attached PDF report.</p>";
message.BodyText = "Report Summary - please see the attached PDF.";

// Add an attachment to the email
Attachment attachment = new Attachment(@"Sample.pdf");
message.Attachments.Add(attachment);

// Configure the SMTP client
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.Port = 587;
smtp.Username = "your@gmail.com";
smtp.Password = "your_app_password";
smtp.ConnectionProtocols = ConnectionProtocols.StartTls;

// Sen the email
smtp.SendOne(message);

Explanation:

  • Uses MailAddress, MailMessage, Attachment, and SmtpClient from Spire.Email
  • Combines BodyHtml and BodyText to support HTML and plain-text email clients
  • Adds multiple recipients via To.Add(), Cc.Add(), and Bcc.Add()
  • Sends email securely through Gmail using ConnectionProtocols.StartTls

Gmail requires App Passwords if 2FA is enabled.

The following screenshot shows the HTML-formatted email with rich text, CC and BCC recipients, and a PDF attachment, as received from Gmail SMTP.

HTML email with attachment and multiple recipients sent from C# via Gmail SMTP using Spire.Email

Related article: How to Send an Email with Attachments in C#


4. Advanced Email Features with Spire.Email

This section demonstrates advanced C# email-sending capabilities using Spire.Email, including embedded images and batch dispatch.

// Prepare an email with embedded image
MailMessage message = new MailMessage(
    new MailAddress("your@domain.com", "Sender"),
    new MailAddress("client@domain.com", "Client"));

message.Subject = "Branding Update";
message.BodyHtml = "<h1>Our New Logo</h1><img src=\"cid:logo\">";
message.BodyText = "Please view this message in HTML to see the image.";

Attachment logo = new Attachment(@"C:\Images\logo.png");
logo.ContentId = "logo";
logo.DispositionType = "Inline";
message.Attachments.Add(logo);

// Prepare a second email
MailMessage message2 = new MailMessage(
    new MailAddress("your@domain.com"),
    new MailAddress("sales@domain.com"));
message2.Subject = "Weekly Summary";
message2.BodyText = "This is an automated weekly update.";

// Create SMTP client
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.domain.com";
smtp.Port = 587;
smtp.Username = "your@domain.com";
smtp.Password = "your_password";
smtp.ConnectionProtocols = ConnectionProtocols.StartTls;

// Send one email
smtp.SendOne(message);

// Send emails in batch
smtp.SendSome(new List<MailMessage> { message, message2 });

Explanation:

  • Attachment.ContentId and DispositionType = "Inline" allow inline images using CID references in HTML.
  • SendOne() sends a single message.
  • SendSome() sends multiple messages as a batch. Ideal for scheduled reports or group notifications.

The following screenshot shows an email with an embedded company logo and a plain-text fallback, demonstrating how Spire.Email renders HTML content with inline images.

Email sent using Spire.Email showing embedded logo image and styled HTML content

You may also like: Creating MSG Files with RTF Body and Attachments Using C#


5. Common Errors and Troubleshooting

Error Likely Cause
Authentication failed Incorrect credentials or missing app password
Secure connection required Use StartTLS or SSL in ConnectionProtocols
HTML content not displaying Ensure BodyHtml and fallback BodyText are set
File not found Incorrect file path for attachment

6. Use Cases for Spire.Email

Spire.Email for .NET is suitable for:

  • Daily/weekly automated reporting
  • User signup and notification emails
  • Order confirmations with attachments
  • Form submission alerts
  • Embedded-image newsletters

Its clean API removes the need to manually handle SMTP headers, MIME formatting, and encoding issues.


Conclusion

With Spire.Email for .NET, developers can quickly build robust and flexible email-sending features directly into C# applications. Whether the goal is to deliver transactional messages, generate styled reports, or dispatch scheduled newsletters, this component provides a clean, reliable API that simplifies every step of the process.

By supporting plain-text and HTML formats, attachments, Gmail SMTP, embedded images, and batch sending, Spire.Email helps streamline email integration without the overhead of external dependencies.


7. Apply for a Free Temporary License

To remove the evaluation warning in the email body or attachment footer, you can apply for a free temporary license:

Request a Free 1-Month License

Simply fill out the form and follow the instructions to apply the license in your project. This enables full feature access during evaluation.


8. FAQ

How to send HTML email in C#?

You can set the BodyHtml property of the MailMessage object to send an HTML email using Spire.Email. You can also include BodyText as a fallback for clients that don't support HTML.

How to send email to multiple recipients in C#?

Add multiple recipients using message.To.Add(), message.Cc.Add(), and message.Bcc.Add() methods. Spire.Email supports To, Cc, and Bcc fields.

How to use SMTP to send email in ASP.NET or MVC projects?

The SMTP usage in ASP.NET or MVC is the same as in Console applications. Simply configure the SmtpClient with host, port, credentials, and use the same SendOne() or SendSome() methods to dispatch your message.

Friday, 18 August 2017 07:27

Add Message to PST File in C#, VB.NET

In the previous article, we have introduced how to read a PST file and get the folder information from it. This article will show you how we can add existing mail message files into PSF file for archiving.

Step 1: Load a PST file from disk into an instance of OutlookFile class.

OutlookFile outlookFile = new OutlookFile(@"C:\Users\Administrator\Documents\Outlook Files\Sample.pst");

Step 2: Load a MSG file into an instance of OutlookItme class.

OutlookItem item = new OutlookItem();
item.LoadFromFile(@"C:\Users\Administrator\Documents\Outlook Files\Sample.msg");

Step 3: Get inbox folder from PST file.

OutlookFolder inboxFolder = outlookFile.RootOutlookFolder.GetSubFolder("Inbox");

Step 4: Add the MSG file to inbox folder.

inboxFolder.AddItem(item);

Full Code:

[C#]
using Spire.Email;
using Spire.Email.Outlook;
using System;

namespace AddMessageToPSTFile
{
    class Program
    {
        static void Main(string[] args)
        {
            OutlookFile outlookFile = new OutlookFile(@"C:\Users\Administrator\Documents\Outlook Files\Sample.pst");
            OutlookItem item = new OutlookItem();
            item.LoadFromFile(@"C:\Users\Administrator\Documents\Outlook Files\Sample.msg");
            OutlookFolder inboxFolder = outlookFile.RootOutlookFolder.GetSubFolder("Inbox");
            inboxFolder.AddItem(item);
            Console.WriteLine("Completed");
        }
    }
}
[VB.NET]
Imports Spire.Email
Imports Spire.Email.Outlook

Namespace AddMessageToPSTFile
	Class Program
		Private Shared Sub Main(args As String())
			Dim outlookFile As New OutlookFile("C:\Users\Administrator\Documents\Outlook Files\Sample.pst")
			Dim item As New OutlookItem()
			item.LoadFromFile("C:\Users\Administrator\Documents\Outlook Files\Sample.msg")
			Dim inboxFolder As OutlookFolder = outlookFile.RootOutlookFolder.GetSubFolder("Inbox")
			inboxFolder.AddItem(item)
			Console.WriteLine("Completed")
		End Sub
	End Class
End Namespace

Spire.Email supports to create Outlook message (MSG) files with rich text bodies and attachments in C# and VB.NET. The RTF body supports to set the formatting for the font, such as in bold, underline and set the color and add lists to the message body. It makes the outlook message vivid and clear to view. Here comes to the steps of how to use Spire.Email to create and save the Outlook message with RTF body and attachment in C#.

Step 1: Create an instance of MailMessage class and specify sender and recipient address.

MailAddress addressFrom = new MailAddress("daisy.zhang@e-iceblue.com", "Daisy Zhang");
MailAddress addressTo = new MailAddress("susanwong32@outlook.com");
MailMessage mail = new MailMessage(addressFrom, addressTo);

Step 2: Add the subject, message body and attachment of the message.

mail.Subject = "This is a test message";

string htmlString = @"
   <p>Dear Ms. Susan,</p>
   <p>This is an example of creating an <b>outlook message</b> <u>(msg)</u>.</p>
   <ul>
   <li> Create a message with RTF file </li>
   <li> Create a message with attachment</li>
   </ul>
   <p style='color:red'>This text is in red </p>
   
   <p>Best regards, </p>
   <p>Daisy </p>";  
 mail.BodyHtml = htmlString;
 
 mail.Attachments.Add(new Attachment("logo.png"));

Step 3: Save the message as MSG format.

mail.Save("Sample.msg", MailMessageFormat.Msg);

Effective screenshot:

Creating MSG Files with RTF body and attachment

Full codes:

using Spire.Email;

namespace CreatingMSGFiles
{
    class Program
    {
        static void Main(string[] args)
        {
            MailAddress addressFrom = new MailAddress("daisy.zhang@e-iceblue.com", "Daisy Zhang");
            MailAddress addressTo = new MailAddress("susanwong32@outlook.com");

            MailMessage mail = new MailMessage(addressFrom, addressTo);

            mail.Subject = "This is a test message";
            string htmlString = @"
           <p>Dear Ms. Susan,</p>
           <p>This is an example of creating an <b>outlook message</b> <u>(msg)</u>.</p>
           <ul>
           <li> Create a message with RTF file </li>
           <li> Create a message with attachment</li>
           </ul>
           <p style='color:red'>This text is in red </p>
           <p>Best regards, </p>
           <p>Daisy </p>";

            mail.BodyHtml = htmlString;

            mail.Attachments.Add(new Attachment("logo.png"));

            mail.Save("Sample.msg", MailMessageFormat.Msg);
        }
    }
}

The PST files are used to store information that pertains to the e-mail folders, addresses, contact information, email messages and other data that is saved within Outlook and Exchange programs. Spire.Email supports to read PST files and get the folder information such as folder name, message count and unread message count.

Step 1: Load a PST file from disk into an instance of OutlookFile class.

OutlookFile olf = new OutlookFile(@"C:\Users\jack\Documents\Outlook Files\Sample.pst");

Step 2: Get the folders collection.

OutlookFolderCollection folderCollection = olf.RootOutlookFolder.GetSubFolders();

Step 3: Traverse the collection and get the folder information of each element in the collection.

foreach (OutlookFolder folder in folderCollection)
{
    Console.WriteLine("Folder: " + folder.Name);
    Console.WriteLine("Total items: " + folder.ItemCount);
    Console.WriteLine("Total unread items: " + folder.UnreadItemCount);
    Console.WriteLine("Whether this folder has subfolders: {0}", (folder.HasSubFolders)?"Yes":"No");
    Console.WriteLine("------------------Next Folder--------------------");
}

Output:

Get Folder Information from PST File in C#, VB.NET

Full Code:

[C#]
using Spire.Email;
using Spire.Email.Outlook;
using System;

namespace GetFolderInformation 
{
    class Program
    {
        static void Main(string[] args)
        {
            OutlookFile olf = new OutlookFile(@"C:\Users\jack\Documents\Outlook Files\Sample.pst");
            OutlookFolderCollection folderCollection = olf.RootOutlookFolder.GetSubFolders();

            foreach (OutlookFolder folder in folderCollection)
            {
                Console.WriteLine("Folder: " + folder.Name);
                Console.WriteLine("Total items: " + folder.ItemCount);
                Console.WriteLine("Total unread items: " + folder.UnreadItemCount);
                Console.WriteLine("Whether this folder has subfolders: {0}", (folder.HasSubFolders) ? "Yes" : "No");
                Console.WriteLine("------------------Next Folder--------------------");
            }
            Console.WriteLine("Completed");
        }
    }
}
[VB.NET]
Imports Spire.Email
Imports Spire.Email.Outlook

Namespace GetFolderInformation
	Class Program
		Private Shared Sub Main(args As String())
			Dim olf As New OutlookFile("C:\Users\jack\Documents\Outlook Files\Sample.pst")
			Dim folderCollection As OutlookFolderCollection = olf.RootOutlookFolder.GetSubFolders()

			For Each folder As OutlookFolder In folderCollection
				Console.WriteLine("Folder: " + folder.Name)
				Console.WriteLine("Total items: " + folder.ItemCount)
				Console.WriteLine("Total unread items: " + folder.UnreadItemCount)
				Console.WriteLine("Whether this folder has subfolders: {0}", If((folder.HasSubFolders), "Yes", "No"))
				Console.WriteLine("------------------Next Folder--------------------")
			Next
			Console.WriteLine("Completed")
		End Sub
	End Class
End Namespace
Published in Manipulate Folders

A file with the EMLX or EML file extension is a Mail Message file used to store an email message. EML/EMLX file can converted to MHTML or MSG file format with few lines of core code by using Spire.Email.

Convert EML/EMLX to MHTML

[C#]
using Spire.Email;
using System;

namespace ConvertEMLandEMLXtoMHTML 
{
    class Program
    {
        static void Main(string[] args)
        {
            MailMessage message = MailMessage.Load("example.eml");
            message.Save("ToMhtml.mhtml", MailMessageFormat.Mhtml);
            Console.WriteLine("Done");
        }
    }
}
[VB.NET]
Imports Spire.Email

Namespace ConvertEMLandEMLXtoMHTML
	Class Program
		Private Shared Sub Main(args As String())
			Dim message As MailMessage = MailMessage.Load("example.eml")
			message.Save("ToMhtml.mhtml", MailMessageFormat.Mhtml)
			Console.WriteLine("Done")
		End Sub
	End Class
End Namespace

Convert EML/EMLX to MSG

[C#]
using Spire.Email;
using System;

namespace ConvertEMLandEMLXtoMSG 
{
    class Program
    {
        static void Main(string[] args)
        {
            MailMessage message = MailMessage.Load("example.eml");
            message.Save("ToMsg.msg", MailMessageFormat.Msg);
            Console.WriteLine("Done");
        }
    }
}
[VB.NET]
Imports Spire.Email

Namespace ConvertEMLandEMLXtoMSG
	Class Program
		Private Shared Sub Main(args As String())
			Dim message As MailMessage = MailMessage.Load("example.eml")
			message.Save("ToMsg.msg", MailMessageFormat.Msg)
			Console.WriteLine("Done")
		End Sub
	End Class
End Namespace

Spire.Email supports to manage folder subscriptions by using ImapClient.Subscribe and ImapClient.Unsubscribe method.

The following example shows how to subscribe to a folder and unsubscribe from a folder using Spire.Email component.

Detail steps:

Step 1: Create an ImapClient instance.

ImapClient imap = new ImapClient();

Step 2: Set host, port, authentication and connection protocol.

imap.Host = "outlook.office365.com";
imap.Port = 143;
imap.Username = "LeonDavisLD@outlook.com";
imap.Password = "password";
imap.ConnectionProtocols = ConnectionProtocols.Ssl;

Step 3: Connect the imap server.

imap.Connect();

Step 4: Subscribe folder using its name.

imap.Subscribe("Folder1");

Step 5: Unsubscribe folder.

imap.Unsubscribe("Folder2");

Screenshot:

Subscribe and Unsubscribe Folders in C#, VB.NET

Full code:

[C#]
using Spire.Email;
using Spire.Email.IMap;

namespace SubscribAndUnsubscribeFolders 
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create an ImapClient instance
            ImapClient imap = new ImapClient();

            //Set host, port, authentication and connection protocol
            imap.Host = "outlook.office365.com";
            imap.Port = 143;
            imap.Username = "LeonDavisLD@outlook.com";
            imap.Password = "password";
            imap.ConnectionProtocols = ConnectionProtocols.Ssl;

            //Connect the imap server
            imap.Connect();

            //subscribe folder using its name
            imap.Subscribe("Folder1");

            //Unsubscribe folder
            imap.Unsubscribe("Folder2"); 
        }
    }
}
[VB.NET]
Imports Spire.Email
Imports Spire.Email.IMap

Namespace SubscribAndUnsubscribeFolders
	Class Program
		Private Shared Sub Main(args As String())
			'Create an ImapClient instance
			Dim imap As New ImapClient()

			'Set host, port, authentication and connection protocol
			imap.Host = "outlook.office365.com"
			imap.Port = 143
			imap.Username = "LeonDavisLD@outlook.com"
			imap.Password = "password"
			imap.ConnectionProtocols = ConnectionProtocols.Ssl

			'Connect the imap server
			imap.Connect()

			'subscribe folder using its name
			imap.Subscribe("Folder1")

			'Unsubscribe folder
			imap.Unsubscribe("Folder2")
		End Sub
	End Class
End Namespace
Published in Manipulate Folders

When we operate the email messages, we may need to send the message to many more email address. Spire.Email supports to send a message to many email addresses at one time. This article demonstrates how to add the new send To and Cc email address from an existing email message via Spire.Email in C# and VB.NET.

Firstly, please view the sample email message with one to and cc email address:

Update the send to email address for Email message

How to add new send to and cc email addresses:

[C#]
using Spire.Email;

namespace Update 
{
    class Program
    {
        static void Main(string[] args)
        {
            //Load the mail message from file
            MailMessage mail = MailMessage.Load("Sample.msg");

            //add a new To email address and its display name
            mail.To.Add(new MailAddress("support@e-iceblue.com", "E-iceblue Support"));

            // add a new Cc email address and its display name
            mail.Cc.Add(new MailAddress("comments@e-iceblue.com", "Comments"));


            // Save the message
            mail.Save("ChangeEmailAddress.msg", MailMessageFormat.Msg);   
        }
    }
}
[VB.NET]
Imports Spire.Email

Namespace Update
	Class Program
		Private Shared Sub Main(args As String())
			'Load the mail message from file
			Dim mail As MailMessage = MailMessage.Load("Sample.msg")

			'add a new To email address and its display name
			mail.[To].Add(New MailAddress("support@e-iceblue.com", "E-iceblue Support"))

			' add a new Cc email address and its display name
			mail.Cc.Add(New MailAddress("comments@e-iceblue.com", "Comments"))


			' Save the message
			mail.Save("ChangeEmailAddress.msg", MailMessageFormat.Msg)
		End Sub
	End Class
End Namespace

Effective screenshot after changing the email address:

Update the send to email address for Email message

Tuesday, 25 July 2017 07:29

Search Email Messages in C#, VB.NET

Spire.Email allows developers to search mailbox for email messages that match the given search criteria. This article illustrates how to search email messages using Spire.Email component.

Detail steps:

Step 1: Create an ImapClient instance.

ImapClient imap = new ImapClient();

Step 2: Set host, port, authentication and connection protocol.

imap.Host = "outlook.office365.com";
imap.Port = 143;
imap.Username = "LeonDavisLD@outlook.com";
imap.Password = "password";
imap.ConnectionProtocols = ConnectionProtocols.Ssl;

Step 3: connect the imap server.

imap.Connect();

Step 4: Select Inbox folder.

imap.Select("Inbox");

Step 5: Search email messages in the folder that match the search criteria.

//Search email messages sent from “Alice”
ImapMessageCollection messages = imap.Search("'From' Contains 'Alice'");
Console.WriteLine("Number of messages sent from Alice: " + messages.Count);

//Search email messages with “Spire” string in subject
messages = imap.Search("'Subject' Contains 'Spire'");
Console.WriteLine("Number of messages with 'Spire' in subject: " + messages.Count);

Screenshot:

Search Email Messages in C#, VB.NET

Full code:

[C#]
using Spire.Email;
using Spire.Email.IMap;
using System;

namespace SearchEmailMessages 
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create an ImapClient instance
            ImapClient imap = new ImapClient();

            //Set host, port, authentication and connection protocol
            imap.Host = "outlook.office365.com";
            imap.Port = 143;
            imap.Username = "LeonDavisLD@outlook.com";
            imap.Password = "password";
            imap.ConnectionProtocols = ConnectionProtocols.Ssl;

            //Connect the imap server
            imap.Connect();

            //Select Inbox folder
            imap.Select("Inbox");

            //Search email messages sent from "Alice"
            ImapMessageCollection messages = imap.Search("'From' Contains 'Alice'");
            Console.WriteLine("Number of messages sent from Alice: " + messages.Count);

            //Search email messages with “Spire” string in subject
            messages = imap.Search("'Subject' Contains 'Spire'");
            Console.WriteLine("Number of messages with 'Spire' in subject: " + messages.Count);    
        }
    }
}
[VB.NET]
Imports Spire.Email
Imports Spire.Email.IMap

Namespace SearchEmailMessages
	Class Program
		Private Shared Sub Main(args As String())
			'Create an ImapClient instance
			Dim imap As New ImapClient()

			'Set host, port, authentication and connection protocol
			imap.Host = "outlook.office365.com"
			imap.Port = 143
			imap.Username = "LeonDavisLD@outlook.com"
			imap.Password = "password"
			imap.ConnectionProtocols = ConnectionProtocols.Ssl

			'Connect the imap server
			imap.Connect()

			'Select Inbox folder
			imap.[Select]("Inbox")

			'Search email messages sent from "Alice"
			Dim messages As ImapMessageCollection = imap.Search("'From' Contains 'Alice'")
			Console.WriteLine("Number of messages sent from Alice: " + messages.Count)

			'Search email messages with “Spire” string in subject
			messages = imap.Search("'Subject' Contains 'Spire'")
			Console.WriteLine("Number of messages with 'Spire' in subject: " + messages.Count)
		End Sub
	End Class
End Namespace
Thursday, 20 July 2017 07:00

Delete Email messages in C#, VB.NET

This article demonstrates how to delete a specific email message along with all email messages using Spire.Email component.

Detail steps:

Step 1: Create a POP3 client.

Pop3Client pop3 = new Pop3Client();

Step 2: Set host, authentication, port and connection protocol.

pop3.Host = "outlook.office365.com";
pop3.Username = "LeonDavisLD@outlook.com";
pop3.Password = "password";
pop3.Port = 995;
pop3.EnableSsl = true;

Step 3: Connect the pop server.

pop3.Connect();

Step 4: Get the number of messages before deleting message(s).

//Get the number of messages before deleting message(s)
Pop3MessageInfoCollection messages = pop3.GetAllMessages();
Console.WriteLine("Number of messages before deleting: " + messages.Count);

Step 5: Delete message(s).

//Delete an email message by its sequence number
pop3.DeleteMessage(2);

//Delete all messages
//pop3.DeleteAllMessages();

Step 6: Get the number of messages after deleting message(s).

//Get the number of messages after deleting message(s)
messages = pop3.GetAllMessages();
Console.WriteLine("Number of messages after deleting: " + messages.Count);

Delete Email messages in C#, VB.NET

Full code:

[C#]
using Spire.Email;
using Spire.Email.Pop3;
using System;

namespace DeleteEmailMessages 
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a POP3 client
            Pop3Client pop3 = new Pop3Client();

            //Set host, authentication, port and connection protocol
            pop3.Host = "outlook.office365.com";
            pop3.Username = "LeonDavisLD@outlook.com";
            pop3.Password = "password";
            pop3.Port = 995;
            pop3.EnableSsl = true;

            //Connect the pop server
            pop3.Connect();

            //Get the number of messages before deleting message(s)
            Pop3MessageInfoCollection messages = pop3.GetAllMessages();
            Console.WriteLine("Number of messages before deleting: " + messages.Count);

            //Delete an email message by its sequence number
            pop3.DeleteMessage(2);

            //Delete all messages
            //pop3.DeleteAllMessages();

            //Get the number of messages after deleting message(s)
            messages = pop3.GetAllMessages();
            Console.WriteLine("Number of messages after deleting: " + messages.Count);       
        }
    }
}
[VB.NET]
Imports Spire.Email
Imports Spire.Email.Pop3

Namespace DeleteEmailMessages
	Class Program
		Private Shared Sub Main(args As String())
			'Create a POP3 client
			Dim pop3 As New Pop3Client()

			'Set host, authentication, port and connection protocol
			pop3.Host = "outlook.office365.com"
			pop3.Username = "LeonDavisLD@outlook.com"
			pop3.Password = "password"
			pop3.Port = 995
			pop3.EnableSsl = True

			'Connect the pop server
			pop3.Connect()

			'Get the number of messages before deleting message(s)
			Dim messages As Pop3MessageInfoCollection = pop3.GetAllMessages()
			Console.WriteLine("Number of messages before deleting: " + messages.Count)

			'Delete an email message by its sequence number
			pop3.DeleteMessage(2)

			'Delete all messages
			'pop3.DeleteAllMessages();

			'Get the number of messages after deleting message(s)
			messages = pop3.GetAllMessages()
			Console.WriteLine("Number of messages after deleting: " + messages.Count)
		End Sub
	End Class
End Namespace
Page 1 of 2