Reading Emails from outlook in C#

Keagan S 20 Reputation points
2024-07-02T06:46:39.94+00:00

Hi, hope you are well.
Junior dev here. I am trying to figure out how to get my C# application to read emails from a certain address, if it matches then check if it has an attachment. IF it does extract the attachment and store it locally. I can not get past the logging in of my account.
//Code in my Program class
string email = "xxx";
string password = "xxx";
string host = "outlook.live.com";
int port = 995;
var emailHandling = new EmailHandling(email, password);
emailHandling.DownloadAttachment(host, port, savePath);

//Class for the handling
public class EmailHandling {

private readonly string email;

private readonly string password;

public EmailHandling(string email, string password) {

  this.email = email;

  this.password = password;  }

public async void DownloadAttachment(string host, int port, string savePath) {

  try  {

    using (var client = new ImapClient()) // creating an instance of ImapClient  {

      using (var cancel = new CancellationTokenSource())  {

        client.Connect(host, port, SecureSocketOptions.Auto); // Estabishing a connection 

        client.AuthenticationMechanisms.Remove("XOAUTH2");

        client.AuthenticationMechanisms.Remove("PLAIN");

        client.AuthenticationMechanisms.Remove("LOGIN");

        client.Authenticate(email, password, cancel.Token); // Supplying the auth with credentials

        var inbox = client.Inbox; // Opening the Inbox folder only

        inbox.Open(MailKit.FolderAccess.ReadOnly); // Permission to readonly 

        var uniqueIds = inbox.Search(SearchQuery.New)  // Search for the most recent emails

                        .OrderByDescending(x => x.Id)

                        .Take(3);

        foreach (var uniqueId in uniqueIds)  {

          var message = inbox.GetMessage(uniqueId);

          // Check if the email is from ******@dhl.com

          if (message.From.Mailboxes.Any(m => m.Address.Equals("xxx", StringComparison.OrdinalIgnoreCase)))  {

            foreach (var attachment in message.Attachments) // Looping through the attachments  {

              if (attachment is MimePart part && part.FileName.EndsWith(".zip", StringComparison.OrdinalIgnoreCase)) // Mimepart is how the body content have to check that for the attachment {

                var fileName = Path.Combine(savePath, part.FileName);

                using (var stream = File.Create(fileName))  {

                  part.Content.DecodeTo(stream); }

                Console.WriteLine($"Attachment saved: {fileName}");  } } } }

        client.Disconnect(true);  }}}

  catch (AuthenticationException ex)  {

    Console.WriteLine("Authentication failed.");

    Console.WriteLine(ex.Message);  }

  catch (Exception ex) {

    Console.WriteLine("An error occurred while downloading the attachment.");

    Console.WriteLine(ex.Message);  } } } }  
```If this helps I am trying to build it in .net 6 core 

Outlook | Windows | Classic Outlook for Windows | For business
Developer technologies | C#
Developer technologies | C#

An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.

0 comments No comments

1 answer

Sort by: Most helpful
  1. Deleted

    This answer has been deleted due to a violation of our Code of Conduct. The answer was manually reported or identified through automated detection before action was taken. Please refer to our Code of Conduct for more information.

    2 deleted comments

    Comments have been turned off. Learn more

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.