1

Outlook で遅延バインディングを使用して、MailItem.AddressEntry の MAPIOBJECT を取得しようとしています。

「呼び出しのターゲットによって例外がスローされました」と「指定されたキャストが無効です」という内部例外が発生し続けていますが、その理由がわかりません。Google検索などでは何も出てきません。

まず、MAPIOBJECT は非推奨であり、インテリセンスでは表示されませんが、機能することを知っています。

遅延バインディングなしで問題なくオブジェクトを取得できます。

コードは次のとおりです。

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

2 に答える 2

2

MAPI インターフェイスをそのまま使用する必要がない限り、 CodeProject でMAPIExプロジェクトを使用することを強くお勧めします。

これにより、MAPI 統合が非常にスムーズに進みました。

そして、最悪の場合、ソース コードから、このような特定の問題が明らかになる可能性があります。

于 2012-01-11T00:29:07.173 に答える
1

まず、MAPIOBJECTは非推奨ではなく、非表示になっているだけです。次に、コードはどこで実行されますか?outlook.exe以外のexeファイルである場合(つまり、コードがCOMアドインにない場合)、MAPIInitialize()を呼び出す必要があります。

于 2012-01-10T23:58:53.810 に答える