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 noreply@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 

C#
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.
10,630 questions
Outlook Management
Outlook Management
Outlook: A family of Microsoft email and calendar products.Management: The act or process of organizing, handling, directing or controlling something.
5,066 questions
0 comments No comments
{count} votes

Accepted answer
  1. Jiale Xue - MSFT 42,816 Reputation points Microsoft Vendor
    2024-07-03T07:13:38.76+00:00

    Hi @Keagan Schultz , Welcome to Microsoft Q&A,

    Make sure you use await for asynchronous calls, configure ImapClient connections and authentication correctly, improve error handling to provide more detailed output.

    using System;
    using System.IO;
    using System.Linq;
    using System.Threading;
    using System.Threading.Tasks;
    using MailKit.Net.Imap;
    using MailKit;
    using MailKit.Search;
    using MimeKit;
    using MailKit.Security;
    
    public class Program
    {
        public static async Task Main(string[] args)
        {
            string email = "your-email@example.com";
            string password = "your-password";
            string host = "outlook.live.com";
            int port = 993; // Use port 993 for IMAP over SSL
            string savePath = "your-save-path";
    
            var emailHandling = new EmailHandling(email, password);
            await emailHandling.DownloadAttachmentAsync(host, port, savePath);
        }
    }
    
    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 Task DownloadAttachmentAsync(string host, int port, string savePath)
        {
            try
            {
                using (var client = new ImapClient())
                {
                    using (var cancel = new CancellationTokenSource())
                    {
                        await client.ConnectAsync(host, port, SecureSocketOptions.SslOnConnect, cancel.Token);
    
                        // Remove unnecessary authentication mechanisms
                        client.AuthenticationMechanisms.Remove("XOAUTH2");
    
                        await client.AuthenticateAsync(email, password, cancel.Token);
    
                        var inbox = client.Inbox;
                        await inbox.OpenAsync(FolderAccess.ReadOnly, cancel.Token);
    
                        var uniqueIds = await inbox.SearchAsync(SearchQuery.NotSeen, cancel.Token);
    
                        foreach (var uniqueId in uniqueIds.OrderByDescending(id => id.Id).Take(3))
                        {
                            var message = await inbox.GetMessageAsync(uniqueId, cancel.Token);
    
                            // Check if the email is from a specific address
                            if (message.From.Mailboxes.Any(m => m.Address.Equals("noreply@dhl.com", StringComparison.OrdinalIgnoreCase)))
                            {
                                foreach (var attachment in message.Attachments)
                                {
                                    if (attachment is MimePart part && part.FileName.EndsWith(".zip", StringComparison.OrdinalIgnoreCase))
                                    {
                                        var fileName = Path.Combine(savePath, part.FileName);
    
                                        using (var stream = File.Create(fileName))
                                        {
                                            await part.Content.DecodeToAsync(stream, cancel.Token);
                                        }
    
                                        Console.WriteLine($"Attachment saved: {fileName}");
                                    }
                                }
                            }
                        }
    
                        await client.DisconnectAsync(true, cancel.Token);
                    }
                }
            }
            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);
            }
        }
    }
    

    Make sure to replace "your-email@example.com", "your-password", and "your-save-path" with actual values.

    Best Regards,

    Jiale


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment". 

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.
    0 comments No comments

0 additional answers

Sort by: Most helpful