When considering importing emails into your DEVONthink databases, the question of "automatic" email importing invariably comes up. While this isn't fully possible yet, there is a mechanism in Apple Mail that can provide some level of "automatic": Mail Rules.

Found in Apple Mail's Settings > Rules, these are a rules consisting of criteria to be matched and an associated action (similar to smart rules). As incoming emails are detected, Mail will check for matches in a rule and execute any actions you've specified in the rule.

One of the actions available is `Run AppleScript`. Selecting this option shows a dropdown with any installed Mail Rule scripts. These scripts are installed in `~/Library/Application Scripts/com.apple.mail` folder. If you write or obtain other scripts for use with Mail Rules, they can also be placed in this directory. The scripts provided by DEVONthink are:

- Mail Rule - Add attachments to DEVONthink: Adds the attachment of the message it acts on as separate documents to DEVONthink.
- Mail Rule - Add links to DEVONthink: Adds detected links in the messages as individual bookmarks in DEVONthink
- Mail Rule - Add messages to DEVONthink: Adds the messages it acts on to DEVONthink.
- Mail Rule - File messages & attachments: Adds the messages it acts on including all attachments to DEVONthink.
- Mail Rule - File messages & attachments hierarchically: Adds the messages it acts on including all attachments to DEVONthink, recreating the mailbox structure.

## Terminology

A full lesson on writing scripts for Mail Rules is beyond the scope of this help, but you can open and explore the installed scripts.

Do note there are two required handlers: `using terms from application "Mail"` and `on perform mail action with messages theMessages for rule theRule`, where `theMessages` is a variable representing the items matched by the rule. Here's a simple example:

Example:

    using terms from application "Mail"
        on perform mail action with messages theMessages for rule theRule
            tell application "Mail"
                repeat with thisMessage in theMessages
                    display alert "" & (subject of thisMessage)
                end repeat
            end tell
        end perform mail action with messages

    					end using terms from

Note: Mail Rules are controlled by Apple Mail, not DEVONthink. While they generally behave as expected, we can't control whether the rules will be triggered in Apple Mail.