Need help to use script with mail rules

Hello,

I have created a script that should do the following from different bits of pieces of other scripts.

1 - collect mail subjet information and break it down to useful data
2 - mount specific volume if necessary
3 - create folder structure is necessary
4 - open eMail message on te right hand side of screen
5 - save an .xls file in the proper folder structure in a specific volume
6 - Open an .xls fil
7 - print the open mail
8 - collect some information from an .xls file and break it down to useful data
9 - create a mailbox structure in mail
10 - create rules in mail

I would like as well that the script to be run when a particular email with a the subject containing “some text” is received from a particular person.

I have tried to place in different position in my script but when the particular mail is received it fails to run the rule from mail( I have created the rule and placed the script in the proper folder for selecting it through te rule pane)

using terms from application “Mail”
on perform mail action with messages theMessages

end perform mail action with messages

end using terms from

Here is my script if anyone could give me a hand on finishing it and to explain me where and why I should place the "using terms… ". Also would appreciate if someone could show me how to make it run faster as it hangs a bit at the moment of creating the mailbox structure.

Thanks,
Claude



--New Inquiry from a sales Email save PS Print eMail create mboxes and rules 
(*
1 - collect mail subjet information and break it down to useful data
2 - mount sourcing volume if necessary
3 - create PS folder structure is necessary
4 - open eMail message on te right hand side of screen
5 - save PS in the proper folder structure in sourcing volume
6 - Open PS file
7 - print the mail
8 - collect PS information and break it down to useful data
9 - create mailbox structure in mail
10 - create rules in mail
*)
script shared
	property imprimer : true
	# false = n'imprime pas les mails
	# true = imprime les mails
end script

--Retrieve subject from selected eMail then get file number then get client short name.
tell application "Mail"
	activate
	set this_message to selection
	set theMessage to item 1 of this_message
	
	try
		set this_subject to subject of theMessage
		--> "Re: Re:____新询价ALSi15081900A_-_500-1000-2000Pcs_Fabric_School_Bag_Collection_Minnie_Miu"
		if this_subject is "" then error
	on error
		set this_subject to "No subject."
	end try
end tell

-------------------------------------------------------------------------

-------------------------------------------------------------------------
--Cleaning the subject from spaces or troublesome characters --> "Re: Re:____新询价ALSi15081900A_-_500-1000-2000Pcs_Fabric_School_Bag_Collection_Minnie_Miu"
set orig to this_subject
--> "Re: Re:____新询价ALSi15081900A_-_500-1000-2000Pcs_Fabric_School_Bag_Collection_Minnie_Miu"

#Cleaned subject
set subjectnormalized to my normalize(orig)
--> "Re: Re: 新询价ALSi15081900A - 500-1000-2000Pcs Fabric School Bag Collection Minnie Miu"

#Separate first part of subject from cleaned subject  
set part_subject to text 1 thru (offset of " - " in subjectnormalized) of subjectnormalized
--> "Re: Re: 新询价ALSi15081900A "

#Isolate file number from first part of subject
set fileNumber to last word of part_subject
--> "ALSi15081900A"

#Isolate Client short name from file number 
set clientShortName to (characters 1 thru 3 of fileNumber) as string
--> "ALS"
-------------------------------------------------------------------------

-------------------------------------------------------------------------
#Building dates
--Date variables
set currentYear to year of (current date)
set nextYear to currentYear + 1
set fiscalMonthEnd to "March"
set fiscalLastDate to "31"
#Sets current fiscal year end
set theDate to fiscalLastDate & "/" & fiscalMonthEnd & "/" & currentYear
--> "31/March/2015"
-------------------------------------------------------------------------

--Checks wether the current date is greater than current fiscal year end
if (current date) > date theDate then
	set currentFiscalYear to currentYear & "-" & nextYear as text
end if
--> "2015-2016"

# create variables for the client short name & current fiscal year
set inquiryYearDate to clientShortName & " - " & currentFiscalYear
--> "ALS - 2015-2016"
-------------------------------------------------------------------------

-------------------------------------------------------------------------
--Mount Volume to save attachment for merchandiser02
set volume_Groups to "smb://server._smb._tcp.local/Groups"
try
	mount volume volume_Groups as user name "merch02" with password "123456"
end try

--Set default folder in sourcing/RLPS/RLPS 2015-2016
set default_source_loc to "Groups:sourcing:" as text
set p2d to default_source_loc

--Construct the RLPS and current fiscal year
set MasterShareFolder to "RLPS"
# create variables for the subfolderNames
set subFolder1 to "RLPS " & currentFiscalYear
--> "RLPS 2015-2016"
set subFolder2 to clientShortName
--> "ALS"

set folderList to quoted form of subFolder1 & "/" & quoted form of subFolder2

-- create folders in case they don't exist
do shell script "/bin/mkdir -p " & quoted form of POSIX path of (p2d & MasterShareFolder) & "/" & folderList

set destinationFolder to p2d & MasterShareFolder & ":" & subFolder1 & ":" & subFolder2

set docsExt to {".xls"}

-------------------------------------------------------------------------
# Save mail attachment based on their types and open the xls file.
tell application "Mail"
	--set selected_messages to selection
	set selected_messages to item 1 of (get selection)
	open selected_messages
	
	--Place mail on the right side of screen
	set the bounds of the front window to {721, 22, 1440, 826}
	repeat with a_message in selected_messages
		# get the attachments embedded in the message
		set the_attachments to every mail attachment of a_message
		# define a nil subfolder name
		set the_xls_path to ""
		# first loop accross the attached files to create the destination folder
		repeat with an_attachment in the_attachments
			# get the attachment's name
			set attachment_name to name of an_attachment
			if attachment_name ends with ".xls" then
				# builds its full pathname
				set destination_path to destinationFolder --& ":" & destination_name
				# builds the pathname of the stored Xls file
				set the_xls_path to destination_path & ":" & attachment_name
				exit repeat # no need to continue to loop
			end if
		end repeat # in the first loop accross attachments
		
		if the_xls_path > "" then
			# as theXlsName is not nil, the destination folder exists
			# loop one more time accross the attached files to save them
			repeat with an_attachment in the_attachments
				# get the attachment's name
				set attachment_name to name of an_attachment
				repeat with ext in (docsExt) # concatenate the lists to loop only once
					if attachment_name ends with ext then
						# try to save the attached file in the destination folder
						# I assume that the subfolder is used only once
						# If I'm wrong add code to treat possible duplicate names
						try
							save an_attachment in file (destination_path & ":" & attachment_name)
						end try
					end if
				end repeat # with ext
			end repeat # in the 2nd loop accross the Attachments
			# here instruction supposed to open the xls file
			try
				tell application "Finder" to open (the_xls_path as alias)
			end try
		end if
	end repeat # in the loop accross selected messages
end tell
--Print mail
#===== Print opened email

set PRINTERS_loc to localized string "PRINTERS" in bundle ((path to library folder from system domain as text) & "PreferencePanes:PrintAndScan.prefPane") as alias
if shared's imprimer then
	tell application "System Events" to tell process "Mail"
		set frontmost to true
		keystroke "p" using {command down}
		tell window 1
			# Sometimes, the application displays a sheet with a single button because it's preparing the contents to print
			# This loop let it do its duty waiting for the sheet with settings item.
			repeat
				try
					if (exists pop up button 1 of sheet 1) then exit repeat
				end try
				delay 0.2
			end repeat
			tell sheet 1
				set lesDescriptions to description of every pop up button
				repeat with i from 1 to count lesDescriptions
					if (item i of lesDescriptions as text) is PRINTERS_loc then
						click pop up button i
						exit repeat
					end if
				end repeat
			end tell # sheet 1
			# Wait as long as the sheet is available.
			repeat while exists sheet 1
				delay 0.2
			end repeat
		end tell # window 1
	end tell # System Events.
end if
--Print in one page images

-- Transfer Data from Excel
tell application "Microsoft Excel"
	-- Get Excel to activate
	activate
	
	# extracting file name
	set fileName to get (value of (get range "BW3")) -- "LAAi15061800A - MOQ Metal Ball Pens Landmark Aviation"
	
	# extracting product category and product name
	set textProductSCPath to get value of (get range "AP1") as text --"/Volumes/Groups/sales/Selling Prices Categories/Office/Writing Instruments/Ball Pen/"
	--> "/Groups/sales/Selling Prices Categories/Office/Writing Instruments/Ball Pen/"
	if textProductSCPath ends with "/" then set textProductSCPath to text 1 thru -2 of textProductSCPath
	
	try
		--> "/Groups/sales/Selling Prices Categories/Office/Writing Instruments/Ball Pen/"
		# 1 on isole ce qui se trouve dans le dossier "Sales"
		set textProductSCPath to item 2 of my decoupe(textProductSCPath, "/sales/")
		-->"/Selling Prices Categories/Office/Writing Instruments/Ball Pen/"
		# 2 on sépare les noms de dossiers
		set lesNoms to my decoupe(textProductSCPath, "/")
		--> Résultat :
		{"Selling Prices Categories", "Office", "Writing Instruments", "Ball Pen"}
		set theOfficeProductCategory to item 2 of lesNoms
		set theOfficeProductName to item -1 of lesNoms
		set theProductNameWithDate to (theOfficeProductName & " - " & theInquiryYearDate)
		--> "Office - Ball Pen"
	end try
end tell

--Create mailbox structure in mail

--Variables

set grandParentMailbox to theOfficeProductCategory as text
set parentMailbox to theProductNameWithDate as text
set childMailbox to fileName as text

set Generation01 to (grandParentMailbox & "/" & parentMailbox) as text
set Generation02 to (grandParentMailbox & "/" & parentMailbox & "/" & childMailbox) as text

tell application "Mail"
	activate
	try
		if (mailbox grandParentMailbox exists) = false then
			make new mailbox with properties {name:grandParentMailbox}
			set frontViewer to (some message viewer whose index is 1)
			set selected mailboxes of frontViewer to {mailbox grandParentMailbox}
			my waitTillmBoxFileExists(grandParentMailbox & ".mbox")
		end if
	end try
end tell

tell application "Mail"
	try
		if (mailbox Generation01 exists) = false then
			make new mailbox with properties {name:Generation01}
			set frontViewer to (some message viewer whose index is 1)
			set selected mailboxes of frontViewer to {mailbox Generation01}
			my waitTillmBoxFileExists(grandParentMailbox & ".mbox" & "/" & parentMailbox & ".mbox")
		end if
	end try
end tell

tell application "Mail"
	try
		if (mailbox Generation02 exists) = false then
			make new mailbox with properties {name:Generation02}
			set frontViewer to (some message viewer whose index is 1)
			set selected mailboxes of frontViewer to {mailbox Generation02}
			my waitTillmBoxFileExists(grandParentMailbox & ".mbox" & "/" & parentMailbox & ".mbox" & "/" & childMailbox & ".mbox")
		end if
	end try
end tell

--Make sure that the mailboxes structure exits
on waitTillmBoxFileExists(mBox)
	--Get machine "short user name" in order to switch machine 
	set userName to short user name of (system info)
	
	--Set the mailboxes structures
	set parentDir to "/Users/" & userName & "/Library/Mail/V2/Mailboxes"
	set theMailBoxFile to parentDir & "/" & mBox & "/Info.plist"
	repeat while (my mBoxFileExists(theMailBoxFile) = false)
		delay 20
	end repeat
end waitTillmBoxFileExists

--Make sure that the mailbox file exits
on mBoxFileExists(the_mBoxFile) -- (String) as Boolean
	tell application "System Events"
		if exists file the_mBoxFile then
			return true
		else
			return false
		end if
	end tell
end mBoxFileExists

--Create rules in mail

tell application "Mail"
	try
		set newRule to make new rule at end of rules with properties {name:fileName, enabled:true, should move message:true}
		
		tell newRule
			make new rule condition at end of rule conditions with properties {rule type:subject header, qualifier:does contain value, expression:fileNumber}
			make new rule condition at end of rule conditions with properties {rule type:message content, qualifier:does contain value, expression:fileNumber}
			set move message to (mailbox (Generation02) of application "Mail")
		end tell
	end try
end tell
-------------------------------------------------------------------------

-------------------------------------------------------------------------

#=====

on decoupe(t, d)
	local oTids, l
	set {oTids, AppleScript's text item delimiters} to {AppleScript's text item delimiters, d}
	set l to text items of t
	set AppleScript's text item delimiters to oTids
	return l
end decoupe

#=====

on normalize(txt)
	local oTids, l
	set {oTids, AppleScript's text item delimiters} to {AppleScript's text item delimiters, {"_", ".", ","}}
	set l to text items of txt
	set AppleScript's text item delimiters to space
	set txt to l as text
	
	repeat while txt contains "  " # two spaces
		set AppleScript's text item delimiters to "  " # two spaces
		set l to text items of txt
		set AppleScript's text item delimiters to " " # one space
		set txt to l as text
	end repeat
	set AppleScript's text item delimiters to oTids
	return txt
end normalize

#=====