Here is a number of examples showing you how to find specific parts of an email message.
First, here is an example of how to find a text/plain MessagePart.
/// <summary>
/// Example showing:
/// - how to a find plain text version in a Message
/// - how to save MessageParts to file
/// </summary>
/// <param name="message">The message to examine for plain text</param>
public static void FindPlainTextInMessage(Message message)
{
MessagePart plainText = message.FindFirstPlainTextVersion();
if(plainText != null)
{
// Save the plain text to a file, database or anything you like
plainText.Save(new FileInfo("plainText.txt"));
}
}
If you want to find a HTML part instead, it is nearly the same, we just call a different method.
/// <summary>
/// Example showing:
/// - how to find a html version in a Message
/// - how to save MessageParts to file
/// </summary>
/// <param name="message">The message to examine for html</param>
public static void FindHtmlInMessage(Message message)
{
MessagePart html = message.FindFirstHtmlVersion();
if (html != null)
{
// Save the plain text to a file, database or anything you like
html.Save(new FileInfo("html.txt"));
}
}
The two examples above used some convenience methods to retrieve text/plain and text/html parts of an email.
Sometimes you want to fetch some part which does not have such a method. There is a method as argument the type
of the MessagePart you want returned. Here is an example showing you how to find a text/xml part.
/// <summary>
/// Example showing:
/// - how to find a MessagePart with a specified MediaType
/// - how to get the body of a MessagePart as a string
/// </summary>
/// <param name="message">The message to examine for xml</param>
public static void FindXmlInMessage(Message message)
{
MessagePart xml = message.FindFirstMessagePartWithMediaType("text/xml");
if (xml != null)
{
// Get out the XML string from the email
string xmlString = xml.GetBodyAsText();
System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
// Load in the XML read from the email
doc.LoadXml(xmlString);
// Save the xml to the filesystem
doc.Save("test.xml");
}
}
All these three methods will return you the first MessagePart of an email that has the correct type. If you want to get all
MessagePart with one type. There are methods that will let you get all these parts as well.