Mail to OmniFocus – AppleScript

I’ve created a little AppleScript that copies the mail contents and attachments into an OmniFocus task. It also creates a back-link into the OF task, and a forward link as a MailTags note.

(*

  Create an OmniFocus task in the OF Inbox from Mail
  that has a link back to the eMail, such as
  
  message://%[email protected]%3e
  
  --
  
  (c) 2018 Matthias Nott

*)

use AppleScript version "2.4" -- Yosemite (10.10) or later
use scripting additions


--
-- Configuration
--
property assignedKeywords : {"#todo"} -- Tag to set
property quickEntry : false -- use Quick Entry


--
-- Main Program
--
on run
	set crt to ASCII character 13
	
	tell application "Mail"
		set theMessage to ""
		set theInboxMessages to selection
		
		if (count of theInboxMessages) is greater than 0 then
			repeat with theMessage in theInboxMessages
				
				set theSender to sender of theMessage as string
				set theSubject to subject of theMessage as string
				set theTitle to theSender & " — " & theSubject
				set theURL to ("message://%3c" & message id of ¬
					theMessage & "%3e" & crt & crt) as rich text
				
				set theNote to theURL
				set theNote to (theNote & content of theMessage)
				set theAttachments to ""
				set theAttachmentsCount to count of ¬
					mail attachment of theMessage
				if theAttachmentsCount is greater than 0 then
					set theMailAttachments to ¬
						mail attachments of theMessage
					repeat with theMailAttachment in theMailAttachments
						set theAttachments to theAttachments & ¬
							name of theMailAttachment & crt
					end repeat
					set theNote to ¬
						theNote & crt & crt & "Attachments:" & ¬
						crt & theAttachments
				end if
				set theTaskID to my makeOmniFocusTask(theTitle, theNote, quickEntry)
				-- set background color of theMessage to purple
				if (quickEntry is not true) then
					using terms from application "MailTagsHelper"
						set keywords of theMessage to assignedKeywords
						set note of theMessage to theTaskID
					end using terms from
				end if
				set flag index of theMessage to 5
				set read status of theMessage to true
			end repeat
		end if
	end tell
	
end run


--
-- Make an OmniFocus Task
--
on makeOmniFocusTask(theTitle, theNote, isQuick)
	tell application "OmniFocus"
		if (isQuick = true) then
			tell quick entry
				set theTask to make new inbox task with properties ¬
					{name:theTitle, note:theNote}
				open
			end tell
		else
			tell default document
				set theTask to make new inbox task with properties ¬
					{name:theTitle, note:theNote}
			end tell
		end if
	end tell
	set theTaskID to "omnifocus:///task/" & id of theTask
	return theTaskID
end makeOmniFocusTask
Share