Apple Mail to Evernote 2.0 — English Language (BETA)

Description

This script has been replaced by a new version which is Lion Compatible! I've left this older version up for people who want to look at the MailTags code (which has been eliminated in the newer version)>

September 30, 2011 -- WARNINGS FOR LION (10.7) AND NON-GROWL USERS

This script doesn't work with Lion yet -- Apple changed a number of AppleScript-related things in 10.7's Mail.app and, long story short, many AppleScripts for Mail have stopped working (including this one). There doesn't seem to be a work-around so, in the meantime, you can let Apple know that you'd like them to fix the header and attachment-related AppleScript in Mail! I'll be posting updates to the Veritrope.com Twitter account, so be sure to follow me there for the latest!

GROWL ISSUES?

  • If you do not have GROWL installed, you'll likely get an "GrowlHelperApp" error. I had been testing a new approach to this, but it seems as if the GROWL app itself is making some changes to how it works. Therefore, I've decided to hold off on spending more time until the new method is released. (If you are feeling especially nerdy, read Dan Byler's excellent post on GROWL and AppleScript and you'll get some sense of how absolutely un-fun this has been to deal with!). As always, updates tend to get pre-announced on the Veritrope.com Twitter account, so be sure to follow the action there!

The Code

(*
http://veritrope.com
Apple Mail to Evernote
Version 2.0-BETA 2
February 4, 2011
Project Status, Latest Updates, and Comments Collected at:
http://veritrope.com/code/apple-mail-to-evernote-english-language-beta

// IMPORTANT NOTES
- If you do not have GROWL installed, you'll currently get an "GrowlHelperApp" error. I think I have a fix for this and -- if you're interested in testing it -- please send me a message:
1.) With the Veritrope.com Contact Form, located at http://veritrope.com/about-veritrope/contact/, or
2.) Via the Veritrope.com Twitter account -- @Veritrope

//INSTALLATION:
A few options....
-- You can highlight the email messages you want to archive into Evernote and double-click this script file;
-- You can save this script to /Library/Scripts/Mail Scripts and launch it using the system-wide script menu from the Mac OS X menu bar.
(The script menu can be activated using the AppleScript Utility application). Keyboard shortcuts can also be assigned to AppleScripts in the script menu using the System Preferences "Keyboard & Mouse Settings".

FastScripts Installation (Optional, but recommended):
-- Download and Install FastScripts from http://www.red-sweater.com/fastscripts/index.html
-- Set up your keyboard shortcut

* 2.00 b2
BUG FIXES (USER SWITCH FOR NOTEBOOK, BETTER BASE 64 DETECTION, ATTACHMENT FIX)

* 2.00 b1
HTML MESSAGES, APPEND ATTACHMENTS, MAILTAGS, QUIET TEMP FILE REMOVAL

* 1.30 (June 5, 2010)
ATTACHMENT CREATION. LAYING TRACK FOR HTML NOTES.

* 1.20 (July 25, 2009)
STREAMLINED MENU FOR NOTE EXPORT

* 1.10 (May 6, 2009)
ACTIVATED MESSAGE LINKING/ADDED EVERNOTE ICON TO DIALOG BOX/MISC. CLEAN-UP!

* 1.01 (April 23, 2009)
FIXED TYPOGRAPHICAL ERROR

* 1.00 (April 20, 2009)
INITIAL RELEASE OF SCRIPT
*)


(*
======================================
// 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 : "OFF"

--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 ("Email Message" IS DEFAULT)
property defaultTag : "Email Message"

(*
======================================
// OTHER PROPERTIES
======================================
*)

property successCount : 0
property growl_Running : "false"
property mailtags_Running : "false"
property account_Type : "free"
property free_extension_list : {"GIF", "JPG", "PNG", "WAV", "MP3", "PDF", "AMR"}
property free_audio_list : {"WAV", "MP3", "AMR"}
property free_image_list : {"GIF", "JPG", "PNG"}
property free_doc_list : {"PDF"}
property myTitle : "Mail Item"
property theMessages : {}
property thisMessage : ""
property itemNum : "0"
property attNum : "0"
property errNum : "0"
property userTag : ""
property EVTag : {}
property multiHTML : ""
property theSourceItems : {}
property mySource : ""
property decode_Success : ""
property finalHTML : ""
(*
======================================
// MAIN PROGRAM
======================================
*)

--RESET ITEMS
set successCount to "0"
set mailtags_Running to "false"
set AppleScript's text item delimiters to ""

try
--CHECK FOR GROWL
my Growl_Check()

--CHECK FOR MAILTAGS
my mailtags_Check()

--CHECK ACCOUNT TYPE
my account_Check()

--SET UP ACTIVITIES
my item_Check()

--MESSAGES SELECTED?
if theMessages is not {} then

--GET FILE COUNT
my item_Count(theMessages)

--ANNOUNCE THE EXPORT OF ITEMS
my process_Items(itemNum, attNum)

--PROCESS MAIL ITEMS FOR EXPORT
my mail_Process(theMessages)

else
--NO MESSAGES SELECTED
set successCount to -1
end if

--GROWL RESULTS
my growl_Growler(growl_Running, successCount)

-- ERROR HANDLING
on error errText number errNum
if growl_Running is true then
if errNum is -128 then
-- GROWL FAILURE FOR CANCEL
tell application "GrowlHelperApp"
notify with name ¬
"Failure Notification" title ¬
"User Cancelled" description ¬
"Failed to export!" application name "Mail to Evernote"
end tell
else
-- GROWL FAILURE FOR ERROR
tell application "GrowlHelperApp"
notify with name ¬
"Failure Notification" title ¬
"Import Failure" description "Failed to export " & return & myTitle & ¬
"" due to the following error: " & return & errText ¬
application name "
Mail to Evernote"
end tell

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

(* ======================================
// HANDLER SUBROUTINES
=======================================*)
--APP DETECT
on appIsRunning(appName)
tell application "
System Events" to (name of processes) contains appName
end appIsRunning

--CHECK FOR MAILTAGS
on mailtags_Check()
if appIsRunning("
MailTagsScriptingSupport") then
set mailtags_Running to true
end if
end mailtags_Check

--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
end tell
end account_Check

--SET UP ACTIVITIES
on item_Check()
set myPath to (path to home folder)
tell application "
Mail"
try
set theMessages to selection
end try
end tell
end item_Check

--GET COUNT OF ITEMS AND ATTACHMENTS
on item_Count(theMessages)
tell application "
Mail"
set itemNum to count of theMessages
set attNum to 0
repeat with theMessage in theMessages
set attNum to attNum + (count of mail attachment of theMessage)
end repeat
end tell
end item_Count

(* ======================================
// TAGGING AND NOTEBOOK SUBROUTINES
=======================================*)
--TAGGING AND NOTEBOOK SELECTION DIALOG
on tagging_Dialog()
display dialog "
" & ¬
"
Enter Your Tags (separated by colons or commas)" with title "Apple Mail 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)
if ButtonSel is "
Select Notebook from List" then set EVnotebook to my Notebook_List()
end tagging_Dialog

--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

--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

--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

(* ======================================
// UTILITY SUBROUTINES
=======================================*)
-- EXTRACTION SUBROUTINE
on extractBetween(SearchText, startText, endText)
set tid to AppleScript's text item delimiters
set AppleScript's text item delimiters to startText
set endItems to text of text item -1 of SearchText
set AppleScript's text item delimiters to endText
set beginningToEnd to text of text item 1 of endItems
set AppleScript's text item delimiters to tid
return beginningToEnd
end extractBetween

--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

(* ======================================
// PROCESS MAIL ITEMS SUBROUTINE
=======================================*)
on mail_Process(theMessages)
--CHECK DEFAULT NOTEBOOK
my default_Notebook()
tell application "
Mail"
try
if tagging_Switch is "
ON" then my tagging_Dialog()

repeat with thisMessage in theMessages
try
--GET MESSAGE INFO
set myTitle to the subject of thisMessage
set myContent to the content of thisMessage
set mySource to the source of thisMessage
set ReplyAddr to the reply to of thisMessage
set EmailDate to the date received of thisMessage
set theRecipient to "
"
set ex to "
"
set MsgLink to "
"
try
set theRecipient to "
"
set theRecipient to the address of to recipient 1 of thisMessage
set MsgLink to "
message://%3c" & thisMessage's message id & "%3e"
if theRecipient is not "
" then set ex to my extractBetween(ReplyAddr, " end try

--MAILTAGS SUPPORT
if mailtags_Running is true then
using terms from application "MailTagsScriptingSupport"
set oldDelims to AppleScript's text item delimiters
set AppleScript's text item delimiters to ","
set userTags to userTag as list
try
set MailTags to {keywords of item 1 of thisMessage}
set MailTag to item 1 of MailTags as list
set FinalTags to {}
set FinalTags to userTags & MailTag as list
set EVTag to FinalTags
set AppleScript's text item delimiters to oldDelims
end try
end using terms from
else
set EVTag to (words of userTag)
end if

--HTML EMAIL
set myHeaders to content of header "content-type" of thisMessage
set theBoundary to my extractBetween(mySource, "boundary="", """)
set theMessageEnd to ("--" & theBoundary & return & "Content-Type:")
set theMessageStart to (return & "--" & theBoundary)
set paraSource to paragraphs of mySource
set myHeaderlines to paragraphs of (all headers of thisMessage as text)
set cutSource to my stripHeader(paraSource, myHeaderlines)
set evHTML to cutSource
end try

--MAKE HEADER TEMPLATE
set the_Template to "
<table width="
\&quot;100%\&quot;" border="\&quot;1\&quot;" cellspacing="\&quot;0\&quot;" cellpadding="\&quot;2\&quot;">
<tbody>
<tr bgcolor="
\&quot;#ffffff\&quot;">
<td valign="
\&quot;top\&quot;"><span><strong>From: </strong> </span></td>
<td valign="
\&quot;top\&quot;"><a href="\&quot;mailto:&quot;">" &amp; ex &amp; "</a></td>
</tr>
<tr bgcolor="
\&quot;#ffffff\&quot;">
<td valign="
\&quot;top\&quot;"><span><strong>Subject: </strong> </span></td>
<td valign="
\&quot;top\&quot;"><strong>" &amp; myTitle &amp; "</strong></td>
</tr>
<tr bgcolor="
\&quot;#ffffff\&quot;">
<td valign="
\&quot;top\&quot;"><span><strong>Date / Time: </strong></span></td>
<td valign="
\&quot;top\&quot;">" &amp; EmailDate &amp; "</td>
</tr>
<tr bgcolor="
\&quot;#ffffff\&quot;">
<td valign="
\&quot;top\&quot;"><span><strong>To:</strong></span></td>
<td valign="
\&quot;top\&quot;">" &amp; theRecipient &amp; "</td>
</tr>
</tbody>
</table>

<hr />

"


--SEND ITEM TO EVERNOTE SUBROUTINE
my make_Evernote(myTitle, EVTag, EmailDate, MsgLink, myContent, mySource, theBoundary, theMessageStart, theMessageEnd, myHeaders, thisMessage, evHTML, EVnotebook, the_Template)

end repeat
end try
end tell
end mail_Process

(* ======================================
// MAKE ITEM IN EVERNOTE SUBROUTINE
=======================================*)

on make_Evernote(myTitle, EVTag, EmailDate, MsgLink, myContent, mySource, theBoundary, theMessageStart, theMessageEnd, myHeaders, thisMessage, evHTML, EVnotebook, the_Template)
tell application "Evernote"
try
--IS IT A TEXT EMAIL?
if myHeaders contains "text/plain" then
set n to create note with html the_Template title myTitle tags EVTag notebook EVnotebook
tell n to append text myContent
set creation date of n to EmailDate
set source URL of n to MsgLink

--IS IT MULTIPART ALTERNATIVE?
else if myHeaders contains "multipart/alternative;" then
--CHECK FOR BASE64
set base64Detect to false
set base64MsgStr to "Content-Transfer-Encoding: base64"
set base64ContentType to "Content-Type: text"
set base64MsgOffset to offset of base64MsgStr in mySource
set base64ContentOffset to offset of base64ContentType in mySource
set base64Offset to base64MsgOffset - base64ContentOffset as real
set theOffset to base64Offset as number
if theOffset is not greater than or equal to 50 then
if theOffset is greater than -50 then set base64Detect to true
end if
if base64Detect is true then
set multiHTML to my extractBetween(mySource, "Content-Transfer-Encoding: base64", theBoundary)
set baseHTML to do shell script "echo " &amp; (quoted form of multiHTML) &amp; "| openssl base64 -d"
set n to create note with html baseHTML title myTitle tags EVTag notebook EVnotebook
set creation date of n to EmailDate
set source URL of n to MsgLink
else
set finalHTML to my htmlFix(mySource, theBoundary, myContent)
if decode_Success is true then
set n to create note with html finalHTML title myTitle tags EVTag notebook EVnotebook
set creation date of n to EmailDate
set source URL of n to MsgLink
else
set n to create note with html the_Template title myTitle tags EVTag notebook EVnotebook
tell n to append text myContent
set creation date of n to EmailDate
set source URL of n to MsgLink
end if
end if

--IS IT MULTIPART MIXED?
else if myHeaders contains "multipart" then
if mySource contains "Content-Type: text/html" then
set finalHTML to my htmlFix(mySource, theBoundary, myContent)
if decode_Success is true then
set n to create note with html finalHTML title myTitle tags EVTag notebook EVnotebook
set creation date of n to EmailDate
set source URL of n to MsgLink
else
set n to create note with html the_Template title myTitle tags EVTag notebook EVnotebook
tell n to append text myContent
set creation date of n to EmailDate
set source URL of n to MsgLink
end if
else if mySource contains "text/plain" then
set n to create note with html the_Template title myTitle tags EVTag notebook EVnotebook
tell n to append text myContent
set creation date of n to EmailDate
set source URL of n to MsgLink

end if -- MULTIPART MIXED

--OTHER TYPES OF HTML-ENCODING
else
set multiHTML to my extractBetween(evHTML, "", "")
set finalHTML to my htmlFix(multiHTML, theBoundary, myContent) as text
set n to create note with html finalHTML title myTitle tags EVTag notebook EVnotebook
set creation date of n to EmailDate
set source URL of n to MsgLink

--END OF MESSAGE PROCESSING
end if

--START OF ATTACHMENT PROCESSING
tell application "Mail"
--IF ATTACHMENTS PRESENT, RUN ATTACHMENT SUBROUTINE
if thisMessage's mail attachments is not {} then my attachment_process(thisMessage, n)
end tell
--ITEM HAS FINISHED! COUNT IT AS A SUCCESS!
set successCount to successCount + 1
end try
end tell
end make_Evernote

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

--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 Mail"}
end try
end f_exists

--ATTACHMENT PROCESSING
on attachment_process(thisMessage, n)
tell application "Mail"
--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) &amp; "Temp Export From Mail:") as string
set SaveLoc to my f_exists(ExportFolder)

--PROCESS THE ATTCHMENTS
set theAttachments to thisMessage's mail attachments
set attCount to 0
repeat with theAttachment in theAttachments
set theFileName to ExportFolder &amp; theAttachment's name
try
save theAttachment in theFileName
end try
tell application "Evernote"
tell n 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 " &amp; quoted form of POSIX path of theFileName &amp; space &amp; quoted form of POSIX path of trash_Folder

end repeat

--SILENT DELETE OF TEMP FOLDER
set success to my trashfolder(SaveLoc)

end tell
end attachment_process

--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 quoted form of POSIX path of SaveLoc
set counter to 0
repeat
if counter is equal to 0 then
set destfolderpath to trashfolderpath &amp; srcfoldername &amp; ":"
else
set destfolderpath to trashfolderpath &amp; srcfoldername &amp; " " &amp; counter &amp; ":"
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 " &amp; SaveLoc &amp; space &amp; destfolderpath
do shell script command
-- this won't be executed if the ditto command errors
set command to "rm -r " &amp; SaveLoc
do shell script command
return true
on error
return false
end try
end trashfolder

(* ======================================
// HTML CLEANUP SUBROUTINES
=======================================*)


--HEADER STRIP (THANKS DOMINIK!)
on stripHeader(paraSource, myHeaderlines)

-- FIND THE LAST NON-EMPTY HEADER LINE
set lastheaderline to ""
set n to count (myHeaderlines)
repeat while (lastheaderline = "")
set lastheaderline to item n of myHeaderlines
set n to n - 1
end repeat

-- COMPARE HEADER TO SOURCE
set sourcelength to (count paraSource)
repeat with n from 1 to sourcelength
if (item n of paraSource is equal to "") then exit repeat
end repeat

-- STRIP OUT THE HEADERS
set cutSourceItems to (items (n + 1) thru sourcelength of paraSource)
set oldDelims to AppleScript's text item delimiters
set AppleScript's text item delimiters to return
set cutSource to (cutSourceItems as text)
set AppleScript's text item delimiters to oldDelims

return cutSource

end stripHeader

--HTML FIX
on htmlFix(evHTML, theBoundary, myContent)

set oldDelims to AppleScript's text item delimiters
set multiHTML to evHTML as string

--TEST FOR / STRIP OUT HEADER
set paraSource to paragraphs of multiHTML
if item 1 of paraSource contains "Received:" then
set myHeaderlines to (item 1 of paraSource)
set multiHTML to my stripHeader(paraSource, myHeaderlines)
end if

set multiHTML to my extractBetween(multiHTML, "Content-Type: text/html;", "")

--TEST FOR / STRIP OUT CHARSET
set paraSource to paragraphs of multiHTML
if item 1 of paraSource contains "charset" then
set myHeaderlines to (item 1 of paraSource)
set multiHTML to my stripHeader(paraSource, myHeaderlines)
end if

--CLEAN CONTENT
set AppleScript's text item delimiters to theBoundary
set theSourceItems to text items of multiHTML
set AppleScript's text item delimiters to ""
set theEncoded to theSourceItems as text

set AppleScript's text item delimiters to "="
set theSourceItems to text items of theEncoded
set AppleScript's text item delimiters to "%"
set theEncoded to theSourceItems as text

set AppleScript's text item delimiters to "%""
set theSourceItems to text items of theEncoded
set AppleScript's text item delimiters to "
=""
set theEncoded to theSourceItems as text

set AppleScript's text item delimiters to "%" &amp; (ASCII character 13)
set theSourceItems to text items of theEncoded
set AppleScript's text item delimiters to ""
set theEncoded to theSourceItems as text

set AppleScript's text item delimiters to "%%"
set theSourceItems to text items of theEncoded
set AppleScript's text item delimiters to "%"
set theEncoded to theSourceItems as text

set AppleScript's text item delimiters to "%" &amp; (ASCII character 10)
set theSourceItems to text items of theEncoded
set AppleScript's text item delimiters to ""
set theEncoded to theSourceItems as text

set AppleScript's text item delimiters to "%0A"
set theSourceItems to text items of theEncoded
set AppleScript's text item delimiters to ""
set theEncoded to theSourceItems as text

set AppleScript's text item delimiters to "%09"
set theSourceItems to text items of theEncoded
set AppleScript's text item delimiters to ""
set theEncoded to theSourceItems as text

set AppleScript's text item delimiters to "%C2%A0"
set theSourceItems to text items of theEncoded
set AppleScript's text item delimiters to " "
set theEncoded to theSourceItems as text

set AppleScript's text item delimiters to "%20"
set theSourceItems to text items of theEncoded
set AppleScript's text item delimiters to " "
set theEncoded to theSourceItems as text

set AppleScript's text item delimiters to (ASCII character 10)
set theSourceItems to text items of theEncoded
set AppleScript's text item delimiters to ""
set theEncoded to theSourceItems as text

set AppleScript's text item delimiters to "="
set theSourceItems to text items of theEncoded
set AppleScript's text item delimiters to "="
set theEncoded to theSourceItems as text

set AppleScript's text item delimiters to "$"
set theSourceItems to text items of theEncoded
set AppleScript's text item delimiters to "$"
set theEncoded to theSourceItems as text

set AppleScript's text item delimiters to "'"
set theSourceItems to text items of theEncoded
set AppleScript's text item delimiters to "'"
set theEncoded to theSourceItems as text

set AppleScript's text item delimiters to """
set theSourceItems to text items of theEncoded
set AppleScript's text item delimiters to "
\\""
set theEncoded to theSourceItems as text

set AppleScript's text item delimiters to oldDelims

set trimHTML to my extractBetween(theEncoded, "", "")

set theHTML to myContent

try
set decode_Success to false

--UTF-8 CONV
set NewEncodedText to do shell script "echo " &amp; quoted form of trimHTML &amp; " | iconv -t UTF-8 "
set the_UTF8Text to quoted form of NewEncodedText

--URL DECODE CONVERSION
set theDecodeScript to "php -r "echo urldecode(" &amp; the_UTF8Text &amp; ");"" as text
set theDecoded to do shell script theDecodeScript
set finalHTML to theDecoded
set decode_Success to true
return finalHTML
end try

end htmlFix

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


--CHECK FOR GROWL
on Growl_Check()
if appIsRunning("GrowlHelperApp") then
set growl_Running to true
tell application "GrowlHelperApp"
set allNotificationsFiles to {"Import To Evernote", "Success Notification", "Failure Notification"}
set enabledNotificationsFiles to {"Import To Evernote", "Success Notification", "Failure Notification"}
register as application ¬
"Mail to Evernote" all notifications allNotificationsFiles ¬
default notifications enabledNotificationsFiles ¬
icon of application "Evernote"
end tell
end if
end Growl_Check

--ANNOUNCE THE COUNT OF TOTAL ITEMS TO EXPORT
on process_Items(itemNum, attNum)
set attPlural to ""
if attNum = 0 then
set attNum to "No"
else if attNum &gt; 1 then
set attPlural to "s"
end if
tell application "Finder"
if growl_Running is true then
set Plural_Test to (itemNum) as number
if Plural_Test is greater than 1 then
tell application "GrowlHelperApp"
notify with name ¬
"Import To Evernote" title ¬
"Import To Evernote Started" description "Now Processing " &amp; itemNum &amp; " Items with " &amp; attNum &amp; ¬
" attachment" &amp; attPlural &amp; "." application name ¬
"Mail to Evernote" identifier "EVERNOTE" --image from location growl_Icon
end tell
else
tell application "GrowlHelperApp"
notify with name ¬
"Import To Evernote" title ¬
"Import To Evernote Started" description "Now Processing " &amp; itemNum &amp; " Item With " &amp; attNum &amp; ¬
" Attachment" &amp; attPlural &amp; "." application name ¬
"Mail to Evernote" identifier "EVERNOTE" --image from location growl_Icon
end tell
end if
end if
end tell --FINDER
end process_Items

--GROWL RESULTS
on growl_Growler(growl_Running, successCount)
if growl_Running is true then
tell application "GrowlHelperApp" -- GROWL SUCCESS
set Plural_Test to (successCount) as number
if Plural_Test is -1 then
notify with name ¬
"Failure Notification" title ¬
"Import Failure" description "No Items Selected From Mail!" application name ¬
¬
"Mail to Evernote"

else if Plural_Test is 0 then
notify with name ¬
"Failure Notification" title ¬
"Import Failure" description "No Items Exported From Mail!" application name ¬
¬
"Mail to Evernote"

else if Plural_Test is equal to 1 then
notify with name ¬
"Success Notification" title ¬
"Import Success" description "Successfully Exported " &amp; itemNum &amp; ¬
" Item to the " &amp; EVnotebook &amp; " Notebook in Evernote" application name ¬
¬
"Mail to Evernote"

else if Plural_Test is greater than 1 then
notify with name ¬
"Success Notification" title ¬
"Import Success" description "Successfully Exported " &amp; itemNum &amp; ¬
" Items to the " &amp; EVnotebook &amp; " Notebook in Evernote" application name ¬
¬
"Mail to Evernote"
end if
end tell
set itemNum to "0"
end if
end growl_Growler

10 Responses to “Apple Mail to Evernote 2.0 — English Language (BETA)”

  1. Rob Olian January 7, 2011 at 9:36 am #

    The script is terrific – my MailTags come over just fine.
    Only issue is that it fails when I run it using a Keyboard Maestro
    keyboard shortcut, and I have no idea why. It works fine when
    selected from the global script menu bar, it works fine when run
    directly from AppleScriptEditor, but fails in KBM, where I have the
    hotkey trigger set to Execute Script File and point it at this
    script.

    • Justin Lancy January 7, 2011 at 3:11 pm #

      Rob — Thanks for your quick feedback!

      Sometimes AppleScripts compile differently when run outside the Script Editor and I think that this may be the case here.

      Keyboard Maestro’s website has this note in its scripting section:

      AppleScripts are executed in the background via osascript. This means they are not allowed to do user interaction. You can work around this by asking an application like System Events to do the user interaction for you, for example:

      tell application "System Events"
        activate
        display dialog "Hello"
      end tell

      One way to test if this is the problem is to try setting the Tagging/Notebook Switch to “OFF” to see if that resolves the issue. If so, then I think we’ve zeroed in on an “osascript issue” and I’ll look at tweaking the code to work around that.

      Let me know what you find out!

  2. Darren DePlonty February 4, 2011 at 12:30 pm #

    Hey there – great script. There is nothing quite like it right now. One thing I noticed is for me, when I disable the dialogs, it doesn’t seem to be honoring my notebook and tag overrides as configured in the USER SWITCHES. Got any ideas?

    • Justin Lancy February 4, 2011 at 2:51 pm #

      Hi Darren,

      The issue with the NOTEBOOK override is simple — I screwed up! Should be fixed now…. 😀

      However, the Default Tag preference only comes into play when the tagging dialog is turned on. If enough people want the script to allow the switch to work more like the Notebook override, I’ll look at tweaking that.

      • Darren DePlonty February 4, 2011 at 2:54 pm #

        Cool, thanks. I’d love it if the tag override would work the same way – i.e. I can hardcode the tags I want. Also, it would be nice if I could comma delimit the string ( “2010, Darren, Email”) and the script was smart enough to parse them as individual tags. Then the script would be near perfect for me. Anyway, thanks!

  3. Lars April 6, 2011 at 3:20 pm #

    Hi,
    I love the improvements overall. Especially the ability to make my not default notebook, the default notebook instead of selecting it afterwards.

    Some bugs that happened with me:
    Somehow the tags aren’t working? Not with the tagging switch on or off.

    Danish letter æ,ø,å looks weird when in the evernote file. Didn’t happen with the original version.

    On the previous version I made the mail move to a folder in apple mail called storage. Not sure how I did that, any way to utilize this in the new version?

    • Justin Lancy April 7, 2011 at 12:50 pm #

      Hi Lars,

      You’re not the only one having some tagging issues… and now that I’m back from Laos, I’m planning on spending some time squashing bugs like these. FYI — you can follow the Veritrope.com Twitter Feed for announcements on new Script releases.

      Not sure how you did the Apple Mail folder move but, via AppleScript, it shouldn’t be too hard to add in a line that does that. When you figure that out, be sure to let us all know… think that would be a cool addition for people to have access to!

      • JC September 16, 2011 at 5:40 pm #

        I’ve just posted a comment on a different post about tags. I’ve had to change this:

        set theDelims to {","}

        to

        set theDelims to {", ",","}

        I don’t know whether this is relevant here.

  4. Helge August 24, 2011 at 9:54 am #

    Did Apple really break things with Applescript and Mail.app or did the interface change.
    Just for me to know that I don’t report stupid things to Apple… 🙂

    • Justin Lancy August 27, 2011 at 6:54 am #

      As far as I can tell, the new version of Mail.app breaks existing AppleScript definitions for pulling certain information from the header. When I have some time, I plan to dig into this more deeply to see if there’s now a new nomenclature for this (or a work-around we can use). Nonetheless, I think it’s safe to say that they’d want to know about this glitch in the new Mail AppleScript dictionary.