Read Emails From Gmail And Outlook In C#

This article will help you to read an email from Gmail or outlook using EAGetMail. Also, it helps to save the attachment which is attached within that email.

Step 1: Install NuGet package EAGetMail V4.6.5.1 from tools > NuGet Package Manager > Manage Nuget Packages for Solution.

Step 2: Now Connect the  IMAP4 server using the following code. Server imap.gmail.com is used to read Gmail inbox. If you want to read the outlook inbox then you can use imap.outlook.com.

MailServer oServer = new MailServer("imap.gmail.com", "Gmail Id", "Gmail password", ServerProtocol.Imap4);
MailClient oClient = new MailClient("TryIt");

Step 3: Enable SSL connection for your server.

oServer.SSLConnection = true;
oServer.Port = 993;

If your server doesn’t allow an SSL connection then you can use the following code.

oServer.SSLConnection = false;
oServer.Port = 143;

Step 4: If you want to search email with unread flag, you have to set EAGetMail.GetMailInfosOptionType.NewOnly. Default will be EAGetMail.GetMailInfosOptionType.All.

oClient.GetMailInfosParam.GetMailInfosOptions = GetMailInfosOptionType.NewOnly;

Step 5: Connect the Mail server and read emails from the mailbox.

oClient.Connect(oServer);
MailInfo[] infos = oClient.GetMailInfos();

Step 6: Now you can read email content using mail object.

for (int i = infos.Length - 1; i > 0; i--)
{
    MailInfo info = infos[i];
    Mail oMail = oClient.GetMail(info);
}

Step 7: Below code is used to save attachments within your project.

var count = oMail.Attachments.ToList().Count;
for (int j = 0; j < count; j++)
{
    oMail.Attachments[j].SaveAs(Server.MapPath("~/Inbox") + "\\" + oMail.Attachments[j].Name, true); // true for overWrite file
}

 

10 Comments

  1. ajay kumar

    Thanks RUPAL RIBADIYA For Sharing It, It’s Working Fine

    1
    0
    Reply
  2. Tanju

    hi,
    the code worked…
    thanks…

    1
    0
    Reply
  3. henry

    hi ,
    apps can t writeline mail infos ,
    NOT WORKING >> no ref oMail and run infinite loop … help :/

    0
    0
    Reply
    1. Can you please tell me the exact issue or can you show me your code?

      0
      0
      Reply
  4. Dmitriy

    Hi Rupal!
    I have installed the package, recieved gmail ID using OAuth 2.0 Client IDs, but i recieve error “EAGetMail.MailServerException: A0002 NO [AUTHENTICATIONFAILED] Invalid credentials (Failure)” on line oClient.Connect(oServer); My IMAP is Enable and I set on unsafe apps allowed. What`s wrong? Can you help me? Thanks!

    0
    0
    Reply
    1. I think you misread this document. Here you don’t need OAuth for authentication. In step 2 simply you need to replace your Gmail ID and Password while connecting Mail Server.
      Thanks

      0
      0
      Reply
  5. Ashish

    great job!!!

    0
    0
    Reply

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories