首页 > 解决方案 > 使用 EWS 托管 API 将 .msg 文件上传到 Exchange Server

问题描述

我发现了几个从 MS Exchange 服务器下载电子邮件并将其保存到文件的示例。

我需要相反的。从“.msg”文件中,我需要在服务器的特定文件夹中创建一封电子邮件。

我找到有关如何使用带有 XML 正文的 EWS 请求的文档。但是,我所有的系统都依赖于EWS Managed API,我找不到等效的方法来执行此操作。

我怎样才能执行我需要的操作?我可以通过Microsoft.Exchange.WebServices.Data.ExchangeService对象传递自定义请求吗?

标签: c#vb.netexchange-serverexchangewebservicesmsg

解决方案


Microsoft 文档链接在这里

您可以使用UploadItems EWS 操作将项目作为数据流上传。项目的这种数据流表示必须来自 ExportItems 操作调用的结果。由于 EWS 托管 API 不实现 UploadItems 操作,因此如果您使用 EWS 托管 API,则需要编写一个例程来发送 Web 请求。

您可以将 .msg 文件转换为 .eml 并使用以下代码添加您的消息。

private static void UploadMIMEEmail(ExchangeService service)
{
    EmailMessage email = new EmailMessage(service);

    string emlFileName = @"C:\import\email.eml";
    using (FileStream fs = new FileStream(emlFileName, FileMode.Open, FileAccess.Read))
    {
        byte[] bytes = new byte[fs.Length];
        int numBytesToRead = (int)fs.Length;
        int numBytesRead = 0;
        while (numBytesToRead > 0)
        {
            int n = fs.Read(bytes, numBytesRead, numBytesToRead);
            if (n == 0)
                break;
            numBytesRead += n;
            numBytesToRead -= n;
        }
        // Set the contents of the .eml file to the MimeContent property.
        email.MimeContent = new MimeContent("UTF-8", bytes);
    }

    // Indicate that this email is not a draft. Otherwise, the email will appear as a 
    // draft to clients.
    ExtendedPropertyDefinition PR_MESSAGE_FLAGS_msgflag_read = new ExtendedPropertyDefinition(3591, MapiPropertyType.Integer);
    email.SetExtendedProperty(PR_MESSAGE_FLAGS_msgflag_read, 1);
    // This results in a CreateItem call to EWS. The email will be saved in the Inbox folder.
    email.Save(WellKnownFolderName.Inbox);
}

推荐阅读