How to Download a Mail | Graph API | C#

Th3TV 46 Reputation points
2022-09-27T12:58:49.957+00:00

Hello, I have a problem.

I have a fully working programm, but I want to add the possibility to Download the E-Mail inclusive the Attachtments. (So the whole package)

Does anyone have a Code-Example for me how i can implement this?

My Code right now:

private static async Task CallMSGraphUsingGraphSDKEmail(IConfidentialClientApplication app, string[] scopes)  
    {       
      // Prepare an authenticated MS Graph SDK client  
      GraphServiceClient graphServiceClient = GetAuthenticatedGraphClient(app, scopes);  
  
      string userID = "{Your ObjectId}"; /// ID (aus Azure Portal) des User von dem wir die Emails abrufen wollen  
  
      try  
      {  
        int anzahl;  
        Console.WriteLine("Choose the number of mails to display: ");  
        anzahl = Convert.ToInt32(Console.ReadLine());  
        /// zum User Wechseln von dem wir die Email wollen          
        var userReqHelper = graphServiceClient.Users[userID];  
  
  
  
          
        // Only messages from Inbox folder  
        var userMessages = await userReqHelper  
            .MailFolders["Inbox"]  
            .Messages  
            .Request().Expand("attachments").Top(anzahl).OrderBy("ReceivedDateTime DESC").GetAsync();  
  
        Console.WriteLine($"Found {userMessages.Count()} messages in infolder of " + userID);  
  
  
  
        foreach (var curMessage in userMessages)  
        {  
          Console.WriteLine($"curMessage ID: {curMessage.Id}");  
          Console.WriteLine($"curMessage From: {curMessage.From.EmailAddress.Address}");  
          Console.WriteLine($"curMessage Sender: {curMessage.Sender.EmailAddress.Address}");  
          Console.WriteLine($"curMessage Sub: {curMessage.Subject}");  
          Console.WriteLine($"curmessage Attachments: {curMessage.Attachments?.Count ?? 0}");  
          Console.WriteLine($"curMessage Recieved: {curMessage.ReceivedDateTime?.ToLocalTime().ToString()}\n");  
        }  
  
        //Console.WriteLine($"Found {users.Count()} users in the tenant");  
      }  
      catch (ServiceException e)  
      {  
        Console.WriteLine("We could not retrieve the emails for user: " + userID + $" Details: {e}");  
      }  
    }  
Microsoft Graph
Microsoft Graph
A Microsoft programmability model that exposes REST APIs and client libraries to access data on Microsoft 365 services.
10,580 questions
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,236 questions
0 comments No comments
{count} votes

Accepted answer
  1. Glen Scales 4,431 Reputation points
    2022-09-28T00:26:42.413+00:00

    The easiest way of downloading a message is to request its mimeContent https://learn.microsoft.com/en-us/graph/outlook-get-mime-message which will allow you to create an eml file (that would contain all attachments) you can then open in Outlook or most other mail clients eg to export the last email in the Inbox with the Graph SDK

                var messages = graphServiceClient.Me.MailFolders["inbox"].Messages.Request().Top(1).GetAsync().GetAwaiter().GetResult();  
                var mimeContentStream = graphServiceClient.Me.Messages[messages[0].Id].Content.Request().GetAsync().GetAwaiter().GetResult();  
                using (var fileStream = System.IO.File.Create("C:\\temp\\lastemail.eml"))  
                {  
                    mimeContentStream.Seek(0, SeekOrigin.Begin);  
                    mimeContentStream.CopyTo(fileStream);  
                };  
    
    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful