Download emails from a Gmail account using POP3 and C#

  |   Martin Vobr

The article shows how to connect to Google Mail (Gmail) mailbox, authenticate using an App Password, retrieve the message list and download messages from your C# code using Rebex POP3 .NET library (also available in the Rebex Mail Pack).

Setting up Gmail

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

Suggestion: POP3 is a legacy mailbox-access protocol. We suggest using the more modern and far more powerful IMAP protocol for connecting to Gmail.

Getting Rebex POP3 library for .NET

Connect, login, get message count and info

Gmail only supports POP3 over TLS-secured channels and uses implicit POP3/TLS mode. The difference between various TLS modes is outside the scope of this article and is discussed in the connecting to a mail server using SSL tutorial.

Now, let's write some code:

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

var pop3 = new Pop3();
pop3.Connect("pop.gmail.com", SslMode.Implicit);
client.Login("example@gmail.com", "haiqdcoiefewedxq");

// list ids of all messages
var messageList = pop3.GetMessageList(Pop3ListFields.Fast);

// want to download the 10 latest messages. 
// calculate which messages to download
int downloadCount = Math.Min(10, messageList.Count);
int downloadStartIndex = messageList.Count - downloadCount;

// download message info; list details
for (int i = downloadStartIndex; i < messageList.Count; i++)
{
    int sequenceNumber = messageList[i].SequenceNumber;
    var messageInfo = pop3.GetMessageInfo(sequenceNumber, Pop3ListFields.FullHeaders);
    Console.WriteLine($"{messageInfo.ReceivedDate}\t {messageInfo.Subject}");
}
Console.WriteLine($"Downloaded {downloadCount} of {messageList.Count} messages.");