Kruthika
Kruthika

Reputation: 21

Retrieving message body using Emailmessage class

I have to retrieve the body of an email sent and store it in a shared folder. I have the following code sample to retrieve attachments from the email and store it.

EmailMessage message = EmailMessage.Bind(service, new ItemId(item.Id.ToString()),
new PropertySet(BasePropertySet.IdOnly, ItemSchema.Attachments));

foreach (Attachment attachment in message.Attachments)
{

    if (attachment is FileAttachment)
    {
        FileAttachment fileAttachment = attachment as FileAttachment;

        // Load attachment contents into a file.
        fileAttachment.Load("C:\\CodeCopy\\Email\\temp\\" + fileAttachment.Name);

Similarly if I want to use EmailMessage.body property how do I use it. I am a beginner, so please give a detailed answer.

Upvotes: 2

Views: 4531

Answers (1)

Frédéric Hamidi
Frédéric Hamidi

Reputation: 263157

You can use the EmailMessage.Body property to get an object representing the body of your message, then call its ToString() method to get the body contents as a string, and write that string to a file:

using System.IO;
using System.Text;
using Microsoft.Exchange.WebServices.Data;

EmailMessage message = EmailMessage.Bind(service, new ItemId(item.Id.ToString()),
    new PropertySet(BasePropertySet.IdOnly, ItemSchema.Attachments));
using (StreamWriter writer = new StreamWriter(String.Format(
       CultureInfo.InvariantCulture, @"C:\CodeCopy\Email\temp\{0}.body.txt",
       item.Id.ToString().Replace('\\', '_')))) {
    writer.Write(message.Body.ToString());
}

Upvotes: 1

Related Questions