Download the latest messages from Gmail using IMAP and C#

  |   Martin Vobr

This article shows how to connect to a Gmail mailbox, authenticate using an App Password, and download the most recent messages using the IMAP protocol. The C# sample code uses the Rebex Secure Mail library.

Setting up Gmail

IMAP protocol support in Gmail needs to be turned on. See how to enable IMAP protocol for Gmail. You will need to generate an App Password for your application as well.

Getting Rebex IMAP library for .NET

Connect, log in and get message list

The following code shows how to download the latest 10 messages from the inbox.

using Rebex.Mail;
using Rebex.Net;
...

var imap = new Imap();
imap.Connect("imap.gmail.com", SslMode.Implicit);
imap.Login("example@gmail.com", "haiqdcoiefewedxq");

// select the 'Inbox' folder
imap.SelectFolder("Inbox");
var totalMessageCount = imap.CurrentFolder.TotalMessageCount;

// max last 10 messages
var messageSet = new ImapMessageSet();
messageSet.AddRange(Math.Max(1, totalMessageCount - 10), totalMessageCount);

// download message info; list details
var messages = imap.GetMessageList(messageSet, ImapListFields.Envelope);
foreach (var message in messages)
{
    Console.WriteLine($"{message.ReceivedDate}\t {message.Subject}");
}
Console.WriteLine($"Downloaded {messages.Count} of {totalMessageCount} messages.");

Solving the "Application-specific password required" error

If you use your main Google account password, you would most likely get the following error when trying to log in:

Application-specific password required

For security reasons, Gmail doesn't allow using the primary password in third-party applications. Instead, either use application-specific App Passwords (simple, less secure) or log in using OAuth 2.0 (more complex, more secure).

See also