Categories
Uncategorized

Sending and Parsing Emails with Microsoft Exchange Web Service Managed API SDK


Using the Microsoft Exchange Web Service Managed API SDK, you can easily perform various email-related tasks. Here’s a quick guide on how to send emails, reply to them, and parse email content using C#.

Setting Up

  1. Add Reference: Download and add the Exchange Web Service SDK.
  2. Using Directive:
   using Microsoft.Exchange.WebServices.Data;

Initialize the Exchange Service

Create and configure the Exchange service object:

ExchangeService exchangeService = new ExchangeService();
try
{
    exchangeService.AutodiscoverUrl("[email protected]");
}
catch (AutodiscoverLocalException ex)
{
    exchangeService.Url = new Uri("https://mail.sampleExchange.com/ews/exchange.asmx");
    Console.WriteLine(ex.Message);
}
exchangeService.Credentials = new WebCredentials("userName", "Password", "Domain");
// OR
exchangeService.Credentials = new NetworkCredential("userName", "Password", "Domain");

Sending Emails

Send an email with a few lines of code:

EmailMessage message = new EmailMessage(exchangeService);
message.Subject = "This is the subject";
message.Body = "This is the body";
message.ToRecipients.Add("[email protected]");
message.SendAndSaveCopy();

Replying to Emails

To reply to an email:

public void ReplyToMessage(EmailMessage messageToReply, string replyBody)
{
    messageToReply.Reply(replyBody, true);
    // Or
    ResponseMessage responseMessage = messageToReply.CreateReply(true);
    responseMessage.BodyPrefix = replyBody;
    responseMessage.CcRecipients.Add("[email protected]");
    responseMessage.SendAndSaveCopy();
}

Creating Appointments

To create recurring appointments:

public void CreateRecurringAppointment()
{
    Appointment appointment = new Appointment(exchangeService)
    {
        Subject = "Sample subject",
        Body = "Body of the appointment",
        Start = new DateTime(2022, 1, 1, 18, 0, 0),
        End = Start.AddHours(2)
    };
    appointment.Recurrence = new Recurrence.WeeklyPattern(new DateTime(2022, 1, 1), 2, DayOfTheWeek.Monday);
    appointment.Save();
}

Parsing Emails

To parse and iterate through emails:

public void ParseEmails()
{
    FindItemsResults<Item> findResults = exchangeService.FindItems(WellKnownFolderName.Inbox, new ItemView(int.MaxValue));
    foreach (var item in findResults.Items)
    {
        EmailMessage message = EmailMessage.Bind(exchangeService, item.Id);
        string subject = message.Subject;
        string body = message.Body.Text;
        if (message.HasAttachments)
        {
            // Handle attachments
        }
    }
}

This guide highlights key functionalities provided by the Exchange Web Service Managed API SDK for handling emails efficiently.