Hello Roshan Ramesh,
I understand you're trying to retrieve email content exactly as it appears, including spacing, line breaks, and formatting, but you're seeing differences when using Microsoft Graph.
To solve this, you can fetch the email in MIME format and extract the original body using the MimeKit
library. This preserves the full HTML or plain text without modifying the formatting.
Below is a working example that retrieves recent emails and saves the content to .html
or .txt
files:
using Microsoft.Graph;
using Microsoft.Identity.Client;
using System.Net.Http.Headers;
using System.Security.Cryptography.X509Certificates;
using MimeKit;
using System;
using System.Linq;
class Program
{
private static readonly string tenantId = "tenantId";
private static readonly string clientId = "appId";
private static readonly string mailboxUser = "******@xxxxxxxxxxxxx.onmicrosoft.com";
private static readonly string certThumbprint = "thumbprint";
static async Task Main(string[] args)
{
var graphClient = GetGraphClient();
var messages = await graphClient.Users[mailboxUser]
.MailFolders["Inbox"].Messages
.Request().Select("id,subject").Top(5).GetAsync();
string outputDir = @"C:\MyMailBodies";
System.IO.Directory.CreateDirectory(outputDir);
foreach (var message in messages.CurrentPage)
{
var mimeStream = await graphClient.Users[mailboxUser]
.Messages[message.Id].Content.Request().GetAsync();
var mime = MimeMessage.Load(mimeStream);
string name = string.Join("_", (message.Subject ?? "No_Subject")
.Split(System.IO.Path.GetInvalidFileNameChars()));
if (!string.IsNullOrWhiteSpace(mime.HtmlBody))
System.IO.File.WriteAllText(System.IO.Path.Combine(outputDir, $"{name}.html"), mime.HtmlBody.Trim());
else if (!string.IsNullOrWhiteSpace(mime.TextBody))
System.IO.File.WriteAllText(System.IO.Path.Combine(outputDir, $"{name}.txt"), mime.TextBody.Trim());
}
}
static GraphServiceClient GetGraphClient()
{
var cert = GetCertificateByThumbprint(certThumbprint);
var app = ConfidentialClientApplicationBuilder.Create(clientId)
.WithCertificate(cert).WithTenantId(tenantId).Build();
var provider = new DelegateAuthenticationProvider(async request =>
{
var token = await app.AcquireTokenForClient(new[] { "https://graph.microsoft.com/.default" }).ExecuteAsync();
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token.AccessToken);
});
return new GraphServiceClient(provider);
}
static X509Certificate2 GetCertificateByThumbprint(string thumbprint)
{
using var store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadOnly);
return store.Certificates
.Find(X509FindType.FindByThumbprint, thumbprint, false)
.OfType<X509Certificate2>().FirstOrDefault()
?? throw new Exception("Certificate not found.");
}
}
Response:
File Explorer:
Browser response:
This ensures the body content is preserved exactly as received, without loss of spacing or structure.
Hope this helps!
If this answers your query, do click Accept Answer
and Yes
for was this answer helpful, which may help members with similar questions.
If you have any other questions or are still experiencing issues, feel free to ask in the "comments" section, and I'd be happy to help.