简体   繁体   中英

Upload .msg file to Exchange Server using EWS Managed API

I have found several examples of downloading an email message from a MS Exchange server and saving it to a file.

I need the opposite. From a ".msg" file I need to create an email message inside a specific folder of the server.

I found this documentation on how to do it using an EWS request with a XML body. However, all my system relies on EWS Managed API , and I couldn't find an equivalent method to perform this operation.

How could I perform the operation I need? Could I pass a custom request through a Microsoft.Exchange.WebServices.Data.ExchangeService Object?

Microsoft documentation link here .

You can use the UploadItems EWS operation to upload an item as a data stream. This data stream representation of an item has to come from the results of an ExportItems operation call . Because the EWS Managed API does not implement the UploadItems operation, if you use the EWS Managed API, you'll need to write a routine to send the web requests.

You may be able to convert your .msg file to an .eml and use the following code to add your message.

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM