I am not a developer (and my scripts are evidence of that), but I do like to tinker with scripting to make my life easier. Script: FreeBusy Export Description: I get many inquiries from clients who don’t have access to the Exchange server’s free/busy date. I wanted to simplify the process of responding to their […]

(*
Script Name: FreeBusy Export
Version:         0.1

Hosted on: https://github.com/yanfosec/applescripts/blob/master/FreeBusy%20Export.applescript

Description: This script makes it easy to respond to requests for available meeting times, for those who are not on the same Exchange server and can't lookup availability through the server.  
        The scripts prompts for start and end date / time, and returns a pre-formatted message with time-slots showing availability.

Author:        Yan Kravchenko (@yanfosec) yan.kravchenko@gmail.com
       
To Do:        
        * Add better error handling, didn't really do much in that regard
        * Add check to make sure the ending date/time is later than starting date/time
        * Add alternative notifications other than Growl
        * Improve message formatting
        * Tighten code (I am not a developer, so I am sure this script is pretty amateur stuff)
*)


-- Configurable Fields
global meetingInterval
global exchangeAccountName
global exchangeUserEmail
global defStartTime
global defEndTime
global timeZoneDescription
global useGrowl
set meetingInterval to 30 as number -- This sets the search interval.  30 seems to offer the best performance / detail balance, smaller intervals increase processing time
set exchangeAccountName to "CompanyExchange" as string -- This is the name of your Exchange account in Outlook Accounts
set exchangeUserEmail to "name@company.com" as string -- Email address of the account queries for availability
set defStartTime to "9:30am" as string -- The earliest meetings that will be considered
set defEndTime to "4:30pm" as string -- The latest meetings that will be considered
set timeZoneDescription to "(Central)" as string -- Time zone, only a label for the header, does not impact any actual dates or times
set useGrowl to true -- Change to false if you don't have Growl installed.  However, turning this off will also turn off notifications for when the script is done running.

-- There should not be any reason to modify anything below this point, unless looking to improve the script.

-- Global declarations
global emailCalendar -- This variable is where the message regarding availability is built
global crlf
global dayOfWeek
global startingTime
global endingTime
global isNewLine
set startingTime to (current date)
set endingTime to (current date)
set isNewLine to true
set dayOfWeek to " " as string
set crlf to (ASCII character 13) & (ASCII character 10) -- Applescript has issues with inserting carriage returns, so had to use this declaration

-- The getDate function converts text input into date.  This was necessary because performing date operations within the Outlook application yielded unpredictable results and often mis-fired.
on getDate(textInput)
    return date textInput
end getDate

-- The writeOutLine takes global variables, concatnates into a single line and adds to the message
on writeOutLine()
    set newLine to "   " & time string of startingTime & " - " & time string of endingTime & crlf as string
    set emailCalendar to emailCalendar & newLine
end writeOutLine

(* This is the biggest and most complex portion of the script.  The evalDate(date,string,boolean,boolean) function takes information from the Outlook's availability arrays, performs all the checks to ensure the time range is "free", within the time when meetings are allowed, not on a weekend, etc.  The two booleans are used for special handling of the first and the last values in the array
*)

on evalDate(inDate, aStatus, isLastItem, isFirstItem)
   
    -- Set the upper and lower time limits for availability
    set upperTime to date (date string of inDate & " " & defStartTime) as date
    set lowerTime to date (date string of inDate & " " & defEndTime) as date
   
    -- First check is to see if the time-slot is available
    if aStatus is "free" then
        -- Check if the time is in-range of availability
        if inDate is greater than or equal to upperTime and inDate is less than or equal to lowerTime then
            -- Check if not on the weekend
            if weekday of inDate as string is not "Saturday" and weekday of inDate as string is not "Sunday" then
                -- This next if statement is used to determine whether a new date / day of the week label is necessary
                if dayOfWeek is not equal to weekday of inDate as string then
                    if isFirstItem then
                        -- If the new label is required and it's the first item in the array, simply write out the date and day of the week
                        set dayOfWeek to weekday of inDate as string
                        set emailCalendar to emailCalendar & crlf & "* " & date string of inDate & crlf
                    else
                        -- If in the middle of processing, in addition to writing the line out, need to manipulate times to keep the logic moving forward
                        set endingTime to endingTime - (meetingInterval * minutes)
                        writeOutLine() of me
                        set aDuration to meetingInterval
                        set isNewLine to true
                        set dayOfWeek to weekday of inDate as string
                        set emailCalendar to emailCalendar & crlf & "* " & date string of inDate & crlf
                    end if
                end if
                -- The next if statement is for grouping available time slots so that the script does not list each meeting interval returned by Outlook on its own line
                if isNewLine then
                    -- Starting a new line, which causes incrementing the endingTime, without writing anything out
                    set startingTime to inDate
                    set endingTime to startingTime + (meetingInterval * minutes)
                    set isNewLine to false
                   
                    if isLastItem then
                        -- If it's the last item, then write out the current times
                        set endingTime to endingTime - (meetingInterval * minutes)
                        writeOutLine() of me
                    end if
                else
                    if endingTime is equal to inDate then
                        -- Not a new line, and the next time slot is still "free", which increments time values without writing anything out.
                        set endingTime to endingTime + (meetingInterval * minutes)
                        set isNewLine to false
                        if isLastItem then
                            -- unless it's the end of the array, which means it should be written out.
                            writeOutLine() of me
                        end if
                    else
                        -- If the next value is not "free", then write out and increment times.
                        writeOutLine() of me
                        set startingTime to inDate
                        set endingTime to startingTime + (meetingInterval * minutes)
                        set isNewLine to false
                    end if
                end if
            end if
        end if
    end if
end evalDate

-- The startMessage function simply prints out the heading at the top of the mesage
on startMessage(startText, endText)
    if short date string of startText is equal to short date string of endText then
        -- Simpler banner if only one date is selected
        set emailCalendar to "Here is my availability for " & date string of startText & " " & timeZoneDescription & ": " & crlf
    else
        set emailCalendar to "Here is my availability between " & short date string of startText & " and " & short date string of endText & " " & timeZoneDescription & ": " & crlf
    end if
    set emailCalendar to emailCalendar & "-------------------------------------------------------------------------------------------" & crlf
end startMessage

-- This routine I took right from the Growl website, and customized it for my purpose.  It's use is controlled through the useGrowl boolean at the top of the script.
on sendNotification()
    tell application "System Events"
        set isRunning to (count of (every process whose bundle identifier is "com.Growl.GrowlHelperApp")) > 0
    end tell
   
    if isRunning then
        tell application id "com.Growl.GrowlHelperApp"
           
            set the allNotificationsList to ¬
                {"Progress Report"}
           
            set the enabledNotificationsList to ¬
                {"Progress Report"}
           
            register as application ¬
                "FreeBusy Data Extract" all notifications allNotificationsList ¬
                default notifications enabledNotificationsList ¬
                icon of application "Script Editor"
           
            notify with name ¬
                "Progress Report" title ¬
                "Availability has been copied into clipboard" description ¬
                "You may now paste into any message you like..." application name "FreeBusy Data Extract"
           
        end tell
    end if
end sendNotification


-- This is the main routine
tell application "Microsoft Outlook"
    with timeout of 600 seconds
       
        set thisAccount to exchange account exchangeAccountName -- Get the exchange account object based on name configured in Outlook Accounts
       
        set defStart to short date string of (current date) & " " & defStartTime
        set defEnd to short date string of (current date) & " " & defEndTime
       
        -- The 2 repeat routines below are used for getting the starting and ending date/times.  I don't remember where I found it, but this is the other piece of code I did not write
        repeat
            display dialog "Starting date..." default answer defStart with title "Starting Date"
            set startText to text returned of result
            --print startText
            try
                if startText is not "" then
                    exit repeat
                end if
            on error
                beep
            end try
        end repeat
       
       
        repeat
            display dialog "Ending date..." default answer defEnd with title "Ending Date"
            set endText to text returned of result
            try
                if endText is not "" then
                    --set endDate to date endText as string
                    exit repeat
                end if
            on error
                beep
            end try
        end repeat
       
       
        -- Writes out the header for availability
        startMessage(getDate(startText) of me, getDate(endText) of me) of me
       
        -- Gets availability from Exchange in the following order:email address, starting date/time, repeat for each{subject, location, and status}
        set availability to (query freebusy thisAccount for attendees exchangeUserEmail range start time date startText range end time date endText interval meetingInterval)
       
        set listSize to (count of availability) as number -- Total number of items returned by Exchange
       
        set timeSlot to getDate(startText as string) of me
        set endSlot to getDate(endText as string) of me
        set listIndex to 5 as number -- The array's first two items are not related to availability, followed by 3 items that are.  Therefore, need to start processing at index 5
       
        set date_array to {} -- Array used to hold dates from the original array returned by Exchange
        set status_array to {} -- Array used to hold status from the original array returned by Exchange
       
        -- Load the two arrays with data from Exchange  Working with the original array was difficult becaues of its structure, creating two new arrays made it easier to troubleshoot the logic of looping through dates / times
        repeat while listIndex is not equal to (count of availability)
           
            set the end of date_array to timeSlot as date
            set the end of status_array to item listIndex of availability as string
           
            set listIndex to listIndex + 3
            set timeSlot to timeSlot + (meetingInterval * minutes) -- Since times are not returned from Exchange, manually creating them for each status returned from Exchange                        
        end repeat
       
        -- Main loop through the new arrays.
        set listIndex to 1
        repeat while listIndex is less than or equal to (count of date_array)
           
            -- Check if the first item in the array
            if listIndex is equal to (count of date_array) then
                set isLastItem to true
            else
                set isLastItem to false
            end if
           
            -- Check if the last item in the array
            if listIndex is equal to 1 then
                set isFirstItem to true
            else
                set isFirstItem to false
            end if
           
            -- Submit date and availability for evaluation
            evalDate(item listIndex of date_array, item listIndex of status_array, isLastItem, isFirstItem) of me
           
            set listIndex to listIndex + 1
            set timeSlot to timeSlot + (meetingInterval * minutes)
           
        end repeat
       
        -- I ran into trouble trying to create text and html versions of the availability information, and eventually settled on simply putting the email content into the clipboard, to be pasted anywhere I like.
        set the clipboard to emailCalendar
       
        -- Notify when done processing.  For slow servers or large date ranges the script can run for a little while, and I found this notification very useful.
        if useGrowl then
            sendNotification() of me
        end if
       
    end timeout
end tell

Mac users who need fuller Exchange Server support often use Outlook 2011 (part of Microsoft’s Office:mac 2011 package) as their primary email application. Here’s an AppleScript for Outlook 2011 that lets you send items directly to (my favorite) task manger — OmniFocus for Mac! This script will send any type of Outlook item/items (messages, tasks, […]

(*
Veritrope.com
Outlook 2011 to Omnifocus
VERSION 1.11
May 31, 2014

// SCRIPT INFORMATION AND UPDATE PAGE
http://veritrope.com/code/outlook-2011-to-omnifocus

// REQUIREMENTS
THIS SCRIPT REQUIRES OS X 10.9+ AND OUTLOOK 2011 SP1 OR GREATER!
More details on the script information page.

// CHANGELOG
1.11  ADDED SWITCH TO DISABLE ATTACHMENTS, CHANGE FROM APPLICATION NAME TO BUNDLE ID TO AVOID VIRTUAL MACHINE CONFLICTS WITH OUTLOOK
1.10  FIX FOR OMNIFOCUS 2.0, GROWL/NOTIFICATION CENTER SWITCH, STARTING TO INTEGRATE NOTIFICATION CENTER
1.01  ADDED ORGANIZER INFO FOR MEETINGS
1.00  FINAL (UPDATED GROWL CODE)
1.00  BETA 1 - ASSORTED BUG FIXES
0.99  REVISED GROWL CODE
0.98  INITIAL RELEASE

// RECOMMENDED INSTALLATION INSTRUCTIONS:
1.) Save this script to ~/Documents/Microsoft User Data/Outlook Script Menu Items (Or Its Equivalent in Localized Language);
(You can navigate quickly to this folder by selecting:
 Outlook's Script Menu => About This Menu... => Open Folder)

2.) Give it a filename that enables a keyboard shortcut to be used.
   
Example:
Saving the script with the name "Send to OmniFocus\mO.scpt" lets you press ⌘O to send items to Evernote!

3.) Enjoy!

// TERMS OF USE:
This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License.
To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-sa/3.0/ or send a letter to Creative Commons, 444 Castro Street, Suite 900, Mountain View, California, 94041, USA.

*)


(*
======================================
// USER SWITCHES (YOU CAN CHANGE THESE!)
======================================
*)


--SET THIS TO "ON" IF YOU PREFER GROWL NOTIFICATIONS
--TO OSX'S NOTIFICATION CENTER (DEFAULT IS "OFF")
property growlSwitch : "OFF"

--SET THIS TO "OFF" IF YOU PREFER TO DISABLE
--ATTACHMENT PROCESSING (DEFAULT IS "ON")
property attachSwitch : "ON"


(*
======================================
// OTHER PROPERTIES (USE CAUTION WHEN CHANGING)
======================================
*)

property successCount : 0
property growl_Running : "false"
property myTitle : "Item"
property theAttachments : ""
property thisMessage : ""
property itemNum : "0"
property attNum : "0"
property errNum : "0"
property errorText : ""
property the_class : ""
property list_Props : {}
property SaveLoc : ""
property NewTask : {}

(*
======================================
// MAIN PROGRAM
======================================
*)


--LET'S GO!
try
    --CHECK FOR GROWL SWITCH
    if growlSwitch is "ON" then my startGrowl()
   
    --SET UP ACTIVITIES
    set selectedItems to {}
   
    set selectedItems to my item_Check()
   
    --MESSAGES SELECTED?
    if selectedItems is not missing value then
       
        --GET FILE COUNT
        my item_Count(selectedItems, the_class)
       
        --ANNOUNCE THE EXPORT OF ITEMS
        my process_Items(itemNum, attNum, the_class)
       
        --PROCESS ITEMS FOR EXPORT
        my item_Process(selectedItems)
       
        --DELETE TEMP FOLDER IF IT EXISTS
        set success to my trashfolder(SaveLoc)
       
        --NO ITEMS SELECTED
    else
        set successCount to -1
    end if
   
   
    --GROWL RESULTS
    if growlSwitch is "ON" then
        my growl_Growler(successCount, itemNum)
    else
        my notification_Center(successCount, itemNum)
    end if
   
    -- ERROR HANDLING
on error errText number errNum
    tell application "System Events"
        set isGrlRunning to (count of (every process whose bundle identifier is "com.Growl.GrowlHelperApp")) > 0
    end tell
   
    ignoring application responses
        if isGrlRunning then
            if errNum is -128 then
                set part_1 to "tell application \"Growl\"
                "

                set part_2 to "notify with name ¬
                    \"Failure Notification\" title ¬
                    \"User Cancelled\" description \"User Cancelled\" application name ¬
                    \"Outlook to OmniFocus\"
                    end tell"

            else
                -- GROWL FAILURE FOR ERROR
                set part_2 to "notify with name ¬
                    \"Failure Notification\" title ¬
                    \"Import Failure\" description \"Failed to export due to the following error: \" & return & errText ¬
                    application name \"Outlook to OmniFocus\"
            end tell"

            end if
           
            -- NON-GROWL ERROR MSG. FOR ERROR
            display dialog "Item Failed to Import: " & errNum & return & errText with icon 0
        end if
    end ignoring
end try

(*
======================================
// PREPARATORY SUBROUTINES
======================================
*)


--APP DETECT
on appIsRunning(appName)
    tell application "System Events" to (name of processes) contains appName
end appIsRunning

--SET UP ACTIVITIES
on item_Check()
    tell application id "com.microsoft.Outlook"
        try -- GET MESSAGES
            set selectedItems to selection
            set raw_Class to (class of selectedItems)
            if raw_Class is list then
                set classList to {}
                repeat with selectedItem in selectedItems
                    copy class of selectedItem to end of classList
                end repeat
                if classList contains task then
                    set the_class to "Task"
                else
                    set raw_Class to (class of item 1 of selectedItems)
                end if
            end if
            if raw_Class is calendar event then set the_class to "Calendar"
            if raw_Class is note then set the_class to "Note"
            if raw_Class is task then set the_class to "Task"
            if raw_Class is contact then set the_class to "Contact"
            if raw_Class is incoming message then set the_class to "Message"
            if raw_Class is text then set the_class to "Text"
        end try
        return selectedItems
    end tell
end item_Check

--GET COUNT OF ITEMS AND ATTACHMENTS
on item_Count(selectedItems, the_class)
    tell application id "com.microsoft.Outlook"
        if the_class is not "Text" then
            set itemNum to [count of selectedItems]
            set attNum to 0
            try
                repeat with selectedMessage in selectedItems
                    set attNum to attNum + (count of attachment of selectedMessage)
                end repeat
            end try
        else
            set itemNum to 1
        end if
    end tell
end item_Count

(*
======================================
// PROCESS OUTLOOK ITEMS SUBROUTINE
======================================
*)


on item_Process(selectedItems)
    tell application id "com.microsoft.Outlook"
       
        --TEXT ITEM CLIP
        if (class of selectedItems) is text then
            set OFTitle to selectedItems
            set theContent to "Text Clipping from Outlook"
           
            --CREATE IN OMNIFOCUS
            tell application "OmniFocus"
                tell the first document
                    set NewTask to make new inbox task with properties {name:OFTitle, note:theContent}
                end tell
            end tell
           
            --ITEM HAS FINISHED -- COUNT IT AS A SUCCESS!
            set successCount to 1
        else
            --FULL ITEM EXPORT
            repeat with selectedItem in selectedItems
                set theProps to (properties of selectedItem)
                try
                    set theAttachments to attachments of selectedItem
                    set raw_Attendees to attendees of selectedItem
                end try
               
                --SET UP SOME VALUES
                set theCompletionDate to missing value
                set theStartDate to missing value
                set theDueDate to missing value
                set theFlag to false
               
                -- GET OUTLOOK ITEM INFORMATION
                set the_vCard to {}
               
                --WHAT KIND OF ITEM IS IT?
                if the_class is "Calendar" then
                   
                    (* // CALENDAR ITEM *)
                   
                    --PREPARE THE TEMPLATE 
                    --LEFT SIDE (FORM FIELDS)
                    set l_1 to "Event:  "
                    set l_2 to "Start Time:  "
                    set l_3 to "End Time:  "
                    set l_4 to "Location:  "
                    set l_5 to "Notes  :"
                   
                    --RIGHT SIDE (DATA FIELDS)
                    set r_1 to (subject of theProps)
                    set r_2 to (start time of theProps)
                    set r_3 to (end time of theProps)
                    set the_Location to (location of theProps)
                    if the_Location is missing value then set the_Location to "None"
                    set r_4 to the_Location
                   
                    --THE NOTES
                    set the_notes to ""
                    set item_Created to (current date)
                    try
                        set the_notes to (plain text content of theProps)
                    end try
                    if the_notes is missing value then set the_notes to ""
                   
                    --ADD ATTENDEE INFO IF IT'S A MEETING
                    if (count of raw_Attendees) > 0 then
                        set the_Organizer to "<strong>Organized By: </strong><br/>" & (organizer of selectedItem) & "<br/><br/>"
                        set the_Attendees to "Invited Attendees: " & return
                        repeat with raw_Attendee in raw_Attendees
                           
                            --GET ATTENDEE DATA
                            set raw_EmailAttendee to (email address of raw_Attendee)
                            set attend_Name to (name of raw_EmailAttendee) as text
                            set raw_Status to (status of raw_Attendee)
                           
                            --COERCE STATUS TO TEXT
                            if raw_Status contains not responded then
                                set attend_Status to "Not Responded"
                            else if raw_Status contains accepted then
                                set attend_Status to "Accepted"
                            else if raw_Status contains declined then
                                set attend_Status to "Declined"
                            else if raw_Status contains tentatively accepted then
                                set attend_Status to "Tentatively Accepted"
                            end if
                           
                            --COMPILE THE ATTENDEE DATA
                            set attend_String to attend_Name & " (" & attend_Status & ")" & return
                            set the_Attendees to the_Attendees & attend_String
                        end repeat
                        set the_notes to (the_Organizer & the_Attendees & the_notes)
                        set raw_Attendees to ""
                    end if
                   
                    --ASSEMBLE THE TEMPLATE
                    set theContent to l_1 & r_1 & return & l_2 & r_2 & return & l_3 & r_3 & return & l_4 & r_4 & return & return & return & return & the_notes & return & return
                   
                    --EXPORT VCARD DATA
                    try
                        set vcard_data to (icalendar data of theProps)
                        set vcard_extension to ".ics"
                        set the_vCard to my write_File(r_1, vcard_data, vcard_extension)
                    end try
                   
                    set OFTitle to r_1
                   
                    (* // NOTE ITEM *)
                else if the_class is "note" then
                   
                    --PREPARE THE TEMPLATE 
                    --LEFT SIDE (FORM FIELDS)
                    set l_1 to "Note:  "
                    set l_2 to "Creation Date:  "
                    set l_3 to "Category:  "
                    set l_4 to ""
                    set l_5 to "Notes:  "
                   
                    --RIGHT SIDE (DATA FIELDS)
                    set r_1 to name of theProps
                    set item_Created to creation date of theProps
                    set r_2 to (item_Created as text)
                   
                    --GET CATEGORY INFO
                    set the_Cats to (category of theProps)
                    set list_Cats to {}
                    set count_Cat to (count of the_Cats)
                    repeat with the_Cat in the_Cats
                        set cat_Name to (name of the_Cat as text)
                        copy cat_Name to the end of list_Cats
                        if count_Cat > 1 then
                            copy ", " to the end of list_Cats
                            set count_Cat to (count_Cat - 1)
                        else
                            set count_Cat to (count_Cat - 1)
                        end if
                    end repeat
                   
                    set r_3 to list_Cats
                    set r_4 to ""
                   
                    set item_Created to creation date of theProps
                   
                    --THE NOTES
                    try
                        set the_notes to plain text content of theProps
                    end try
                    if the_notes is missing value then set the_notes to ""
                   
                    --ASSEMBLE THE TEMPLATE
                    set theContent to l_1 & r_1 & return & l_2 & r_2 & return & l_3 & r_3 & return & l_4 & r_4 & return & return & return & return & the_notes & return & return
                   
                    --EXPORT VCARD DATA
                    set vcard_data to (icalendar data of theProps)
                    set vcard_extension to ".ics"
                    set the_vCard to my write_File(r_1, vcard_data, vcard_extension)
                   
                    set theHTML to true
                    set OFTitle to r_1
                   
                    (* // CONTACT ITEM *)
                else if the_class is "contact" then
                   
                    --PREPARE THE TEMPLATE 
                    --LEFT SIDE (FORM FIELDS)
                    set l_1 to "Name:  "
                    set l_2 to "Email:  "
                    set l_3 to "Phone Numbers:" & return
                    set l_4 to "Addresses:" & return
                    set l_5 to "Notes:"
                   
                    --GET EMAIL INFO
                    try
                        set list_Addresses to {}
                        set email_Items to (email addresses of theProps)
                        repeat with email_Item in email_Items
                            set the_Type to (type of email_Item as text)
                            set addr_Item to (address of email_Item) & " (" & my TITLECASE(the_Type) & ")" & return as text
                            copy addr_Item to the end of list_Addresses
                        end repeat
                    end try
                   
                    --GET PHONE INFO AND ENCODE TELEPHONE LINK
                    try
                        set list_Phone to {}
                        if business phone number of theProps is not missing value then
                            set b_Number to (business phone number of theProps)
                            set b_String to "-Work:  " & b_Number & return
                            copy b_String to end of list_Phone
                        end if
                        if home phone number of theProps is not missing value then
                            set h_Number to (home phone number of theProps)
                            set h_String to "-Home:  " & h_Number & return
                            copy h_String to end of list_Phone
                        end if
                        if mobile number of theProps is not missing value then
                            set m_Number to (mobile number of theProps)
                            set m_String to "-Mobile:  " & m_Number & return
                            copy m_String to end of list_Phone
                        end if
                    end try
                   
                    --GET ADDRESS INFO
                    try
                        set list_Addr to {}
                       
                        (*BUSINESS *)
                        if business street address of theProps is not missing value then
                            set b_Str to (business street address of theProps)
                            set b_gStr to my encodedURL(b_Str)
                            if (business city of theProps) is not missing value then
                                set b_Cit to (business city of theProps)
                                set b_gCit to my encodedURL(b_Cit)
                            else
                                set b_Cit to ""
                                set b_gCit to ""
                            end if
                            if (business state of theProps) is not missing value then
                                set b_Sta to (business state of theProps)
                                set b_gSta to my encodedURL(b_Sta)
                            else
                                set b_Sta to ""
                                set b_gSta to ""
                            end if
                            if (business zip of theProps) is not missing value then
                                set b_Zip to (business zip of theProps)
                                set b_gZip to my encodedURL(b_Zip)
                            else
                                set b_Zip to ""
                                set b_gZip to ""
                            end if
                            if (business country of theProps) is not missing value then
                                set b_Cou to (business country of theProps)
                                set b_gCou to my encodedURL(b_Cou)
                            else
                                set b_Cou to ""
                                set b_gCou to ""
                            end if
                            set b_Addr to b_Str & return & b_Cit & ", " & b_Sta & "  " & b_Zip & return & b_Cou
                           
                            --GOOGLE MAPS LOCATION IN URL
                            set b_gString to b_gStr & "," & b_gCit & "," & b_gSta & "," & b_gZip & "," & b_gCou
                            set b_GMAP to "http://maps.google.com/maps?q=" & b_gString
                            set b_String to "-Work: " & return & b_Addr & return & "(Link to Google Map:  " & b_GMAP & ")" & return
                            copy b_String to end of list_Addr
                        end if
                       
                        (*HOME *)
                        if home street address of theProps is not missing value then
                            set h_Str to (home street address of theProps)
                            set h_gStr to my encodedURL(h_Str)
                            if (home city of theProps) is not missing value then
                                set h_Cit to (home city of theProps)
                                set h_gCit to my encodedURL(h_Cit)
                            else
                                set h_Cit to ""
                                set h_gCit to ""
                            end if
                            if (home state of theProps) is not missing value then
                                set h_Sta to (home state of theProps)
                                set h_gSta to my encodedURL(h_Sta)
                            else
                                set h_Sta to ""
                                set h_gSta to ""
                            end if
                            if (home zip of theProps) is not missing value then
                                set h_Zip to (home zip of theProps)
                                set h_gZip to my encodedURL(h_Zip)
                            else
                                set h_Zip to ""
                                set h_gZip to ""
                            end if
                            if (home country of theProps) is not missing value then
                                set h_Cou to (home country of theProps)
                                set h_gCou to my encodedURL(h_Cou)
                            else
                                set h_Cou to ""
                                set h_gCou to ""
                            end if
                            set h_Addr to h_Str & return & h_Cit & ", " & h_Sta & "  " & h_Zip & return & h_Cou
                           
                            --GOOGLE MAPS LOCATION IN URL
                            set h_gString to h_gStr & "," & h_gCit & "," & h_gSta & "," & h_gZip & "," & h_gCou
                            set h_GMAP to "http://maps.google.com/maps?q=" & h_gString
                            set h_String to "-Home:  " & return & h_Addr & return & "(Link to Google Map:  " & h_GMAP & ")" & return
                            copy h_String to end of list_Addr
                        end if
                    end try
                   
                    --RIGHT SIDE (DATA FIELDS)
                    set r_1 to (display name of theProps)
                    set r_2 to (list_Addresses as string)
                    set r_3 to (list_Phone as text)
                    set r_4 to (list_Addr as text)
                   
                    --EXPORT VCARD DATA
                    set vcard_data to (vcard data of theProps)
                    set vcard_extension to ".vcf"
                    set item_Created to (current date)
                   
                    --THE NOTES
                    try
                        set the_notes to plain text note of theProps
                    end try
                    if the_notes is missing value then set the_notes to ""
                   
                    --ASSEMBLE THE TEMPLATE
                    set theContent to l_1 & r_1 & return & l_2 & r_2 & return & l_3 & r_3 & return & l_4 & r_4 & return & return & return & return & the_notes & return & return
                    set the_vCard to my write_File(r_1, vcard_data, vcard_extension)
                   
                    set OFTitle to r_1
                   
                    (* // TASK ITEM *)
                else if the_class is "Task" then
                   
                    --PREPARE THE TEMPLATE 
                    --LEFT SIDE (FORM FIELDS)
                    set l_1 to "Note:  "
                    set l_2 to "Priority:  "
                    set l_3 to "Due Date:  "
                    set l_4 to "Status:  "
                    set l_5 to "Notes:  "
                   
                    --RIGHT SIDE (DATA FIELDS)
                    set propClass to (class of theProps) as text
                    if propClass is "incoming message" then
                        set r_1 to (subject of theProps)
                    else
                        set r_1 to (name of theProps)
                    end if
                    set the_Priority to (priority of theProps)
                    if the_Priority is priority normal then set r_2 to "Normal"
                    if the_Priority is priority high then set r_2 to "High"
                    if the_Priority is priority low then set r_2 to "Low"
                   
                    set theDueDate to (due date of theProps)
                    set r_3 to theDueDate
                    set theCompletionDate to (completed date of theProps)
                    set theStartDate to (start date of theProps)
                    set item_Created to (current date)
                   
                    --TODO?
                    try
                        set todo_Flag to (todo flag of theProps) as text
                        set r_4 to my TITLECASE(todo_Flag)
                    end try
                   
                    --THE NOTES
                    try
                        set the_notes to plain text content of theProps
                    end try
                    if the_notes is missing value then set the_notes to ""
                   
                    --ASSEMBLE THE TEMPLATE
                    set theContent to l_1 & r_1 & return & l_2 & r_2 & return & l_3 & r_3 & return & l_4 & r_4 & return & return & return & return & the_notes & return & return
                   
                   
                    --EXPORT VCARD DATA
                    if propClass is not "incoming message" then
                        set vcard_extension to ".ics"
                        set vcard_data to (icalendar data of theProps)
                        set the_vCard to my write_File(r_1, vcard_data, vcard_extension)
                    end if
                   
                    set OFTitle to r_1
                   
                    (* // MESSAGE ITEM *)
                else
                   
                    --GET EMAIL INFO
                    set the_Sender to (sender of theProps)
                    set s_Name to (address of the_Sender)
                    set s_Address to (address of the_Sender)
                   
                    --REPLACE WITH NAME, IF AVAILABLE
                    try
                        set s_Name to (name of the_Sender)
                    end try
                   
                   
                    --GET CATEGORY INFO
                    set the_Cats to (category of theProps)
                    set list_Cats to {}
                    set count_Cat to (count of the_Cats)
                    repeat with the_Cat in the_Cats
                        set cat_Name to (name of the_Cat as text)
                        copy cat_Name to the end of list_Cats
                        if count_Cat > 1 then
                            copy ", " to the end of list_Cats
                            set count_Cat to (count_Cat - 1)
                        else
                            set count_Cat to (count_Cat - 1)
                        end if
                    end repeat
                   
                    --RIGHT SIDE (DATA FIELDS)
                    set m_Sub to (subject of theProps)
                    if m_Sub is missing value then
                        set r_2 to "<No Subject>"
                    else
                        set r_2 to {subject of theProps}
                    end if
                    set r_3 to (time sent of theProps)
                    set r_4 to list_Cats
                   
                    set theID to id of theProps as string
                    set item_Created to r_3
                    set OFTitle to r_2
                   
                    set theDueDate to (due date of theProps)
                    set theCompletionDate to (completed date of theProps)
                    set theStartDate to (start date of theProps)
                   
                    set oFlag to (todo flag of theProps) as text
                    if oFlag is "not completed" then
                        set theFlag to true
                    end if
                   
                    --PROCESS EMAIL CONTENT
                    set m_Content to plain text content of theProps
                    set theContent to "Name: " & s_Name & return & "Subject: " & r_2 & return & "Sent: " & r_3 & return & "Category: " & r_4 & return & return & return & return & m_Content & return & return
                end if
               
                --CREATE IN OMNIFOCUS
                tell application "OmniFocus"
                    tell the first document
                        set NewTask to make new inbox task with properties {name:OFTitle, note:theContent, flagged:theFlag, due date:theDueDate, completion date:theCompletionDate, defer date:theStartDate}
                    end tell
                end tell
               
                --ATTACH VCARD (IF PRESENT)
                if the_vCard is not {} then my vCard_Attach(the_vCard, theProps, NewTask)
               
                --IF ATTACHMENTS PRESENT, RUN ATTACHMENT SUBROUTINE
                if theAttachments is not {} then my message_Attach(theAttachments, theProps, NewTask)
               
                --ITEM HAS FINISHED! COUNT IT AS A SUCCESS AND RESET ATTACHMENTS!
                set successCount to successCount + 1
                set theAttachments to {}
            end repeat
        end if
    end tell
end item_Process

(*
======================================
// UTILITY SUBROUTINES
======================================
*)


--URL ENCODE
on encodedURL(the_Word)
    set scpt to "php -r 'echo urlencode(\"" & the_Word & "\");'"
    return do shell script scpt
end encodedURL

--TITLECASE
on TITLECASE(txt)
    return do shell script "python -c \"import sys; print unicode(sys.argv[1], 'utf8').title().encode('utf8')\" " & quoted form of txt
end TITLECASE

--SORT SUBROUTINE
on simple_sort(my_list)
    set the index_list to {}
    set the sorted_list to {}
    repeat (the number of items in my_list) times
        set the low_item to ""
        repeat with i from 1 to (number of items in my_list)
            if i is not in the index_list then
                set this_item to item i of my_list as text
                if the low_item is "" then
                    set the low_item to this_item
                    set the low_item_index to i
                else if this_item comes before the low_item then
                    set the low_item to this_item
                    set the low_item_index to i
                end if
            end if
        end repeat
        set the end of sorted_list to the low_item
        set the end of the index_list to the low_item_index
    end repeat
    return the sorted_list
end simple_sort

--REPLACE
on replaceString(theString, theOriginalString, theNewString)
    set theNum to 0
    set {od, AppleScript's text item delimiters} to {AppleScript's text item delimiters, theOriginalString}
    set theStringParts to text items of theString
    if (count of theStringParts) is greater than 1 then
        set theString to text item 1 of theStringParts as string
        repeat with eachPart in items 2 thru -1 of theStringParts
            set theString to theString & theNewString & eachPart as string
            set theNum to theNum + 1
        end repeat
    end if
    set AppleScript's text item delimiters to od
    return theString
end replaceString


(*
======================================
// ATTACHMENT SUBROUTINES
=======================================
*)


--CLEAN TITLE FOR FILENAME
on clean_Title(rawFileName)
    set previousDelimiter to AppleScript's text item delimiters
    set potentialName to rawFileName
    set legalName to {}
    set illegalCharacters to {".", ",", "/", ":", "[", "]"}
    repeat with thisCharacter in the characters of potentialName
        set thisCharacter to thisCharacter as text
        if thisCharacter is not in illegalCharacters then
            set the end of legalName to thisCharacter
        else
            set the end of legalName to "_"
        end if
    end repeat
    return legalName
end clean_Title

--WRITE THE FILE
on write_File(r_1, vcard_data, vcard_extension)
    set ExportFolder to ((path to desktop folder) & "Temp Export From Outlook:") as string
    set SaveLoc to my f_exists(ExportFolder)
    set fileName to (my clean_Title(r_1) & vcard_extension)
    set theFileName to (ExportFolder & fileName)
    try
        open for access file theFileName with write permission
        write vcard_data to file theFileName as string
        close access file theFileName
        return theFileName
       
    on error errorMessage
        log errorMessage
        try
            close access file theFileName
        end try
    end try
end write_File

--FOLDER EXISTS
on f_exists(ExportFolder)
    try
        set myPath to (path to home folder)
        get ExportFolder as alias
        set SaveLoc to ExportFolder
    on error
        tell application "Finder" to make new folder with properties {name:"Temp Export From Outlook"}
    end try
end f_exists

--VCARD PROCESSING
on vCard_Attach(the_vCard, theProps, NewTask)
    tell application "OmniFocus"
        tell the note of NewTask
            make new file attachment with properties {file name:POSIX file the_vCard, embedded:true}
        end tell
    end tell
end vCard_Attach

--ATTACHMENT PROCESSING
on message_Attach(theAttachments, theProps, NewTask)
    if attachSwitch is "ON" then
        tell application id "com.microsoft.Outlook"
            --MAKE SURE TEXT ITEM DELIMITERS ARE DEFAULT
            set AppleScript's text item delimiters to ""
           
            --TEMP FILES PROCESSED ON THE DESKTOP
            set ExportFolder to ((path to desktop folder) & "Temp Export From Outlook:") as string
            set SaveLoc to my f_exists(ExportFolder)
           
            --PROCESS THE ATTCHMENTS
            set attCount to 0
            repeat with theAttachment in theAttachments
                set theFileName to (ExportFolder & theAttachment's name)
                try
                    save theAttachment in theFileName
                end try
                tell application "OmniFocus"
                    tell the note of NewTask
                        make new file attachment with properties {file name:file theFileName, embedded:true}
                    end tell
                end tell
               
                --SILENT DELETE OF TEMP FILE
                set trash_Folder to path to trash folder from user domain
                do shell script "mv " & quoted form of POSIX path of theFileName & space & quoted form of POSIX path of trash_Folder
            end repeat
        end tell
    end if
end message_Attach

--SILENT DELETE OF TEMP FOLDER (THANKS MARTIN MICHEL!)
on trashfolder(SaveLoc)
    try
        set trashfolderpath to ((path to trash) as Unicode text)
        set srcfolderinfo to info for (SaveLoc as alias)
        set srcfoldername to name of srcfolderinfo
        set SaveLoc to (SaveLoc as alias)
        set SaveLoc to (quoted form of POSIX path of SaveLoc)
        set counter to 0
        repeat
            if counter is equal to 0 then
                set destfolderpath to trashfolderpath & srcfoldername & ":"
            else
                set destfolderpath to trashfolderpath & srcfoldername & " " & counter & ":"
            end if
            try
                set destfolderalias to destfolderpath as alias
            on error
                exit repeat
            end try
            set counter to counter + 1
        end repeat
        set destfolderpath to quoted form of POSIX path of destfolderpath
        set command to "ditto " & SaveLoc & space & destfolderpath
        do shell script command
        -- this won't be executed if the ditto command errors
        set command to "rm -r " & SaveLoc
        do shell script command
        return true
    on error
        return false
    end try
end trashfolder

(*
======================================
// GROWL SUBROUTINES
======================================
*)

on startGrowl()
    try
        tell application "System Events"
            set isGrlRunning to (count of (every process whose bundle identifier is "com.Growl.GrowlHelperApp")) > 0
        end tell
        ignoring application responses
            if isGrlRunning then
                set osaSc to "tell application \"Growl\"
set the allNotificationsList to {\"Import To OmniFocus\", \"Success Notification\", \"Failure Notification\"}
set the enabledNotificationsList to {\"Import To OmniFocus\", \"Success Notification\", \"Failure Notification\"}
register as application \"Outlook to OmniFocus\" all notifications allNotificationsList default notifications enabledNotificationsList icon of application \"OmniFocus\"
notify with name \"Import To OmniFocus\" title \"Import To OmniFocus Started\" description \"Processing Items from Outlook\" application name \"Outlook to OmniFocus\"
end tell"

                set shSc to "osascript -e " & quoted form of osaSc & "  &>  /dev/null &"
                ignoring application responses
                    do shell script shSc
                end ignoring
            end if
        end ignoring
    end try
end startGrowl


--ANNOUNCE THE COUNT OF TOTAL ITEMS TO EXPORT
on process_Items(itemNum, attNum, the_class)
    try
        if growlSwitch is "ON" then
            tell application "System Events"
                set isGrlRunning to (count of (every process whose bundle identifier is "com.Growl.GrowlHelperApp")) > 0
            end tell
           
            set app_Path to (path to application id "com.microsoft.Outlook")
           
            ignoring application responses
                if isGrlRunning then
                    set attPlural to "s"
                    set the_class to the_class as text
                    if the_class is "List" then set the_class to "Outlook"
                    if the_class is "Incoming Message" then
                        set growl_Icon to (path to resource "Mail.icns" in bundle app_Path)
                    else if the_class is "Contact" then
                        set growl_Icon to (path to resource "vCrd.icns" in bundle app_Path)
                    else
                        set growl_Icon to (path to resource "lcs.icns" in bundle app_Path)
                    end if
                    set growl_Icon to (POSIX path of growl_Icon) as text
                   
                    if attNum = 0 then
                        set attNum to "No"
                    else if attNum is 1 then
                        set attPlural to ""
                    end if
                   
                    tell application "Finder"
                        if the_class is not "Text" then
                            set Plural_Test to (itemNum) as number
                            if Plural_Test is greater than 1 then
                               
                                set osaSc to "tell application \"Growl\"
notify with name \"Import To OmniFocus\" title \"Import To OmniFocus Started\" description \"Now Importing "
& itemNum & " " & the_class & " Items with " & attNum & ¬
                                    " Attachment" & attPlural & ".\" application name ¬
                            \"Outlook to OmniFocus\" identifier \"OmniFocus\" image from location \""
& growl_Icon & "\"
                            end tell"

                                set shSc to "osascript -e " & quoted form of osaSc & "  &>  /dev/null &"
                                my growlThis(shSc)
                            else
                                set osaSc to "tell application \"Growl\"
notify with name \"Import To OmniFocus\" title \"Import To OmniFocus Started\" description \"Now Importing "
& itemNum & " " & the_class & " Items with " & attNum & ¬
                                    " Attachment" & attPlural & ".\" application name ¬
                            \"Outlook to OmniFocus\" identifier \"OmniFocus\" image from location \""
& growl_Icon & "\"
                            end tell"

                                set shSc to "osascript -e " & quoted form of osaSc & "  &>  /dev/null &"
                                my growlThis(shSc)
                            end if
                        end if
                    end tell --FINDER
                end if
            end ignoring
        end if
       
    end try
end process_Items

on growlThis(shSc)
    ignoring application responses
        do shell script shSc
    end ignoring
end growlThis

--GROWL RESULTS
on growl_Growler(successCount, itemNum)
    try
        tell application "System Events"
            set isGrlRunning to (count of (every process whose bundle identifier is "com.Growl.GrowlHelperApp")) > 0
        end tell
       
        ignoring application responses
            if isGrlRunning then
                set part_1 to "tell application \"Growl\"
"

                set Plural_Test to (successCount) as number
                if Plural_Test is -1 then
                    set part_2 to "notify with name ¬
                    \"Failure Notification\" title ¬
                    \"Import Failure\" description \"No Items Selected In Outlook!\" application name ¬
                    \"Outlook to OmniFocus\"
                    end tell"

                else if Plural_Test is 0 then
                    set part_2 to "notify with name ¬
                    \"Failure Notification\" title ¬
                    \"Import Failure\" description \"No Items Exported From Outlook!\" application name ¬
                    \"Outlook to OmniFocus\"
                    end tell"

                else if Plural_Test is equal to 1 then
                    set part_2 to "notify with name ¬
                    \"Success Notification\" title ¬
                    \"Import Success\" description \"Successfully Exported "
& itemNum & ¬
                        " Item to OmniFocus\" application name ¬
                    \"Outlook to OmniFocus\"
                    end tell"

                else if Plural_Test is greater than 1 then
                    set part_2 to "notify with name ¬
                    \"Success Notification\" title ¬
                    \"Import Success\" description \"Successfully Exported "
& itemNum & ¬
                        " Items to OmniFocus\" application name ¬
                    \"Outlook to OmniFocus\"
                    end tell"

                end if
                set itemNum to "0"
                set combined_parts to part_1 & part_2
                set shSc to "osascript -e " & quoted form of combined_parts & "  &>  /dev/null &"
                my growlThis(shSc)
            end if
           
        end ignoring
    end try
end growl_Growler

--NOTIFICATION CENTER
on notification_Center(successCount, itemNum)
    set Plural_Test to (successCount) as number
   
    if Plural_Test is -1 then
        display notification "No Items Selected In Outlook!" with title "Outlook to OmniFocus" subtitle "Veritrope.com"
       
    else if Plural_Test is 0 then
        display notification "No Items Exported From Outlook!" with title "Outlook to OmniFocus" subtitle "Veritrope.com"
       
    else if Plural_Test is equal to 1 then
        display notification "Successfully Exported " & itemNum & ¬
            " Item to OmniFocus" with title "Outlook to OmniFocus" subtitle "Veritrope.com"
       
    else if Plural_Test is greater than 1 then
        display notification "Successfully Exported " & itemNum & ¬
            " Items to OmniFocus" with title "Outlook to OmniFocus" subtitle "Veritrope.com"
    end if
   
    set itemNum to "0"
    delay 1
end notification_Center

Notes to 10.9 “Mavericks” Users – Updated on May 31, 2014 Thanks to user Steven Beebe, the script has been reworked to use Notification Center instead of GROWL. As a result, you now need OS X 10.9 or above to run it without modification. One caveat: 10.9 and AppleScript seems to be a little glitchy […]

(*
Veritrope.com
OUTLOOK 2011 TO EVERNOTE
VERSION 1.07
May 31, 2014

// TERMS OF USE:
This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License.
To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-sa/3.0/ or send a letter to Creative Commons, 444 Castro Street, Suite 900, Mountain View, California, 94041, USA.

// LIKE THIS SCRIPT?
If this AppleScript is helpful to you, please show your support here:
http://veritrope.com/support

// SCRIPT INFORMATION AND UPDATE PAGE
http://veritrope.com/code/outlook-2011-to-evernote

// REQUIREMENTS
• OS X 10.9 Mavericks and Above.
• Microsoft Outlook 2011 SP1 and above.

//CHANGELOG
1.07   Change to budle id to avoid conflicts with Outlook installed on Virtual Machines
1.06    Thanks to Steven Beebe, script notifications now updated to use Notification Center and there's a user switch to remove embedded image links.
1.05     Fix for leading spaces in tags
1.04     Fixes for Attachements, Tagging
1.03     Added TO: / CC: Information to Email Messages
1.02     Added Meeting Organizer information
1.01     Removed unused code, Additional Tweak to GROWL code, Added Meeting Attendees
1.00     Tweak to GROWL code

// RECOMMENDED INSTALLATION INSTRUCTIONS:
1.)  Save this script to ~/Documents/Microsoft User Data/Outlook Script Menu Items (Or Its Equivalent in Localized Language);

(You can navigate quickly to this folder by selecting: Outlook's Script Menu => About This Menu… => Open Folder)

2.)  Give it a filename that enables a keyboard shortcut to be used.
   
Example: "Send to Evernote\mE.scpt" lets you press ⌘E to send items to Evernote!

3.) Enjoy!
   
*)


(*
======================================
// USER SWITCHES
======================================
*)


--SET THIS TO "OFF" IF YOU WANT TO SKIP THE TAGGING/NOTEBOOK DIALOG
--AND SEND ITEMS DIRECTLY INTO YOUR DEFAULT NOTEBOOK
property tagging_Switch : "ON"

--IF YOU'VE DISABLED THE TAGGING/NOTEBOOK DIALOG,
--TYPE THE NAME OF THE NOTEBOOK YOU WANT TO SEND ITEM TO
--BETWEEN THE QUOTES IF IT ISN'T YOUR DEFAULT NOTEBOOK.
--(EMPTY SENDS TO DEFAULT)
property EVnotebook : ""

--IF TAGGING IS ON AND YOU'D LIKE TO CHANGE THE DEFAULT TAG,
--TYPE IT BETWEEN THE QUOTES (ITEM TYPE IS DEFAULT)
property defaultTag : ""

--SOME EMAILS USING THE SRC="CID:..." TAG FOR EMBEDDED IMAGES
--GENERATE A "There is no application set to open the URL cid:(filename)"
--ERROR WHEN SENDING TO EVERNOTE. SETTING THIS PROPERTY TO
--ON WILL STRIP OUT THOSE TAGS AND AVOID THE ERROR.
property stripEmbeddedImages : "OFF"
(*
======================================
// OTHER PROPERTIES
======================================
*)

property successCount : 0
property account_Type : "free"
property myTitle : "Item"
property theAttachments : ""
property thisMessage : ""
property itemNum : "0"
property attNum : "0"
property errNum : "0"
property userTag : ""
property EVTag : {}
property the_class : ""
property list_Props : {}
property SaveLoc : ""
property selectedItem : {}
property t_List : {}
property c_List : {}

(*
======================================
// MAIN PROGRAM
======================================
*)


--RESET ITEMS
set successCount to "0"
set AppleScript's text item delimiters to ""
set selectedItems to {}
set ExportFolder to ""
set SaveLoc to ""

--LET'S GO!
try
   
    --SET UP ACTIVITIES
    set selectedItems to my item_Check()
   
    --MESSAGES SELECTED?
    if selectedItems is not missing value then
       
        --GET FILE COUNT
        my item_Count(selectedItems, the_class)
       
        --ANNOUNCE THE EXPORT OF ITEMS
        my process_Items(itemNum, attNum)
       
        --CHECK EVERNOTE ACCOUNT TYPE
        my account_Check()
       
        --PROCESS ITEMS FOR EXPORT
        my item_Process(selectedItems)
       
        --DELETE TEMP FOLDER IF IT EXISTS
        set success to my trashfolder(SaveLoc)
       
        --NO ITEMS SELECTED
    else
        set successCount to -1
    end if
   
    --Notify RESULTS
    my notify_results(successCount)
   
   
    -- ERROR HANDLING
on error errText number errNum
   
    if errNum is -128 then
        set notifTitle to "Outlook to Evernote"
        set notifSubtitle to "Failure Notification"
        set notifMessage to "User Cancelled - Failed to export!"
    else
        set notifTitle to "Outlook to Evernote"
        set notifSubtitle to "Failure Notification"
        set notifMessage to "Import Failure - " & errText
    end if
   
    display notification notifMessage with title notifTitle subtitle notifSubtitle
   
end try

(*
======================================
// PREPARATORY SUBROUTINES
=======================================
*)


--CHECK ACCOUNT TYPE
on account_Check()
    tell application "Evernote"
        set account_Info to (properties of account info 1)
        set account_Type to (account type of account_Info) as text
        if EVnotebook is "" then set EVnotebook to my default_Notebook()
    end tell
end account_Check

--SET UP ACTIVITIES
on item_Check()
    --set myPath to (path to home folder)
    tell application id "com.microsoft.Outlook"
        try -- GET MESSAGES
            set selectedItems to selection
            set raw_Class to (class of selectedItems)
            if raw_Class is list then
                set classList to {}
                repeat with selectedItem in selectedItems
                    copy class of selectedItem to end of classList
                end repeat
                if classList contains task then
                    set the_class to "Task"
                else
                    set raw_Class to (class of item 1 of selectedItems)
                end if
            end if
            if raw_Class is calendar event then set the_class to "Calendar"
            if raw_Class is note then set the_class to "Note"
            if raw_Class is task then set the_class to "Task"
            if raw_Class is contact then set the_class to "Contact"
            if raw_Class is incoming message then set the_class to "Message"
            if raw_Class is text then set the_class to "Text"
            if defaultTag is "" then set defaultTag to the_class
        end try
        return selectedItems
    end tell
end item_Check

--GET COUNT OF ITEMS AND ATTACHMENTS
on item_Count(selectedItems)
    tell application id "com.microsoft.Outlook"
        if the_class is not "Text" then
            set itemNum to count of selectedItems
            set attNum to 0
            try
                repeat with selectedMessage in selectedItems
                    set attNum to attNum + (count of attachment of selectedMessage)
                end repeat
            end try
        else
            set itemNum to 1
        end if
    end tell
end item_Count

(*
======================================
// PROCESS OUTLOOK ITEMS SUBROUTINE
======================================
*)


on item_Process(selectedItems)
    tell application id "com.microsoft.Outlook"
       
        --TAGGING?
        if tagging_Switch is "ON" then my tagging_Dialog()
       
        --TEXT CLIPPING?
        if (class of selectedItems) is text then
            set EVTitle to "Text Clipping from Outlook"
            set theContent to selectedItems
            --CREATE IN EVERNOTE
            tell application "Evernote"
                set theNote to create note with text theContent title EVTitle notebook EVnotebook
                if EVTag is not {} then assign EVTag to theNote
            end tell
           
            --ITEM HAS FINISHED -- COUNT IT AS A SUCCESS!
            set successCount to 1
        else
            -- GET OUTLOOK ITEM INFORMATION
            repeat with selectedItem in selectedItems
                try
                    set theAttachments to attachments of selectedItem
                    set raw_Attendees to attendees of selectedItem
                end try
               
                try
                    set t_List to {}
                    set c_List to {}
                   
                    --LOOK FOR "TO: RECIPIENTS" AND MAKE LIST
                    set t_Recipients to (to recipients of selectedItem)
                    set t_Count to (count of t_Recipients)
                    set t_Mult to ", "
                    repeat with t_Recipient in t_Recipients
                        set t_Completed to false
                        if t_Count is 1 then set t_Mult to ""
                        set t_Address to (email address of t_Recipient)
                        try
                            set t_Name to (name of t_Address)
                            set t_List to t_List & {t_Name & " (" & (address of t_Address) & ")" & t_Mult} as string
                            set t_Completed to true
                        end try
                        if t_Completed is false then
                            set t_List to t_List & {(address of t_Address) & t_Mult} as string
                        end if
                        set t_Count to (t_Count - 1)
                    end repeat
                   
                   
                   
                    --LOOK FOR "CC: RECIPIENTS" AND MAKE LIST
                    set c_Recipients to (cc recipients of selectedItem)
                    set c_Count to (count of c_Recipients)
                    set c_Mult to ", "
                    repeat with c_Recipient in c_Recipients
                        set c_Completed to false
                        if c_Count is 1 then set c_Mult to ""
                        set c_Address to (email address of c_Recipient)
                        try
                            set c_Name to (name of c_Address)
                            set c_List to c_List & {c_Name & " (" & (address of c_Address) & ")" & c_Mult} as string
                            set c_Completed to true
                        end try
                        if c_Completed is false then
                            set c_List to c_List & {(address of c_Address) & c_Mult} as string
                        end if
                        set c_Count to (c_Count - 1)
                    end repeat
                   
                end try
               
                set selectedItem to (properties of selectedItem)
                set the_vCard to {}
                set the_notes to ""
               
                --WHAT KIND OF ITEM IS IT?
                if the_class is "Calendar" then
                   
                    (* // CALENDAR ITEM *)
                   
                    --PREPARE THE TEMPLATE 
                    --LEFT SIDE (FORM FIELDS)
                    set l_1 to "Event:"
                    set l_2 to "Start Time:"
                    set l_3 to "End Time:"
                    set l_4 to "Location:"
                    set l_5 to "Notes:"
                   
                    --RIGHT SIDE (DATA FIELDS)
                    set r_1 to (subject of selectedItem)
                    set r_2 to (start time of selectedItem)
                    set r_3 to (end time of selectedItem)
                    set the_Location to (location of selectedItem)
                    if the_Location is missing value then set the_Location to "None"
                    set r_4 to the_Location
                   
                    --THE NOTES
                    set the_notes to ""
                    set item_Created to (current date)
                    try
                        set the_notes to (content of selectedItem)
                    end try
                    if the_notes is missing value then set the_notes to ""
                   
                    --ADD ORGANIZER / ATTENDEE INFO IF IT'S A MEETING
                    if (count of raw_Attendees) > 0 then
                        set the_Organizer to "<strong>Organized By: </strong><br/>" & (organizer of selectedItem) & "<br/><br/>"
                        set the_Attendees to "<strong>Invited Attendees: </strong><br/>"
                        repeat with raw_Attendee in raw_Attendees
                           
                            --GET ATTENDEE DATA
                            set raw_EmailAttendee to (email address of raw_Attendee)
                            set attend_Name to (name of raw_EmailAttendee) as text
                            set raw_Status to (status of raw_Attendee)
                           
                            --COERCE STATUS TO TEXT
                            if raw_Status contains not responded then
                                set attend_Status to "Not Responded"
                            else if raw_Status contains accepted then
                                set attend_Status to "Accepted"
                            else if raw_Status contains declined then
                                set attend_Status to "Declined"
                            else if raw_Status contains tentatively accepted then
                                set attend_Status to "Tentatively Accepted"
                            end if
                           
                            --COMPILE THE ATTENDEE DATA
                            set attend_String to attend_Name & " (" & attend_Status & ")<br/>"
                            set the_Attendees to the_Attendees & attend_String
                        end repeat
                        set the_notes to (the_Organizer & the_Attendees & the_notes)
                        set raw_Attendees to ""
                    end if
                   
                    --ASSEMBLE THE TEMPLATE
                    set theContent to my make_Template(l_1, l_2, l_3, l_4, l_5, r_1, r_2, r_3, r_4, the_notes)
                   
                    --EXPORT VCARD DATA
                    try
                        set vcard_data to (icalendar data of selectedItem)
                        set vcard_extension to ".ics"
                        set the_vCard to my write_File(r_1, vcard_data, vcard_extension)
                    end try
                   
                    set theHTML to true
                    set EVTitle to r_1
                   
                    (* // NOTE ITEM *)
                else if the_class is "note" then
                   
                    --PREPARE THE TEMPLATE 
                    --LEFT SIDE (FORM FIELDS)
                    set l_1 to "Note:"
                    set l_2 to "Creation Date:"
                    set l_3 to "Category"
                    set l_4 to ""
                    set l_5 to "Notes:"
                   
                    --RIGHT SIDE (DATA FIELDS)
                    set r_1 to name of selectedItem
                    set item_Created to creation date of selectedItem
                    set r_2 to (item_Created as text)
                   
                    --GET CATEGORY INFO
                    set the_Cats to (category of selectedItem)
                    set list_Cats to {}
                    set count_Cat to (count of the_Cats)
                    repeat with the_Cat in the_Cats
                        set cat_Name to (name of the_Cat as text)
                        copy cat_Name to the end of list_Cats
                        if count_Cat > 1 then
                            copy ", " to the end of list_Cats
                            set count_Cat to (count_Cat - 1)
                        else
                            set count_Cat to (count_Cat - 1)
                        end if
                    end repeat
                   
                    set r_3 to list_Cats
                    set r_4 to ""
                   
                    set item_Created to creation date of selectedItem
                   
                    --THE NOTES
                    try
                        set the_notes to content of selectedItem
                    end try
                    if the_notes is missing value then set the_notes to ""
                   
                    --ASSEMBLE THE TEMPLATE
                    set theContent to my make_Template(l_1, l_2, l_3, l_4, l_5, r_1, r_2, r_3, r_4, the_notes)
                   
                    --EXPORT VCARD DATA
                    set vcard_data to (icalendar data of selectedItem)
                    set vcard_extension to ".ics"
                    set the_vCard to my write_File(r_1, vcard_data, vcard_extension)
                   
                    set theHTML to true
                    set EVTitle to r_1
                   
                    (* // CONTACT ITEM *)
                else if the_class is "contact" then
                   
                    --PREPARE THE TEMPLATE 
                    --LEFT SIDE (FORM FIELDS)
                    set l_1 to "Name:"
                    set l_2 to "Email:"
                    set l_3 to "Phone:"
                    set l_4 to "Address:"
                    set l_5 to "Notes:"
                   
                    --GET EMAIL INFO
                    try
                        set list_Addresses to {}
                        set email_Items to (email addresses of selectedItem)
                        repeat with email_Item in email_Items
                            set the_Type to (type of email_Item as text)
                            set addr_Item to (address of email_Item) & " (" & my TITLECASE(the_Type) & ")<br />" as text
                            copy addr_Item to the end of list_Addresses
                        end repeat
                    end try
                   
                    --GET PHONE INFO AND ENCODE TELEPHONE LINK
                    try
                        set list_Phone to {}
                        if business phone number of selectedItem is not missing value then
                            set b_Number to (business phone number of selectedItem)
                            set b_String to "<strong>Work: </strong><a href=\"tel:\\" & b_Number & "\">" & b_Number & "</a><br /><br />"
                            copy b_String to end of list_Phone
                        end if
                        if home phone number of selectedItem is not missing value then
                            set h_Number to (home phone number of selectedItem)
                            set h_String to "<p><strong>Home: </strong><a href=\"tel:\\" & h_Number & "\">" & h_Number & "<br /><br />"
                            copy h_String to end of list_Phone
                        end if
                        if mobile number of selectedItem is not missing value then
                            set m_Number to (mobile number of selectedItem)
                            set m_String to "<p><strong>Mobile: </strong><a href=\"tel:\\" & m_Number & "\">" & m_Number & "<br /><br />"
                            copy m_String to end of list_Phone
                        end if
                    end try
                   
                    --GET ADDRESS INFO
                    try
                        set list_Addr to {}
                       
                        (*BUSINESS *)
                        if business street address of selectedItem is not missing value then
                            set b_Str to (business street address of selectedItem)
                            set b_gStr to my encodedURL(b_Str)
                            if (business city of selectedItem) is not missing value then
                                set b_Cit to (business city of selectedItem)
                                set b_gCit to my encodedURL(b_Cit)
                            else
                                set b_Cit to ""
                                set b_gCit to ""
                            end if
                            if (business state of selectedItem) is not missing value then
                                set b_Sta to (business state of selectedItem)
                                set b_gSta to my encodedURL(b_Sta)
                            else
                                set b_Sta to ""
                                set b_gSta to ""
                            end if
                            if (business zip of selectedItem) is not missing value then
                                set b_Zip to (business zip of selectedItem)
                                set b_gZip to my encodedURL(b_Zip)
                            else
                                set b_Zip to ""
                                set b_gZip to ""
                            end if
                            if (business country of selectedItem) is not missing value then
                                set b_Cou to (business country of selectedItem)
                                set b_gCou to my encodedURL(b_Cou)
                            else
                                set b_Cou to ""
                                set b_gCou to ""
                            end if
                            set b_Addr to b_Str & "<br/>" & b_Cit & ", " & b_Sta & "  " & b_Zip & "<br/>" & b_Cou
                           
                            --GOOGLE MAPS LOCATION IN URL
                            set b_gString to b_gStr & "," & b_gCit & "," & b_gSta & "," & b_gZip & "," & b_gCou
                            set b_GMAP to "http://maps.google.com/maps?q=" & b_gString
                            set b_String to "<strong>Work: </strong><br /><a href=\"" & b_GMAP & "\">" & b_Addr & "</a><br /><br />"
                            copy b_String to end of list_Addr
                        end if
                       
                        (*HOME *)
                        if home street address of selectedItem is not missing value then
                            set h_Str to (home street address of selectedItem)
                            set h_gStr to my encodedURL(h_Str)
                            if (home city of selectedItem) is not missing value then
                                set h_Cit to (home city of selectedItem)
                                set h_gCit to my encodedURL(h_Cit)
                            else
                                set h_Cit to ""
                                set h_gCit to ""
                            end if
                            if (home state of selectedItem) is not missing value then
                                set h_Sta to (home state of selectedItem)
                                set h_gSta to my encodedURL(h_Sta)
                            else
                                set h_Sta to ""
                                set h_gSta to ""
                            end if
                            if (home zip of selectedItem) is not missing value then
                                set h_Zip to (home zip of selectedItem)
                                set h_gZip to my encodedURL(h_Zip)
                            else
                                set h_Zip to ""
                                set h_gZip to ""
                            end if
                            if (home country of selectedItem) is not missing value then
                                set h_Cou to (home country of selectedItem)
                                set h_gCou to my encodedURL(h_Cou)
                            else
                                set h_Cou to ""
                                set h_gCou to ""
                            end if
                            set h_Addr to h_Str & "<br/>" & h_Cit & ", " & h_Sta & "  " & h_Zip & "<br/>" & h_Cou
                           
                            --GOOGLE MAPS LOCATION IN URL
                            set h_gString to h_gStr & "," & h_gCit & "," & h_gSta & "," & h_gZip & "," & h_gCou
                            set h_GMAP to "http://maps.google.com/maps?q=" & h_gString
                            set h_String to "<strong>Home: </strong><br /><a href=\"" & h_GMAP & "\">" & h_Addr & "</a><br />"
                            copy h_String to end of list_Addr
                        end if
                    end try
                   
                    --RIGHT SIDE (DATA FIELDS)
                    set r_1 to (display name of selectedItem)
                    set r_2 to (list_Addresses as string)
                    set r_3 to (list_Phone as text)
                    set r_4 to (list_Addr as text)
                   
                    --EXPORT VCARD DATA
                    set vcard_data to (vcard data of selectedItem)
                    set vcard_extension to ".vcf"
                    set item_Created to (current date)
                   
                    --THE NOTES
                    try
                        set the_notes to plain text note of selectedItem
                        if the_notes is missing value then set the_notes to ""
                    end try
                   
                    --ASSEMBLE THE TEMPLATE
                    set theContent to my make_Template(l_1, l_2, l_3, l_4, l_5, r_1, r_2, r_3, r_4, the_notes)
                    set the_vCard to my write_File(r_1, vcard_data, vcard_extension)
                   
                    set theHTML to true
                    set EVTitle to r_1
                   
                    (* // TASK ITEM *)
                else if the_class is "task" then
                   
                    --PREPARE THE TEMPLATE 
                    --LEFT SIDE (FORM FIELDS)
                    set l_1 to "Note:"
                    set l_2 to "Priority:"
                    set l_3 to "Due Date:"
                    set l_4 to "Status:"
                    set l_5 to "Notes:"
                   
                    --RIGHT SIDE (DATA FIELDS)
                    set propClass to (class of selectedItem) as text
                    if propClass is "incoming message" then
                        set r_1 to (subject of selectedItem)
                    else
                        set r_1 to (name of selectedItem)
                    end if
                    set the_Priority to (priority of selectedItem)
                    if the_Priority is priority normal then set r_2 to "Normal"
                    if the_Priority is priority high then set r_2 to "High"
                    if the_Priority is priority low then set r_2 to "Low"
                   
                    set r_3 to (due date of selectedItem)
                    set item_Created to (current date)
                   
                    --TODO?
                    try
                        set todo_Flag to (todo flag of selectedItem) as text
                        set r_4 to my TITLECASE(todo_Flag)
                    end try
                   
                    --THE NOTES
                    try
                        if content of selectedItem is missing value then
                            set the_notes to plain text content of selectedItem
                        else
                            set the_notes to content of selectedItem
                        end if
                       
                    end try
                    if the_notes is missing value then set the_notes to ""
                   
                    --ASSEMBLE THE TEMPLATE
                    set theContent to my make_Template(l_1, l_2, l_3, l_4, l_5, r_1, r_2, r_3, r_4, the_notes)
                   
                    --EXPORT VCARD DATA
                    if propClass is not "incoming message" then
                        set vcard_extension to ".ics"
                        set vcard_data to (icalendar data of selectedItem)
                        set the_vCard to my write_File(r_1, vcard_data, vcard_extension)
                    end if
                   
                    set theHTML to true
                    set EVTitle to r_1
                   
                    (* // MESSAGE ITEM *)
                else
                    --PREPARE THE TEMPLATE 
                    --LEFT SIDE (FORM FIELDS)
                    set l_1 to "From: / To: / CC: "
                    set l_2 to "Subject:"
                    set l_3 to "Date:"
                    set l_4 to "Category:"
                    set l_5 to "Email Contents:"
                   
                    --GET EMAIL INFO
                    set the_Sender to (sender of selectedItem)
                    set s_Name to (address of the_Sender)
                    set s_Address to (address of the_Sender)
                   
                    --REPLACE WITH NAME, IF AVAILABLE
                    try
                        set s_Name to (name of the_Sender)
                    end try
                   
                    set sender_Link to "<a href=\"mailto:" & s_Address & "\">" & s_Name & " (" & s_Address & ")</a>"
                   
                    --GET CATEGORY INFO
                    set the_Cats to (category of selectedItem)
                    set list_Cats to {}
                    set count_Cat to (count of the_Cats)
                    repeat with the_Cat in the_Cats
                        set cat_Name to (name of the_Cat as text)
                        copy cat_Name to the end of list_Cats
                        if count_Cat > 1 then
                            copy ", " to the end of list_Cats
                            set count_Cat to (count_Cat - 1)
                        else
                            set count_Cat to (count_Cat - 1)
                        end if
                    end repeat
                   
                    --RIGHT SIDE (DATA FIELDS)
                    set r_1 to "From: " & sender_Link & "<hr/>To: " & t_List & "<hr/>CC: " & c_List
                   
                    set m_Sub to (subject of selectedItem)
                    if m_Sub is missing value then
                        set r_2 to "<No Subject>"
                    else
                        set r_2 to {subject of selectedItem}
                    end if
                    set r_3 to (time sent of selectedItem)
                    set r_4 to list_Cats
                   
                    set theID to id of selectedItem as string
                    set item_Created to r_3
                    set EVTitle to r_2
                   
                    --PROCESS EMAIL CONTENT
                    set m_Content to content of selectedItem
                    set theHTML to has html of selectedItem
                    --set m_Content to plain text content of selectedItem
                    --set theHTML to false
                   
                   
                    --IF PLAINTEXT EMAIL CONTENT…
                    if theHTML is false then
                        set theContent to "Name: " & s_Name & return & "Subject: " & r_2 & return & "Sent: " & r_3 & return & return & return & return & m_Content
                        --IF HTML EMAIL CONTENT…
                    else
                        set the_notes to m_Content
                        --ASSEMBLE THE TEMPLATE
                        set theContent to my make_Template(l_1, l_2, l_3, l_4, l_5, r_1, r_2, r_3, r_4, the_notes)
                       
                        if stripEmbeddedImages is "ON" then
                            --REMOVE ANY EMBEDDED IMAGE RERENCES
                            set theContent to my stripCID(theContent)
                        end if
                    end if
                end if
               
                --CREATE NOTE IN EVERNOTE (FINALLY!)
                if theHTML is true then
                    tell application "Evernote"
                        set theNote to create note with html theContent title EVTitle notebook EVnotebook
                        if EVTag is not {} then assign EVTag to theNote
                        set creation date of theNote to item_Created
                       
                        --ATTACH VCARD (IF PRESENT)
                        if the_vCard is not {} then tell theNote to append attachment file the_vCard
                    end tell
                else
                    tell application "Evernote"
                        set theNote to create note with text theContent title EVTitle notebook EVnotebook
                        if EVTag is not {} then assign EVTag to theNote
                        set creation date of theNote to item_Created
                       
                        --ATTACH VCARD (IF PRESENT)
                        if the_vCard is not {} then tell theNote to append attachment file the_vCard
                    end tell
                end if
               
                --IF ATTACHMENTS PRESENT, RUN ATTACHMENT SUBROUTINE
                if theAttachments is not {} then my message_Attach(theAttachments, selectedItem, theNote)
               
                --ITEM HAS FINISHED! COUNT IT AS A SUCCESS AND RESET ATTACHMENTS!
                set successCount to successCount + 1
                set theAttachments to {}
            end repeat
        end if
    end tell
end item_Process


(*
======================================
// UTILITY SUBROUTINES
======================================
*)

--URL ENCODE
on encodedURL(the_Word)
    set scpt to "php -r 'echo urlencode(\"" & the_Word & "\");'"
    return do shell script scpt
end encodedURL

--TITLECASE
on TITLECASE(txt)
    return do shell script "python -c \"import sys; print unicode(sys.argv[1], 'utf8').title().encode('utf8')\" " & quoted form of txt
end TITLECASE

--SORT SUBROUTINE
on simple_sort(my_list)
    set the index_list to {}
    set the sorted_list to {}
    repeat (the number of items in my_list) times
        set the low_item to ""
        repeat with i from 1 to (number of items in my_list)
            if i is not in the index_list then
                set this_item to item i of my_list as text
                if the low_item is "" then
                    set the low_item to this_item
                    set the low_item_index to i
                else if this_item comes before the low_item then
                    set the low_item to this_item
                    set the low_item_index to i
                end if
            end if
        end repeat
        set the end of sorted_list to the low_item
        set the end of the index_list to the low_item_index
    end repeat
    return the sorted_list
end simple_sort

--REPLACE
on replaceString(theString, theOriginalString, theNewString)
    set theNum to 0
    set {od, AppleScript's text item delimiters} to {AppleScript's text item delimiters, theOriginalString}
    set theStringParts to text items of theString
    if (count of theStringParts) is greater than 1 then
        set theString to text item 1 of theStringParts as string
        repeat with eachPart in items 2 thru -1 of theStringParts
            set theString to theString & theNewString & eachPart as string
            set theNum to theNum + 1
        end repeat
    end if
    set AppleScript's text item delimiters to od
    return theString
end replaceString

--REMOVE EMBEDDED IMAGE REFERENCES
on stripCID(theContent)
    set theCommandString to "echo " & quoted form of theContent & " | sed 's/\"cid:.*\"/\"\"/'"
    set theResult to do shell script theCommandString
    return theResult
end stripCID

(*
======================================
// TAGGING SUBROUTINES
======================================
*)


--TAGGING AND NOTEBOOK SELECTION DIALOG
on tagging_Dialog()
    display dialog "Enter The Tag or Tags Below." & return & ¬
        "(NOTE: Multiple Tags Should Be Separated By Commas)" with title "Outlook to Evernote Export" default answer defaultTag ¬
        buttons {"Create in Default Notebook", "Select Notebook from List", "Cancel"} ¬
        default button "Create in Default Notebook" cancel button ¬
        "Cancel" with icon path to resource "Evernote.icns" in bundle (path to application "Evernote")
    set dialogresult to the result
    set userInput to text returned of dialogresult
    set ButtonSel to button returned of dialogresult
    set theDelims to {","}
    set userTag to my Tag_List(userInput, theDelims)
   
    --RESET, FINAL CHECK, AND FORMATTING OF TAGS
    set EVTag to {}
    set EVTag to my Tag_Check(userTag)
    if ButtonSel is "Select Notebook from List" then set EVnotebook to my Notebook_List()
end tagging_Dialog

--TAG SELECTION SUBROUTINE
on Tag_List(userInput, theDelims)
    set oldDelims to AppleScript's text item delimiters
    set theList to {userInput}
    repeat with aDelim in theDelims
        set AppleScript's text item delimiters to aDelim
        set newList to {}
        repeat with anItem in theList
            set newList to newList & text items of anItem
        end repeat
        set theList to newList
    end repeat
    set AppleScript's text item delimiters to oldDelims
    return theList
end Tag_List

--CREATES TAGS IF THEY DON'T EXIST
on Tag_Check(theTags)
    tell application "Evernote"
        set finalTags to {}
        repeat with theTag in theTags
           
            -- TRIM LEADING SPACE, IF ANY
            if (the character 1 of theTag is " ") then set theTag to text 2 thru end of theTag as text
           
            if (not (tag named theTag exists)) then
                try
                    set makeTag to make tag with properties {name:theTag}
                    set end of finalTags to makeTag
                end try
            else
                set end of finalTags to tag theTag
            end if
        end repeat
    end tell
    return finalTags
end Tag_Check

(*
======================================
// NOTEBOOK SUBROUTINES
======================================
*)


--GET EVERNOTE'S DEFAULT NOTEBOOK
on default_Notebook()
    tell application "Evernote"
        set get_defaultNotebook to every notebook whose default is true
        if EVnotebook is "" then
            set EVnotebook to name of (item 1 of get_defaultNotebook) as text
        end if
    end tell
end default_Notebook

--EVERNOTE NOTEBOOK SELECTION SUBROUTINE
on Notebook_List()
    tell application "Evernote"
        activate
        set listOfNotebooks to {} (*PREPARE TO GET EVERNOTE'S LIST OF NOTEBOOKS *)
        set EVNotebooks to every notebook (*GET THE NOTEBOOK LIST *)
        repeat with currentNotebook in EVNotebooks
            set currentNotebookName to (the name of currentNotebook)
            copy currentNotebookName to the end of listOfNotebooks
        end repeat
        set Folders_sorted to my simple_sort(listOfNotebooks) (*SORT THE LIST *)
        set SelNotebook to choose from list of Folders_sorted with title "Select Evernote Notebook" with prompt ¬
            "Current Evernote Notebooks" OK button name "OK" cancel button name "New Notebook" (*USER SELECTION FROM NOTEBOOK LIST *)
        if (SelNotebook is false) then (*CREATE NEW NOTEBOOK OPTION *)
            set userInput to ¬
                text returned of (display dialog "Enter New Notebook Name:" default answer "")
            set EVnotebook to userInput
        else
            set EVnotebook to item 1 of SelNotebook
        end if
    end tell
end Notebook_List

(*
======================================
// ATTACHMENT SUBROUTINES
=======================================
*)


--CLEAN TITLE FOR FILENAME
on clean_Title(rawFileName)
    set previousDelimiter to AppleScript's text item delimiters
    set potentialName to rawFileName
    set legalName to {}
    set illegalCharacters to {".", ",", "/", ":", "[", "]"}
    repeat with thisCharacter in the characters of potentialName
        set thisCharacter to thisCharacter as text
        if thisCharacter is not in illegalCharacters then
            set the end of legalName to thisCharacter
        else
            set the end of legalName to "_"
        end if
    end repeat
    return legalName
end clean_Title

--WRITE THE FILE
on write_File(r_1, vcard_data, vcard_extension)
    set ExportFolder to ((path to desktop folder) & "Temp Export From Outlook:") as string
    set SaveLoc to my f_exists(ExportFolder)
    set FileName to (my clean_Title(r_1) & vcard_extension)
    set theFileName to (ExportFolder & FileName)
    try
        open for access file theFileName with write permission
        write vcard_data to file theFileName as string
        close access file theFileName
        return theFileName
       
    on error errorMessage
        log errorMessage
        try
            close access file theFileName
        end try
    end try
end write_File

--FOLDER EXISTS
on f_exists(ExportFolder)
    try
        set myPath to (path to home folder)
        get ExportFolder as alias
        set SaveLoc to ExportFolder
    on error
        tell application "Finder" to make new folder with properties {name:"Temp Export From Outlook"}
    end try
end f_exists

--ATTACHMENT PROCESSING
on message_Attach(theAttachments, selectedItem, theNote)
   
    tell application id "com.microsoft.Outlook"
        --MAKE SURE TEXT ITEM DELIMITERS ARE DEFAULT
        set AppleScript's text item delimiters to ""
       
        --TEMP FILES PROCESSED ON THE DESKTOP
        set ExportFolder to ((path to desktop folder) & "Temp Export From Outlook:") as string
        set SaveLoc to my f_exists(ExportFolder)
       
        --PROCESS THE ATTCHMENTS
        set attCount to 0
        repeat with theAttachment in theAttachments
           
            set theFileName to ExportFolder & theAttachment's name
            try
                save theAttachment in file theFileName
            end try
            tell application "Evernote"
                tell theNote to append attachment file theFileName
            end tell
           
            --SILENT DELETE OF TEMP FILE
            set trash_Folder to path to trash folder from user domain
            do shell script "mv " & quoted form of POSIX path of theFileName & space & quoted form of POSIX path of trash_Folder
           
        end repeat
    end tell
   
end message_Attach

--SILENT DELETE OF TEMP FOLDER (THANKS MARTIN MICHEL!)
on trashfolder(SaveLoc)
    try
        set trashfolderpath to ((path to trash) as Unicode text)
        set srcfolderinfo to info for (SaveLoc as alias)
        set srcfoldername to name of srcfolderinfo
        set SaveLoc to (SaveLoc as alias)
        set SaveLoc to (quoted form of POSIX path of SaveLoc)
        set counter to 0
        repeat
            if counter is equal to 0 then
                set destfolderpath to trashfolderpath & srcfoldername & ":"
            else
                set destfolderpath to trashfolderpath & srcfoldername & " " & counter & ":"
            end if
            try
                set destfolderalias to destfolderpath as alias
            on error
                exit repeat
            end try
            set counter to counter + 1
        end repeat
        set destfolderpath to quoted form of POSIX path of destfolderpath
        set command to "ditto " & SaveLoc & space & destfolderpath
        do shell script command
        -- this won't be executed if the ditto command errors
        set command to "rm -r " & SaveLoc
        do shell script command
        return true
    on error
        return false
    end try
end trashfolder

(*
======================================
// NOTIFICATION SUBROUTINES
======================================
*)


--ANNOUNCE THE COUNT OF TOTAL ITEMS TO EXPORT
on process_Items(itemNum, attNum)
   
    set attPlural to "s"
   
    if attNum = 0 then
        set attNum to "No"
    else if attNum is 1 then
        set attPlural to ""
    end if
   
    set notifTitle to "Import to Evernote"
    set notifSubtitle to "Started - Processing " & itemNum & " " & " Item(s)"
    set notifText to "Including " & attNum & " Attachment" & attPlural
   
    display notification notifText with title notifTitle subtitle notifSubtitle
   
end process_Items

--NOTIFY RESULTS
on notify_results(successCount)
    if EVnotebook is "" then set EVnotebook to "Default"
   
    set notifTitle to ""
    set notifSubtitle to ""
    set notifMessage to ""
   
    set Plural_Test to (successCount) as number
   
    if Plural_Test is -1 then
        set notifTitle to "Outlook to Evernote"
        set notifSubtitle to "Failure Notification"
        set notifMessage to "Import failure - No Items Selected in Outlook!"
       
    else if Plural_Test is 0 then
        set notifTitle to "Outlook to Evernote"
        set notifSubtitle to "Failure Notification"
        set notifMessage to "No Items Exported From Outlook!"
       
    else
        set notifTitle to "Outlook to Evernote"
        set notifSubtitle to "Success Notification"
        set notifMessage to "Exported " & itemNum & " item(s) to " & EVnotebook & " notebook"
       
    end if
   
    display notification notifMessage with title notifTitle subtitle notifSubtitle
   
    set itemNum to "0"
    set EVnotebook to ""
   
end notify_results

(*
======================================
// TEMPLATE SUBROUTINES
======================================
*)

on make_Template(l_1, l_2, l_3, l_4, l_5, r_1, r_2, r_3, r_4, the_notes)
    --MAKE TASK TEMPLATE
    set the_Template to "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">
<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\"/></head><body><table BGCOLOR=\"#bbbbbb\" width=\"100%\" cellspacing=\"1\" cellpadding=\"1\" style=\"border: 1px solid #bbbbbb\">
<tbody>
<tr BGCOLOR=\"#ffffff\">
<td align=\"center\" ><font color=\"#424242\"><h4><strong>  "
& l_1 & "</strong></h4>  </td>
<td align=\"center\"  ><h4>"
& r_1 & "</h4></td>
</tr>

<tr BGCOLOR=\"#ffffff\">
<td align=\"center\" ><font color=\"#424242\"><h4><strong>  "
& l_2 & "</strong></h4>  </td>
<td align=\"center\" ><h4><strong>"
& r_2 & "</strong></h4></td>
</tr>

<tr BGCOLOR=\"#ffffff\">
<td align=\"center\" ><font color=\"#424242\"><h4><strong>  "
& l_3 & "</strong></h4></td>
<td align=\"center\" ><h4>"
& r_3 & "</h4></td>
</tr>

<tr BGCOLOR=\"#ffffff\">
<td align=\"center\" ><font color=\"#424242\"><h4><strong>  "
& l_4 & "</strong></h4></td>
<td align=\"center\" ><h4> "
& r_4 & "</h4></td>
</tr>
</tbody>
</table>
<hr />
<table border=\"1\" width=\"100%\" cellspacing=\"10\" cellpadding=\"10\">
<tbody>
<strong>"
& l_5 & "</strong><br /><br />" & the_notes & "</tbody></table></body></html>"
end make_Template