Home > Blockchain >  Getting the sender from Outlook.MailItem returns null
Getting the sender from Outlook.MailItem returns null

Time:03-29

I am trying to get the sender (From) of an Outlook.MailItem without success. It returns null.

I have tried below.

Attempt 1:

string from = omi.SenderEmailAddress;

Attempt 2:

var exch = omi.Sender.GetExchangeUser(); // it returns null
if (exch != null)
{
    string from = exch.PrimarySmtpAddress;
}

Also I have checked omi.SenderEmailType to see what type is, and it returns null.

Note: omi is an Outlook.MailItem object.

CodePudding user response:

Keep in mind that the sender related properties are only populated on the received or already sent messages. If you are accessing these properties on a message being submitted, they won't be present until the message is sent and moved to the Sent Items folder.

CodePudding user response:

You can check out the SendUsingAccount property. If it is not set then you can use the Namespace.CurrentUser property which returns the display name of the currently logged-on user as a Recipient object.

CodePudding user response:

Assuming you have an Outlook.MailItem that is not null, you should be able to follow this process to retrieve the sender's email address, adapted from the Microsoft Documentation.

string PR_SMTP_ADDRESS = @"http://schemas.microsoft.com/mapi/proptag/0x39FE001E";

if (omi == null)
{
    throw new ArgumentNullException();
}
if (omi.SenderEmailType == "EX")
{
    Outlook.AddressEntry sender = omi.Sender;
    
    if (sender != null)
    {
        // Now we have an AddressEntry representing the Sender
        if (sender.AddressEntryUserType == Outlook.OlAddressEntryUserType.olExchangeUserAddressEntry ||
            sender.AddressEntryUserType == Outlook.OlAddressEntryUserType.olExchangeRemoteUserAddressEntry)
        {
            // Use the ExchangeUser object PrimarySMTPAddress
            Outlook.ExchangeUser exchUser = sender.GetExchangeUser();
            
            if (exchUser != null)
            {
                return exchUser.PrimarySmtpAddress;
            }
            else
            {
                return null;
            }
        }
        else
        {
            return sender.PropertyAccessor.GetProperty(PR_SMTP_ADDRESS) as string;
        }
    }
    else
    {
        return null;
    }
}
else
{
    return omi.SenderEmailAddress;
}
  • Related