This article illustrates how to get message contents such as from address, send to address, subject, date and the body of the message by using Spire.Email.
Code snippets of how to extract the message contents:
Step 1: Load the mail message.
MailMessage mail = MailMessage.Load("Sample.msg");
Step 2: Create a new instance of StringBuilder.
StringBuilder sb = new StringBuilder();
Step 3: Get the message contents as we want.
//get the From address sb.AppendLine("From:"); sb.AppendLine(mail.From.Address); //get the To address sb.AppendLine("To:"); foreach (MailAddress toAddress in mail.To) { sb.AppendLine(toAddress.Address); } //get the date sb.AppendLine("Date:"); sb.AppendLine(mail.Date.ToString()); //get the subject sb.AppendLine("Subject:"); sb.AppendLine(mail.Subject); //get the BodyText sb.AppendLine("Message contents"); sb.AppendLine(mail.BodyText); //get the BodyHtml sb.AppendLine("BodyHtml"); sb.AppendLine(mail.BodyHtml);
Step 4: Write all contents in .txt
File.WriteAllText("ExtractMessageContents.txt", sb.ToString());
The extracted message contents in .txt file format.
Full codes:
[C#]
using Spire.Email; using System.IO; using System.Text; namespace ExtractMessage { class Program { static void Main(string[] args) { MailMessage mail = MailMessage.Load("Sample.msg"); StringBuilder sb = new StringBuilder(); sb.AppendLine("From:"); sb.AppendLine(mail.From.Address); sb.AppendLine("To:"); foreach (MailAddress toAddress in mail.To) { sb.AppendLine(toAddress.Address); } sb.AppendLine("Date:"); sb.AppendLine(mail.Date.ToString()); sb.AppendLine("Subject:"); sb.AppendLine(mail.Subject); sb.AppendLine("Message contents"); sb.AppendLine(mail.BodyText); sb.AppendLine("BodyHtml"); sb.AppendLine(mail.BodyHtml); File.WriteAllText("ExtractMessageContents.txt", sb.ToString()); } } }
[VB.NET]
Dim mail As MailMessage = MailMessage.Load("Sample.msg") Dim sb As New StringBuilder() sb.AppendLine("From:") sb.AppendLine(mail.From.Address) sb.AppendLine("To:") For Each toAddress As MailAddress In mail.[To] sb.AppendLine(toAddress.Address) Next sb.AppendLine("Date:") sb.AppendLine(mail.[Date].ToString()) sb.AppendLine("Subject:") sb.AppendLine(mail.Subject) sb.AppendLine("Message contents") sb.AppendLine(mail.BodyText) sb.AppendLine("BodyHtml") sb.AppendLine(mail.BodyHtml) File.WriteAllText("ExtractMessageContents.txt", sb.ToString())