Apple Mail to Evernote 2.0 — Japanese Language (BETA)

Description

This script has now been replaced -- Click Here To Go To The New Script's Page!

OLD VERSION INFORMATION

This script doesn't work with Lion and I've only left it up here in case someone wanted to look at the MailTags code (which has been removed from the new script).

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!
There are also a couple of notifications in this script that have not been translated into Japanese yet. Please add your translations (and any other suggestions) in the comments below!

The Code

(*
http://veritrope.com
Apple Mail to Evernote
Version 2.0-BETA
January 6, 2011
Project Status, Latest Updates, and Comments Collected at:
http://veritrope.com/code/apple-mail-to-evernote-japanese-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
    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 : "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 YOU'D LIKE TO CHANGE THE DEFAULT TAG,
--TYPE IT BETWEEN THE QUOTES ("タグ" IS DEFAULT)
property default_Tag : "タグ"


(*
======================================
// 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 : "メッセージ"
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 ¬
                    "書き出し失敗" description "次のエラーで書き出しに失敗しました:" & return & myTitle & ¬
                    ""  " & 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 "
アイテムの読み込みに失敗しました:" & 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 "
" & ¬
        "
タグを入力(コロンかコンマで分割)" with title "Apple Mail から Evernote へ書き出し" default answer default_Tag buttons {"既定のノートブックに作成", "ノートブックを選択", "キャンセル"} default button "既定のノートブックに作成" cancel button ¬
        "
キャンセル" 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 "
ノートブックを選択" 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
        set EVnotebook to name of (item 1 of get_defaultNotebook) as text
    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 (JP)
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 "
Evernote のノートブックを選択" with prompt ¬
            "
現在の Evernote ノートブック" OK button name "OK" cancel button name "新規ノートブック" (*USER SELECTION FROM NOTEBOOK LIST *)
        if (SelNotebook is false) then (*CREATE NEW NOTEBOOK OPTION *)
            set userInput to ¬
                text returned of (display dialog "
新規ノートブック名を入力:" 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, "<", ">") -- extract the Address
                    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 border="
1" width="100%" cellspacing="0" cellpadding="2">
<tbody>

<tr BGCOLOR="
#ffffff">
<td valign="
top"><font color="#797979"><strong>From: </strong>  </td>
<td valign="
top" ><a href="mailto:" & ex & "">" & ex & "</a></td>
</tr>

<tr BGCOLOR="
#ffffff">
<td valign="
top"><font color="#797979"><strong>Subject: </strong>  </td>
<td valign="
top" ><strong>" & myTitle & "</strong></td>
</tr>

<tr BGCOLOR="
#ffffff">
<td valign="
top"><font color="#797979"><strong>Date / Time:  </strong></td>
<td valign="
top">" & EmailDate & "</td>
</tr>

<tr BGCOLOR="
#ffffff">
<td valign="
top"><font color="#797979"><strong>To:</strong></td>
<td valign="
top">" & theRecipient & "</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 base64MsgStr to "Content-Transfer-Encoding: base64" & return & "Content-Type: text"
                if mySource contains base64MsgStr then
                    set multiHTML to my extractBetween(mySource, "Content-Transfer-Encoding: base64", theBoundary)
                    set baseHTML to do shell script "echo " & (quoted form of multiHTML) & "| 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, "</head>", "</html>")
                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"
       
        --TEMP FILES PROCESSED ON THE DESKTOP
        set ExportFolder to ((path to desktop folder) & "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 & 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 " & quoted form of POSIX path of theFileName & space & 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 & 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

(* ======================================
// 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;", "</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 "%" & (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 "%" & (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 "&nbsp;"
    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 "%3D"
    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 "&#36;"
    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 "&apos;"
    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, "</head>", "</html>")
   
    set theHTML to myContent
   
    try
        set decode_Success to false
       
        --UTF-8 CONV
        set NewEncodedText to do shell script "echo " & quoted form of trimHTML & " | iconv -t UTF-8 "
        set the_UTF8Text to quoted form of NewEncodedText
       
        --URL DECODE CONVERSION
        set theDecodeScript to "php -r "echo urldecode(" & the_UTF8Text & ");"" 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 > 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 " & itemNum & " Items with " & attNum & ¬
                        " attachment" & attPlural & "." 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 " & itemNum & " Item With " & attNum & ¬
                        " Attachment" & attPlural & "." 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 ¬
                    "読み込み失敗" description ¬
                    "ヘッドラインまたはタブが選択されていません!" application name "Mail to Evernote"
               
            else if Plural_Test ≥ 1 then
                notify with name ¬
                    "Success Notification" title ¬
                    "書き出し成功" description " " & successCount & ¬
                    " 件のメッセージを Evernote に書き出しました!" application name "Mail to Evernote"
               
            end if
        end tell
        set itemNum to "0"
    end if
end growl_Growler