This script extracts email addresses from the body of a message and resends the message to each of the extracted addresses. It works well when one message arrives at a time. However, when several messages arrive at once, it often sends a message to the wrong address. The script is very straight forward, yet I am not sure what is going on. Any ideas?
property debug : false
property choAddress : "your@email.com"
using terms from application "Mail"
on perform mail action with messages theMessages for rule theRule
tell application "Mail"
repeat with aMessage in theMessages
-- Extract addresses from message content
set messageContent to aMessage's content
set messageSubject to aMessage's subject
set mAddresses to my extractAddresses(messageContent)
-- Build a unique list of addresses
set uAddresses to {}
repeat with mAddress in mAddresses
set mAddress to contents of mAddress
if mAddress ≠choAddress and mAddress is not in uAddresses then set end of uAddresses to mAddress
end repeat
-- Forward messages to each extracted address
repeat with uAddress in uAddresses
set newMessage to make new outgoing message at the beginning of outgoing messages with properties {sender:choAddress, subject:messageSubject}
tell newMessage
make new to recipient at beginning of to recipients with properties {address:uAddress}
set content to aMessage's content
if debug then
set visible to true
else
send
delay 1
end if
end tell
end repeat
delay 1
end repeat
end tell
end perform mail action with messages
end using terms from
on extractAddresses(mContent)
try
-- Thanks Nigel Garvey
set extractedAddresses to paragraphs of (do shell script "echo " & quoted form of mContent & " | grep -Eo '[[:alnum:]][^[:space:]<>@\":;]+@[^ <>\"]+[][:alpha:]]'")
on error
error number -128
end try
end extractAddresses