使用后期绑定从MailItem.AddressEntry获取MAPIOBJECT时,指定的强制转换无效

本文关键字:无效 转换 MAPIOBJECT 绑定 获取 AddressEntry MailItem | 更新日期: 2023-09-27 18:19:53

我正在尝试使用Outlook的Late Binding获取MailItem.AddressEntry的MAPIOBJECT。

我不断收到"调用的目标抛出了异常"answers"指定的强制转换无效"的内部异常,我不知道为什么。在谷歌搜索等方面没有出现任何内容。

首先,我知道MAPIOBJECT是不推荐使用的,通过intellisense看不到,但它是有效的。

如果不延迟绑定,我可以毫无问题地获得对象。

这是代码:

/// <summary>
/// Gets the MAPI Object from the AddressEntry of the new recipient.
/// </summary>
/// <param name="senderName">The name of the sender to add to the recipients.</param>
/// <param name="outlookApplication">The Outlook Application instance.</param>
private static object GetMapiObject(string senderName, object outlookApplication)
{
    var mailItem = InvokeMember("CreateItem", outlookApplication, new object[] { 0 });
    var recipients = GetProperty("Recipients", mailItem);
    var recipient = InvokeMember("Add", recipients, new object[] { senderName });
    InvokeMember("Resolve", recipient, new object[] {});
    var addressEntry = GetProperty("AddressEntry", recipient);
    var mapiObject = GetProperty("MAPIOBJECT", addressEntry); // Error occurs here.
    return mapiObject;
}
/// <summary>
/// Gets a property of an instance by its name
/// </summary>
/// <param name="propertyName">The property name to get.</param>
/// <param name="instance">The object to get the property from.</param>
/// <returns>The resulting object.</returns>
private static object GetProperty(string propertyName, object instance)
{
    Type type = instance.GetType();
    return type.InvokeMember(propertyName, BindingFlags.GetProperty, null, instance, new object[] { });
}
/// <summary>
/// Invoke an object by its method and type - takes parameters.
/// </summary>
/// <param name="method">The method to invoke.</param>
/// <param name="instance">The object that contains the method to invoke.</param>
/// <param name="parameters">The parameters to pass to the method.</param>
/// <returns>The resulting object.</returns>
private static object InvokeMember(string method, object instance, object[] parameters)
{
    try
    {
        Type type = instance.GetType();
        return type.InvokeMember(method, BindingFlags.InvokeMethod, null, instance, parameters);
    }
    catch (Exception ex)
    {
        switch (method)
        {
           case "SaveAsFile":
                throw new System.IO.IOException("Error occurred during '"SaveAsFile'" for attachments. Attachment filename may be too long. ", ex);                                                
            default:
                throw new TargetInvocationException("Handled error at Invoke Member. Method Name: " + method, ex);
        }
    }
}

使用后期绑定从MailItem.AddressEntry获取MAPIOBJECT时,指定的强制转换无效

除非您必须使用MAPI接口,否则我强烈建议您在CodeProject中使用MAPIEx项目。

这使得我们的MAPI集成进行得非常顺利。

而且,在最坏的情况下,源代码可以揭示特定的问题,比如这个。

首先,MAPIOBJECT并没有被弃用,只是不可见。第二,你的代码在哪里运行?如果它是outlook.exe以外的exe(即您的代码不在COM加载项中),则必须调用MAPIInitialize()。