在Mac OS X上获取默认电子邮件地址

时间:2011-05-12 13:02:36

标签: c macos email abaddressbook

我正在尝试获取当前用户的电子邮件(如果有),以便我可以创建自定义的“与我们联系”消息。

代码在C中。我尝试过使用AddressBook.framework,但我找不到获取电子邮件地址的方法。

任何人都知道如何获取电子邮件地址? 谢谢。

1 个答案:

答案 0 :(得分:4)

使用Address Book C Framework

#include <AddressBook/AddressBook.h>

获取所有电子邮件地址:

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

或者,要检查标记为主要电子邮件地址的电子邮件地址:

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

并非所有潜在错误都在上述代码中处理,例如如果用户尚未为自己创建地址簿条目,则ABGetMe()可以返回NULL