Exchange (EWS) with NTML-Authentication

What is Exchange

Microsoft Exchange Server is a groupware and email transport server software developed by Microsoft. It is used for the central storage and management of emails, appointments, contacts, tasks and other items for multiple users, thereby enabling collaboration within a work group or company.

What is the task

The task was to check whether it was possible to access the customer’s Exchange using Windows authentication and to check whether calendar entries can be read and appointments can be created.

NuGet Dependencies

https://www.nuget.org/packages/Microsoft.Exchange.WebServices/2.2.0?_src=template

Code

// Create the ExchangeService instance
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2013_SP1);

// Set credentials for NTLM authentication
service.Credentials = new NetworkCredential(username, password, domain);

// Set the Exchange server URL
service.Url = new Uri(url);

// Configure NTLM authentication explicitly
service.PreAuthenticate = true;
service.UseDefaultCredentials = false;
service.TraceEnabled = true;

try
{
    // Get calendar folder
    Folder calendar = Folder.Bind(service, WellKnownFolderName.Calendar);
    Console.WriteLine($"Calendar: {calendar.DisplayName}");

    // Find appointments in the next 7 days
    DateTime startDate = DateTime.Now;
    DateTime endDate = startDate.AddDays(7);

    CalendarView calView = new CalendarView(startDate, endDate);
    FindItemsResults<Appointment> appointments = service.FindAppointments(
        WellKnownFolderName.Calendar, calView);

    // List appointments
    Console.WriteLine($"\nUpcoming appointments ({appointments.Items.Count}):");
    foreach (Appointment appt in appointments)
    {
        Console.WriteLine($"- {appt.Subject}");
        Console.WriteLine($"  Start: {appt.Start}");
        Console.WriteLine($"  End: {appt.End}");
        Console.WriteLine($"  Location: {appt.Location}\n");
    }

    // Create a new appointment
    Appointment newAppt = new Appointment(service);
    newAppt.Subject = "Team Meeting";
    newAppt.Body = "Discuss project status";
    newAppt.Start = DateTime.Now.AddDays(1).Date.AddHours(10);
    newAppt.End = newAppt.Start.AddHours(1);
    newAppt.Location = "Conference Room A";
    newAppt.Save(SendInvitationsMode.SendToNone);

    Console.WriteLine("Appointment created successfully!");
}
catch (Exception ex)
{
    Console.WriteLine($"Error: {ex.Message}");
}

Example project

The sample project is located in Gitlab: https://github.com/tobiasoehler/Exchange-Web-Service-with-NTLM


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *