使用EWS 2.2创建和修改电子邮件消息

在2014年发布的一篇关于使用Exchange Web Services (EWS)的文章中,作者介绍了如何使用EWS v2.2.0来创建和修改电子邮件。尽管从2018年7月19日起,EWS将不再接收功能更新,但服务仍将继续接收安全更新和某些非安全更新,产品的设计和功能将保持不变。本文将介绍如何使用C#.NETFramework 4.7.2、EWS 2.2、NUnit和FluentAssertions来创建和修改电子邮件消息。

电子邮件是现代通信的重要组成部分,而Exchange Web Services (EWS)提供了一种方式,允许开发者通过编程方式访问和操作Microsoft Exchange服务器上的电子邮件。EWS是一个SOAP基的Web服务,它允许开发者执行各种任务,如创建、发送、搜索和修改电子邮件。

解决方案

解决方案包含一个控制台应用程序EWSMailMessage和一个测试库EWSMailMessage.Tests

EmailMethods类中,重构了代码,以便单独更新提到的每个属性。以下是使用C#创建电子邮件消息的示例:

public class EmailMethods : IEmailMethods { public EmailMessage CreateEmailMessage(ExchangeService service, string subject, string body, string address) { if (service == null || string.IsNullOrWhiteSpace(subject) || string.IsNullOrWhiteSpace(address)) return null; var emailMessage = new EmailMessage(service) { Subject = subject, Body = body, ItemClass = "IPM.Note", From = address }; return emailMessage; } public void SetReceivedBy(EmailMessage emailMessage, string address) { if (emailMessage == null || string.IsNullOrWhiteSpace(address)) return; SetProperty(emailMessage, EmailMessageSchema.ReceivedBy, new EmailAddress(address)); } public void SetDateTimeCreated(EmailMessage emailMessage, DateTime dateTime) { if (emailMessage == null) return; SetProperty(emailMessage, ItemSchema.DateTimeCreated, dateTime); } public void SetDateTimeSent(EmailMessage emailMessage, DateTime dateTime) { if (emailMessage == null) return; SetProperty(emailMessage, ItemSchema.DateTimeSent, dateTime); } public void SetDateTimeReceived(EmailMessage emailMessage, DateTime dateTime) { if (emailMessage == null) return; SetProperty(emailMessage, ItemSchema.DateTimeReceived, dateTime); } // ...省略部分代码... }

EmailMethods类中,定义了一个私有方法SetProperty,用于设置电子邮件消息的属性。这个方法通过反射获取消息的内部属性字典,并更新指定的属性值。

private bool SetProperty(EmailMessage message, PropertyDefinition propertyDefinition, object value) { if (message == null) return false; // ...省略部分代码... dictionary[propertyDefinition] = value; return true; }

Program.cs文件中,展示了如何调用EmailMethods类的方法来创建和修改电子邮件消息。

var emailMethods = new EmailMethods(); var exchangeServer = new ExchangeService(); var emailMessage = emailMethods.CreateEmailMessage( exchangeServer, "New Subject", "Interesting text", "illya@ireznykov.com" ); emailMethods.SetReceivedBy(emailMessage, "ews@example.com"); emailMethods.SetDateTimeCreated(emailMessage, DateTime.Now.AddDays(-1)); emailMethods.SetDateTimeSent(emailMessage, DateTime.Now.AddHours(-22)); emailMethods.SetDateTimeReceived(emailMessage, DateTime.Now.AddHours(-20));

1. 文中使用的所有IP地址、服务器名称、工作站、域都是虚构的,仅作为演示使用。

沪ICP备2024098111号-1
上海秋旦网络科技中心:上海市奉贤区金大公路8218号1幢 联系电话:17898875485