Jessica
Jessica

Reputation: 2035

Getting default email address on Mac OS X

I'm trying to get the current user's email (if any) so that I can create a customized "contact us" message.

The code is in C. I've tried with AddressBook.framework but I can't find a way to get the email address.

Anyone knows how to get the email address?
Thank you.

Upvotes: 2

Views: 710

Answers (1)

Hagelin
Hagelin

Reputation: 16658

Using Address Book C Framework:

#include <AddressBook/AddressBook.h>

To get all email addresses:

ABAddressBookRef addressbook = ABGetSharedAddressBook();
ABPersonRef user = ABGetMe(addressbook);
ABMultiValueRef emails = ABRecordCopyValue(user, kABEmailProperty);

if(emails)
{
    if(ABMultiValueCount(emails) != 0)
    {
        for(int i=0;i<ABMultiValueCount(emails);i++)
        {
            CFStringRef email = ABMultiValueCopyValueAtIndex(emails, i);

            // Do something with current email string

            CFRelease(email);
        }
    }

    CFRelease(emails);
}

Or, to check for the email address marked as the primary one:

ABAddressBookRef addressbook = ABGetSharedAddressBook();
ABPersonRef user = ABGetMe(addressbook);
ABMultiValueRef emails = ABRecordCopyValue(user, kABEmailProperty);

if(emails)
{
    if(ABMultiValueCount(emails) != 0)
    {

        CFStringRef primaryIdentifier = ABMultiValueCopyPrimaryIdentifier(emails);

        for(int i=0;i<ABMultiValueCount(emails);i++)
        {
            CFStringRef currentIdentifier = ABMultiValueCopyIdentifierAtIndex(emails, i);

            if(currentIdentifier==primaryIdentifier)
            {
                CFStringRef email = ABMultiValueCopyValueAtIndex(emails, i);

                // Do something with primary email string

                CFRelease(email);
            }

            CFRelease(currentIdentifier);
        }

        CFRelease(primaryIdentifier);
    }

    CFRelease(emails);
}

Not all potential errors are handled in the above code, e.g. ABGetMe() could return NULL if the user hasn’t created an address book entry for herself.

Upvotes: 4

Related Questions