How to use a password from the keychain within an applescript running within Mail.app?

GJ. picture GJ. · May 13, 2012 · Viewed 7.9k times · Source

I'm trying to set up an applescript that performs (via python imaplib...) certain manipulations on my gmail account (which isn't configured with IMAP in Mail.app, only POP).

For that, the script needs to login using my password. If it weren't for security considerations, I could simply hardcode my password into the python script...

Is there a way that such an applescript triggered inside Mail.app (e.g. by a rule) can use my password stored inside the keychain?

Answer

regulus6633 picture regulus6633 · May 13, 2012

The following is copied out of a script in my script library...

-- If you need to use a password in a script you can use the keychain to store the password and have the script retrieve it. This way your password is protected because you don't need to store passwords in clear text in a script.

-- Create the password item - Open Keychain Access application and select the keychain in the left column. Then click File>New Password Item..., give it a name, put your account shortname in account, and enter the password. Highlight it in the password list and get information on it. Under the Attributes button enter its kind as generic key. This is chosen because there aren't many of them and the search is much faster.

-- NOTE: In 10.7 apple removed keychain scripting and thus we now use the security command line tool

getPW("name of keychain item")

on getPW(keychainItemName)
    do shell script "security 2>&1 >/dev/null find-generic-password -gl " & quoted form of keychainItemName & " | awk '{print $2}'"
    return (text 2 thru -2 of result)
end getPW