How to retrieve the exact mail content (i.e., Body) as it is.

Roshan Ramesh 5 Reputation points
2025-05-21T06:21:26.65+00:00

Hello,

I am using Microsoft Graph to retrieve emails. However, while retrieving the email, some carriage return and newline characters are removed from the body. I need to retrieve the email body exactly as it is, but for some reason, these characters are being eliminated in the process. I have attached a sample of my code. Please review it and suggest a way to retrieve the email body without modifying the content.

NuGet Package Version:-

Microsoft Graph version : 4.54.0

Microsoft.Identity.Client : 4.69.1

private void Mails()
{           
 try
 {
    Mails = Mail.GetEmails();
    Folders = Mail.GetFolders();
 }                
 catch (Exception ex)
 {
    throw new Exception (ex.Message);
 }

public static IMailFolderMessagesCollectionPage GetEmails()
{
   try
   {
      IMailFolderMessagesCollectionPage messages = MsGraph.MsGraphInfos(TenantId,     ClientIdService, new[] { EmailScope }, CertificateKey)
                    .GraphConnection().Users[MailBox].MailFolders.Inbox
                    .Messages
                    .Request()
                    .Select("id,subject,hasAttachments")
                    .Expand("attachments")
                    .GetAsync().Result;
       if (messages != null)
       {
          foreach (var message in messages)
          {
              var mimeMessage = MsGraph.MsGraphInfos(MscTenantId, ClientIdService,
                                new[] { EmailScope }, CertificateKey)
                                .GraphConnection()
                                .Users[MailBox]
                                .Messages[message.Id]
                                .Request()
                                .GetAsync().Result;
          }
       }
       return messages ?? new MailFolderMessagesCollectionPage();
    }
    catch (Exception ex)
    {
        throw new Exception($"Error in GetEmails:\r\n\r\n{ex}");
    }
            
}

public static MsGraph MsGraphInfos(string tenantId, string clientId, string[] scope, string certificatKey)
{
  return _msGraphInfos ?? (_msGraphInfos = new MsGraph(tenantId, clientId, scope,                      certificatKey));
}

public GraphServiceClient GraphConnection()
{
   if (Connection != null)
   {
      return Connection;
   }
   Connection = new GraphServiceClient("https://graph.microsoft.com/v1.0",
                new DelegateAuthenticationProvider(
                requestMessage =>
                 {
                    requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer",       Authenticate().AccessToken);
                    requestMessage.Headers.Add("Prefer", "outlook.body-content-type='text'");
                    return Task.CompletedTask;
                  }));
    return Connection;
}

private AuthenticationResult Authenticate()
{
    Scope = new[] { "https://graph.microsoft.com/.default" };
    App = ConfidentialClientApplicationBuilder.Create(ClientId)
          .WithCertificate(ReadCertificate(CertificatKey))
          .WithTenantId(TenantId)
          .Build();
    if (App != null)
    {
        Authentication = App.AcquireTokenForClient(Scope).ExecuteAsync().Result;
    }
   return Authentication;
}

private X509Certificate2 ReadCertificate(string thumbprint)
{
  X509Certificate2 cert;
  using (X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine))
  {
    store.Open(OpenFlags.ReadOnly);
    X509Certificate2Collection certCollection = store.Certificates;
    X509Certificate2Collection currentCerts = certCollection.Find(X509FindType.FindByTimeValid, DateTime.Now.ToUniversalTime(), false);
    X509Certificate2Collection signingCert = currentCerts.Find(X509FindType.FindByThumbprint, thumbprint, false);
    cert = signingCert.OfType<X509Certificate2>().OrderByDescending(c => c.NotBefore)
           .FirstOrDefault();
  }
    return cert;
}
Microsoft Security | Microsoft Entra | Microsoft Entra ID

2 answers

Sort by: Oldest
  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.

    4 deleted comments

    Comments have been turned off. Learn more

  2. Roshan Ramesh 5 Reputation points
    2025-05-27T05:47:08.19+00:00

    Hello @Sridevi Machavarapu

    As per my requirement, i have used the regex in a customized way, which solved the issue.
    Hope this helps others too.

    I have attached the code snippet below.

                string pattern = @"(\r\n){2,}";
                string output = Regex.Replace(content, pattern, match =>
                {
                    int count = match.Length / 2; 
                    int startIndex = match.Index;
                    int endIndex = match.Index + match.Length;
                    bool precededBySlashParen = startIndex >= 2 && content.Substring(startIndex - 2, 2) == "/)";
                    bool followedByKeyword = false;
                    foreach (Match isMatch in Regex.Matches(content, $@"(?<=\r\n)({keywordsPattern})"))
                    {
                        if (isMatch.Index == endIndex)
                        {
                            followedByKeyword = true;
                            break;
                        }
                        else if (isMatch.Index > endIndex)
                        {
                            var intermediate = content.Substring(endIndex, isMatch.Index - endIndex);
                            if (string.IsNullOrWhiteSpace(intermediate))
                            {
                                followedByKeyword = true;
                                break;
                            }
                        }
                    }
                    string result = "";
                    for (int i = 1; i <= count; i++)
                    {
                        if (precededBySlashParen && i == 1)
                        {
                            result += "\r\n";
                        }
                        else if (followedByKeyword && i == count)
                        {
                            result += "\r\n";
                        }
                        else
                        {
                            result += "\r\n ";
                        }
                    }
                    return result;
                });
    

    Was this answer helpful?

    1 person found this answer helpful.
    0 comments No comments

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.