Mail script problems for email reply from text file template

Hi all,

I was wondering if you could help me out. I have written a little applescript with the help of you and the posts on this forum. The script is linked to a Mail Act-on key and should the user select a template text file and then extract the email address of a craigslist post email in your inbox. Then create a new email with the emails addresses in the BCC field and copy the content of the text file into the body of the email message.

The script works, but NOT when run as mail script. See below. I tried to debug it but can’t put my finger on the exact cause (my while loop?). It also sometimes causes mail.app to crash. Mhh. that worries me.

So here we go, and any input is greatly appreciated:


-- Automated Reply with templates
-- Choose the template for the reply
--
using terms from application "Mail"
	on perform mail action with messages theMessages for rule theRule
		tell application "System Events"
			set TemplateFolder to "HomeDrive:Users:sebastian:Library:Mail:Templates:" as alias
			set filepath to (choose file with prompt "Choose a Reply Template" default location TemplateFolder) as text
			set Templatebody to read file filepath
		end tell
		
		-- extract email address from craigslist email
		tell application "Mail"
			set theEmailList to {}
			set theMessages to selection as list
			repeat with msg in theMessages
				set inquiry_email to ""
				set the_body to paragraphs of (content of msg as string)
				set old_atid to AppleScript's text item delimiters
				set AppleScript's text item delimiters to {": "}
				
				try
					set inquiry_email to text item 2 of (item 6 of the_body)
				on error
					display dialog "It seems this email is not a craigslist post. " & "Please enter a valid email or leave it blank." default answer "" buttons {"Oops, go on"} default button 1
					-- get email address entered by user
					set inquiry_email to text returned of result
				end try
				set AppleScript's text item delimiters to old_atid
				
				if inquiry_email is not in theEmailList then set theEmailList to theEmailList & {inquiry_email}
			end repeat
			-- create new mail message and set Subject Line
			set ReplyMail to make new outgoing message with properties {subject:"Reply to your recent craigslist post", visible:true}
			-- Set me as sender of the email and add each recipient as BCC
			tell ReplyMail
				set sender to "Sebastian Auer <s.auer@neolithmedia.com>"
				make new to recipient with properties {name:"Sebastian Auer", address:"s.auer@neolithmedia.com"}
				repeat with theRecip in theEmailList
					make new bcc recipient at end of bcc recipients with properties {address:theRecip}
				end repeat
				set content to Templatebody
				
				-- ** Signatures **
				-- signatures do not work yet as they are added to the top of every email message not below the content. Weird.
				-- **
				--set message signature of ReplyMail to signature "Business" of application "Mail"
				--set MailSigName to "InquiryReply"
				--set MailSig to "Sebastian Auer | neolithmedia | s.auer@neolithmedia.com | 805.300.9308" as string
				--make new signature with properties {name:MailSigName, content:MailSig}
			end tell
			
			-- send ReplyMail -- Still Blocked out in order to ensure the script actually works
		end tell
	end perform mail action with messages
end using terms from

See here…

http://discussions.apple.com/thread.jspa?threadID=1226817

Just fooling around with this myself.

Hi elreverend,

Unfortunately mail rule action scripts should not contain any user interaction, this crashes Apple Mail:


set filepath to (choose file with prompt "Choose a Reply Template" default location TemplateFolder) as text
...
display dialog "It seems this email is not a craigslist post. " & "Please enter a valid email or leave it blank." default answer "" buttons {"Oops, go on"} default button 1

See also this thread.

:frowning:

Thanks for the reply, but if Apple Mail Rule Actions should NOT contain any user interactions, why is Apple’s own example created with one error handler? And it works flawlessly (not that it does much)? Is there a specific reason?

Thanks for any insight into this.

See below:

using terms from application "Mail"
	on perform mail action with messages theMessages for rule theRule
		tell application "Mail"
			set theText to "This AppleScript is intended to be used as an AppleScript rule action, but is also an example of how to write scripts that act on a selection of messages or mailboxes." & return & return & "To view this script, hold down the option key and select it again from the Scripts menu."
			repeat with eachMessage in theMessages
				set theSubject to subject of eachMessage
				try
					-- If this is not being executed as a rule action,
					-- getting the name of theRule variable will fail.
					set theRuleName to name of theRule
					set theText to "The rule named '" & theRuleName & "' matched this message:"
					set theText to theText & return & return & "Subject: " & theSubject
					display dialog theText
					set theText to ""
				end try
			end repeat
			if theText is not equal to "" then
				display dialog theText buttons {"OK"} default button 1
			end if
		end tell
	end perform mail action with messages
end using terms from

I am running Mac OS X 10.5.4 and Apple Mail 3.3 and executing an Apple Mail Rule Action with the given code example crashes my Apple Mail absolutely reliable :wink:

Here’s a work around that will fool Applescript into letting you do this. Replace your ‘set filepath’ line with the following:

tell application "Finder" to activate
set x to "osascript -e 'tell app \"Finder\" to choose file with prompt \"Choose a Reply Template\" default location \"" & TemplateFolder & "\"'"
set filepath to do shell script x
set filepath to characters 7 thru -1 of filepath as text

Hello cwtnospam,

thanks for your reply. I tried the code you gave me, but unfortunately it does not work. It reports that it cannot make the TemplatePath variable in type alias. I have tried string and text, but to no avail. I have also isolated the sections to gather the contents of the file, but it times out. If you have any other ideas I am all ear.

Here is a quick question: with the osacript i am trying to call a new script that then in turn should return a variable.
Script A call script B

  • Script B runs
    • User selects Template
    • Script B copies text of template into variable
    • Script B return variable to Script A
  • Script A continues with variable of Script B
    Script B finishes

Script A


do shell script "osascript \"/Users/theuser/Desktop/Readfile.scpt\""

Script B


tell application "System Events"
	set TemplateFolder to "HomeDrive:Users:theuser:Library:Mail:Templates:" as alias
	set filepath to (choose file with prompt "Choose a Reply Template" default location TemplateFolder) as text
	set Templatebody to read file filepath
end tell
return Templatebody as text

those two scripts work, but when inserted into the original script it takes an extremely long time just to run the readfile script. I am talking about 8mins here. So what am i doing wrong?

Here is the revised script:


-- Author: Sebastian
-- Creation Date: 7/01/2008
-- Version: 1.0
-- Description: Script to automate the reply to email process by selecting one or more craigslist post from your inbox and replying with a selected text template.
-- Pre-requisites: 
-- * Must email craigslist post your own email
-- * Must use Apple's Mail.app
--
using terms from application "Mail"
	on perform mail action with messages themanyMessages for rule theRule
		
		tell application "System Events"
			do shell script "osascript \"/Users/theuser/Desktop/Readfile.scpt\""
			set Templatebody to the result as text
		end tell
		-- extract email address from craigslist email
		tell application "Mail"
			set theEmailList to {}
			set theMessages to selection as list
			repeat with msg in theMessages
				set inquiry_email to ""
				set the_body to paragraphs of (content of msg as string)
				set old_atid to AppleScript's text item delimiters
				set AppleScript's text item delimiters to {": "}
				
				try -- Extracting the email address from the original poster & Error handling if its not recognized
					set inquiry_email to text item 2 of (item 6 of the_body)
				on error
					--display dialog "It seems this email is not a craigslist post. " & "Please enter a valid email or leave it blank." default answer "" buttons {"Oops, go on"} default button 1
					-- get email address manually from user
					-- set inquiry_email to text returned of result
					-- Ignore email address input FOR NOW
				end try
				set AppleScript's text item delimiters to old_atid
				
				if inquiry_email is not in theEmailList then set theEmailList to theEmailList & {inquiry_email}
			end repeat
			-- create new mail message and set subject line
			set ReplyMail to make new outgoing message with properties {subject:"Reply to your recent craigslist post", visible:true} -- visibility may be set to false to hide the message window. You MUST also uncomment the 'send ReplyMail' line below in order to be able to send your email.
			-- Set me as sender of the email and add each recipient as BCC
			tell ReplyMail
				set sender to "Joe Sixpack <js@aol.com>"
				make new to recipient with properties {name:"Joe Sixpack", address:"js@aol.com"}
				repeat with theRecip in theEmailList
					make new bcc recipient at end of bcc recipients with properties {address:theRecip}
				end repeat
				set content to Templatebody
				
			end tell
			-- Uncomment the line below to atomatically send email without user interaction
			-- send ReplyMail
		end tell
		
	end perform mail action with messages
end using terms from

OK I figured it out. I just call another script from a first one that gets called by Mail, using osascript. The error in the first one was to let “System Events” handle the copying of the file contents instead of the finder.
Here is my new script that works. Feel free to use it, but gimme (and others) some credit should you sell it.


(*
Author: Sebastian Auer
WWW: http://neolithmedia[DOT]com
EMAIL: s.auer[AT]neolithmedia[DOT]com
Creation Date: 7/01/2008
Version: 1.0

Description: Script to automate the reply to email process by selecting one or more craigslist post from your inbox and replying with a selected text template.

Pre-requisites: 
-- Must email/forward craigslist post to your own email address (or someone else to you).
-- Must use Apple's Mail.app
-- the script must be called with this script as Apple's Mail does not allows user interaction:

using terms from application "Mail"
	on perform mail action with messages themanyMessages for rule theRule
		do shell script "osascript \"/PATH_TO_YOUR_MAILSCRIPT_FOLDER/Mail Scripts/Reply_Template.scpt\""
	end perform mail action with messages
end using terms from

*)

-- Setup your variables below
-- Your name.
set sender_name to "YOUR NAME"
-- Your email address.
set sender_email to "<YOUR EMAIL>"
-- Your Account. This is the email address of your OUTGOING mail account.
set full_sender_email to "YOUR NAME <YOUR EMAIL>"
-- The reply subject.
set reply_subject to "Reply to your recent craigslist post"
-- The folder where your templates are stored in text format.
set TemplateFolder to "PATH TO YOUR TEMPLATE FOLDER" as alias

-- DO NOT MODIFY ANYTHING BELOW THIS LINE. Most users should not have to.
tell application "Finder"
	activate
	set theTemplateFile to (choose file with prompt "Choose a CRAIGSLIST Reply Template:" default location TemplateFolder)
	open for access theTemplateFile
	set fileContents to (read theTemplateFile)
	close access theTemplateFile
end tell

-- extract email address from craigslist email
tell application "Mail"
	activate
	set theEmailList to {}
	set theMessages to selection as list
	repeat with msg in theMessages
		set inquiry_email to ""
		set the_body to paragraphs of (content of msg as string)
		set old_atid to AppleScript's text item delimiters
		set AppleScript's text item delimiters to {": "}
		
		try
			set inquiry_email to text item 2 of (item 6 of the_body)
		on error
			-- if the selected email(s) is not a creaiglsit forward or it does not correspond to the craigslist format the user can manually enter an email address. A warning will be given.
			set current_subject to subject of msg as string
			display dialog "It seems this email:" & "
" & "
" & current_subject & "
" & "
" & "is not a craigslist post. Please enter a valid email or leave it blank." default answer "" buttons {"Ooops, I'm done. Continue"} default button 1 giving up after 10 with icon caution
			-- get email address entered by user
			set inquiry_email to text returned of result
		end try
		set AppleScript's text item delimiters to old_atid
		
		if inquiry_email is not in theEmailList then set theEmailList to theEmailList & {inquiry_email}
	end repeat
	-- create new mail message and set Subject Line
	set ReplyMail to make new outgoing message with properties {subject:reply_subject, visible:true}
	-- Set me as sender of the email and add each recipient as BCC
	tell ReplyMail
		set sender to full_sender_email
		make new to recipient with properties {name:sender_name, address:sender_email}
		repeat with theRecip in theEmailList
			make new bcc recipient at end of bcc recipients with properties {address:theRecip}
		end repeat
		set content to fileContents
		
		-- ** Signatures **
		-- signature do not work yeat as they are added to the top of every email message not below the content. Weird.
		-- **
		--set message signature of ReplyMail to signature "Business" of application "Mail"
	end tell
	
	-- send ReplyMail -- Still Blocked out in order to ensure the script actually works
end tell

Now if I only could get rich text signatures to work…