Home > Net >  How to download an email including attachments?
How to download an email including attachments?

Time:09-29

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 UserId}"; /// 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}");
  }
}

CodePudding user response:

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);
             };
  • Related