When I receive a message with an attachment the rule should
Download the attachment
Process it using do shell script
Forward the original message (but not send it, just create a draft - I will manually add details to this)
Attach the processed file and preferably delete the original attachment.
1-3 works but 4 deletes both the existing attachment (good) as well as the message body (bad).
The code is very simple:
tell theDraft
set outputAlias to POSIX file outputPath as alias
make new attachment with properties {file name:outputAlias}
end tell
How do I attach something to a draft without deleting the existing message body?
Preferably while deleting the existing attachment. I can live with manually deleting the original attachment but I want to preserve the message body. HTML/plain text doesn’t matter.
I have solved this problem now, but it required GUI-scripting, which feels unsatisfactory. Input and feedback on how to improve this is welcome.
Here is a simplified version of the code:
tell application "Mail"
repeat with aMessage in theMessages
set fwdMsg to forward aMessage with opening window
set visible of fwdMsg to true
set draftMessages to (every outgoing message whose visible is true)
if draftMessages is not {} then
set theDraft to item 1 of draftMessages
tell application "System Events"
repeat 4 times -- Focus is on the to-field. Four tabs to get into the body field
delay 0.3
key code 48
end repeat
keystroke "a" using {command down} -- select all
delay 0.3
keystroke "x" using {command down} -- cut, placing the content of the body on the clipboard. The body only consists of the to, from, subject, date values that Mail.app itself includes when you forward a message
delay 0.3
end tell
tell theDraft
set outputAlias to POSIX file outputPath as alias
set content of theDraft to my getClipboardAsRichText()
make new attachment with properties {file name:outputAlias}
save
end tell
end if
end repeat
end tell
The main problem is that the original message doesn’t have any body, and the body of the draft that results from forward a message, i.e., From, To, Date and Subject isn’t (?) accessible programmatically, but I wanted to keep that meta-data.
The solution was to GUI script:
Change focus from To to Body
Select All
Cut
Can (1) be achieved some other way than by sending multiple tabs?
Here is another weird behaviour:
If I inserted the attachment directly after forwarding the message the body was deleted, but if I first cut the body, then paste the body (you would think you where back to the original state after these operations) and finally insert the attachment the body isn’t deleted!?!?
To sum up the complications:
Original message didn’t have any body. The draft that resulted from forwarding just contained some metadata.
Insert an attachment deleted that metadata. However cut’n’pasting the metadata somehow “reset” it, and allowed you to insert the attachment.