Applescript to send email messages to the persons with specific in interest and with at least one email address

I am trying to write a script that filters the persons in the Contacts application whose note include a specific keyword and sending those who has at least one e-mail address an e-mail. I have written the following code but something seems to be wrong. I couldn't figure out especially how to make a null check for e-mails.

property mailSubject : "A bulk message"
property mailBody : "Hi %NAME%"
property keyword : "topic"

tell application "Contacts"
    set theRecipients to every person whose ((note contains keyword))
end tell

repeat with i from 1 to number of items in theRecipients
    set theContact to item i of theRecipients
    set theName to name of theContact
    set theEmail to email of theContact
    if (theEmail is not equal to "") then
        set theBody to replaceName(mailBody, theName)
        tell application "Mail"
            set theOutMessage to make new outgoing message with properties {visible:true}
            tell theOutMessage
                make new to recipient at end of to recipients with properties {address:theEmail}
                set sender to "o****.g****@gmail.com>"
                set subject to mailSubject
                set content to theBody
            end tell
        end tell
    end if
end repeat

The execution of this script returns following error at the line set theEmail to email of theContact:

Contacts got an error: Can’t make |email| of person id "2827E13D-907A-41C5-A649-2174D1F61093:ABPerson" into type specifier.

Any ideas?

Önder.


You did not include the replaceName(mailBody, theName) handler, so I could not test the full script, however to fix the current error you need to modify the existing code.

Change:

repeat with i from 1 to number of items in theRecipients
    set theContact to item i of theRecipients
    set theName to name of theContact
    set theEmail to email of theContact

To:

repeat with i from 1 to number of items in theRecipients
    set theContact to item i of theRecipients
    tell application "Contacts"
        set theName to name of theContact
        set theEmail to value of email of theContact
    end tell