Using AppleScript to mail merge with attachments

Here is some code that is useful for sending batch emails with Mac Mail to recipients using information stored in a text file. This also enables attaching specific files to the message, again based on the information in the text file.

set mol_list to {}
-- This will ask you to select a file containing the intended recepients and their emails --
-- I also include in this file information needed to link to an attachment --
set theFile to choose file with prompt "Select a text file:"
set theFileReference to open for access theFile
-- Note that the line end here is an old Mac return (not MSFT carriage return) --
set theFileContents to read theFileReference using delimiter return
close access theFileReference

-- Now parse the file that was selected. Here I'm parsing a tab-delimited file. --
set text item delimiters to tab
-- Loop through the file one line at a time --
repeat with i from 1 to count of theFileContents
	set theLine to text items of item i of theFileContents
	copy theLine to the end of mol_list
	-- this identifies each column in the tab-delimited file --
	set stid to item 1 of theLine
	set first_name to item 2 of theLine
	set last_name to item 3 of theLine
	set email_add to item 4 of theLine
	-- specify the location of the file to attach --
	-- here I'm pasting together information from the tab-delimited file to point to the file for this particular recipient --
	set file_attach to "Macintosh HD:Users:USERID:file_" & stid & ".pdf"
	-- Set the message, again pasting together info from the recipient file --
	set message_content to "Dear " & first_name & ",
	This is my email to you containing your information. 
	-- Now push this to Mac's mail software
	tell application "Mail"
		-- Create a new message with the message above and the subject --
		set theMessage to make new outgoing message with properties {visible:true, subject:"Set the subject here", content:message_content}
		-- Set the address for this recipient --
		tell theMessage
			make new to recipient at end of to recipients with properties {address:email_add}
		end tell
		-- Add the attachment to this recipient --
		tell content of theMessage
			make new attachment with properties {file name:file_attach as alias} at after last paragraph
		end tell
		-- Add a little delay to attach larger files to the email before sending --
		delay 2
		-- Send the message to this recipient --
		send theMessage
	end tell
end repeat

Leave a Reply

Your email address will not be published. Required fields are marked *