Handler to create Email with Attachments using AppleScript
Bob Sneidar
bobsneidar at iotecdigital.com
Wed Jan 22 13:00:28 EST 2020
For your general consumption. No error checking, so send it good data.
/**
AppleScript Create Mail. Pass a comma delimited list of email addresses, a subject line, Body text and
optionally a numbered array of file paths. Creates a new mail in the OS X Mail app.
*/
on asCreateEmail pAddressList, pSubject, pBody, aAttachments
--create a new email
put "tell application " & quote & "Mail" & quote & cr into tAppleScript
put tab & \
"set newMessage to (a reference to (make new outgoing message))" & cr & cr after tAppleScript
-- To: address
put tab & "tell newMessage" & cr after tAppleScript
put tab & tab & \
"make new recipient at beginning of to recipients" & numToChar(194) & cr after tAppleScript
put tab & tab & tab & \
"with properties {address:" & quote & item 1 of pAddressList & quote & "}" & cr after tAppleScript
-- Bcc: addresses (if more than one item in pAddressList
if the number of items of pAddressList >1 then
put tab & tab & \
"make new cc recipient at end of cc recipients " & numToChar(194) & cr after tAppleScript
put tab & tab & tab & \
"with properties {address:" & quote after tAppleScript
repeat with i = 2 to the number of items of pAddressList
put item i of pAddressList & comma after tAppleScript
end repeat
put quote & "}" & cr & cr into last char of tAppleScript
end if
-- Subject
put tab & tab & \
"set the subject to " & quote & pSubject & quote & cr after tAppleScript
-- Content
put tab & tab & \
"set the content to " & quote & pBody & cr & cr & quote & cr & cr after tAppleScript
-- add attachments
if aAttachments is an array then
put the keys of aAttachments into tKeyList
put tab & tab & tab & \
"tell content" & cr after tAppleScript
repeat for each line tKey in tKeyList
put tab & tab & tab & tab & \
"make new attachment " & numToChar(194) & cr after tAppleScript
put tab & tab & tab & tab & \
"with properties {file name:" & quote after tAppleScript
put aAttachments [tKey] & quote & "}" & cr after tAppleScript
end repeat
end if
put tab & tab & \
"end tell" & cr after tAppleScript
/*
Unsure why using send sends the email before the attachments get attached
-- put tab & tab & "send" & cr after tAppleScript
*/
put tab & tab & "set visible to true" & cr after tAppleScript -- displays email in Mail App
-- close tells
put tab & \
"end tell" & cr after tAppleScript -- tell newMessage
put "end tell" & cr after tAppleScript -- tell application
-- Send it!
do tAppleScript as appleScript
return the result -- returns empty if no errors
end asCreateEmail
More information about the use-livecode
mailing list