Why does this AppleScript get an "AppleEvent handler failed" error on Mac OS X 10.5 Leopard? - email

First, I know, Leopard is the old-fogey at this point, but it's the minimum I'd like to be able to support with this script, so please bear with me (it's not even possible under Mac OS X 10.4 Tiger due to a bug w/Mail redirect/forward/reply bug I had uncovered long ago).
I've been revisiting building an AppleScript to work in conjunction with Topic Desk's spamtrainer, so it goes through a selection of messages in the Junk folder and attempts to redirect them to a specified mailbox. Here's what I have so far (note that the actual sending is commented out at the moment, more on that later):
(* Train Spam - Redirect (not forward) email from the Junk folder (which hasn't already been redirected or
* determined by the mail server to be spam) to an appropriate spam mailbox on the mail server.
* Developed to be used in conjunction w/spamtrainer on a Mac OS X Server mail server.
*
* v0.1 2011-07-27 - Morgan Aldridge
* Initial version.
*)
using terms from application "Mail"
on perform mail action with messages selectedMsgs in mailboxes selectedMailboxes
tell application "Mail"
-- configuration variables
set junkPrefix to "***JUNK MAIL***"
set junkRecipient to "junkmail#domain.tld"
-- ensure that we're in the Junk mailbox
-- (it'd be disasterous to accidentally redirect mail for training from another mailbox)
if (count of selectedMailboxes) is 1 and (first item of selectedMailboxes) is junk mailbox then
set selCount to (count of selectedMsgs)
set redirectedCount to 0
repeat with counter from 1 to selCount
set msg to item counter of selectedMsgs
-- if the subject doesn't start with junkPrefix and the message hasn't already been redirected, then redirect it
-- (otherwise, if it starts with junkPrefix, it means it was already detected as junk by the mail server)
-- (and, obviously, if it was already redirected, that was probably for the sake of junk training as well)
if subject of msg does not start with junkPrefix and not was redirected of msg then
set newRedirectMsg to redirect msg with opening window
tell newRedirectMsg
-- set the to recipient to that of the specified spam mailbox on the mail server
make new recipient at beginning of to recipients with properties {address:junkRecipient}
-- remove any bcc or cc recipient (we don't want to be spamming anyone else in the process)
delete bcc recipients
delete cc recipients
end tell
-- actually send the message
-- send newRedirectMsg
else
display dialog "Oops, the message was already flagged as junk by the mail server or you've already redirected it!"
end if
end repeat
else
display dialog "Oops, you're not in your Junk mailbox!"
end if
end tell
end perform mail action with messages
end using terms from
-- this is required when _not_ running from the Script menu (e.g. Script Editor, FastScripts, etc.)
using terms from application "Mail"
on run
tell application "Mail" to set sel to selection
tell application "Mail" to set selBox to selected mailboxes of message viewer 1
tell me to perform mail action with messages (sel) in mailboxes (selBox)
end run
end using terms from
When running it from Script Editor.app (so it goes through the on run and tell me to) and a small number of Junk messages select in Mail (this is under Mac OS X 10.5.8 Leopard), it seems to work for the first message (opening a new redirected message, w/to recipient set, and CC/BCC fields emptied), and the other redirected message windows open, but their To/CC/BCC fields are not updated and Script Editor.app pops up the dialog with the "Mail got an error: AppleEvent handler failed" error. The contents of the Event Log are as follows:
tell application "Mail"
get selection
{message id 464214 of mailbox "Junk", message id 464213 of mailbox "Junk", message id 464211 of mailbox "Junk"}
get selected mailboxes of message viewer 1
{junk mailbox}
get junk mailbox
junk mailbox
get subject of message id 464214 of mailbox "Junk"
": Your Invitation Into a Global Directory"
get was redirected of message id 464214 of mailbox "Junk"
false
redirect message id 464214 of mailbox "Junk" with opening window
outgoing message id 400031520
make new recipient at beginning of every to recipient of outgoing message id 400031520 with properties {address:"junkmail#domain.tld"}
to recipient 1 of outgoing message id 400031520
delete every bcc recipient of outgoing message id 400031520
delete every cc recipient of outgoing message id 400031520
get subject of message id 464213 of mailbox "Junk"
"Nominate Your Favorite Products for the Community Choice Awards"
get was redirected of message id 464213 of mailbox "Junk"
false
redirect message id 464213 of mailbox "Junk" with opening window
outgoing message id 378471104
make new recipient at beginning of every to recipient of outgoing message id 378471104 with properties {address:"junkmail#domain.tld"}
"Mail got an error: AppleEvent handler failed."
So, clearly it seems like the failure is with setting the to recipients in all but the first message. Subsequent runs of the script without relaunching Mail result in failures on the first message as well.
The oddest part of this issue is that, when quitting mail after running the script, there's a hidden, blank window for each of the redirected messages (even the one that was successful) that pops up asking if you want to save changes or not. This sounds very similar to something noted in this thread, but I'm not sure what causes it.
So, what's causing this error and failure? How can I resolve it? And, for extra credit, why are the hidden, blank messages created and how can I prevent that from occurring?

Your script looks fine to me.
If I were you, I would try running the script in another OS X account on the same computer, repair permissions, look at your logs (you've already done that, but it's still a good idea), run all relevant software updates, temporarily move your ~/Library/Mail folder to eliminate it as a factor, etc. Tell me what happens, especially if it works again :)

Related

PowerShell/EWS Send message with Delayed/Deferred delivery

I have a function that sends an email (EDIT1: from an ON-PREM mailbox) using delayed delivery, via COM objects. I am trying to write an equivalent function for EWS. I got a working PoC but it has 1 glaring issue: The message sits in the sent items folder, not the outbox, until the defer date arrives, then it sends as expected.
I'm using the SendAndSaveCopy method and I tried specifying the Outbox folder. This did put the message into the Outbox, but when it sends, it doesn't get moved to the Sent Items folder.
$service = New-EwsService # .... assume this works; My RequestedServerVersion is Exchange2013
$EmailMessage = New-Object Microsoft.Exchange.WebServices.Data.EmailMessage -ArgumentList $service
$EmailMessage.Subject = 'outbox test'
$EmailMessage.Body = 'this is a test'
$EmailMessage.ToRecipients.Add('someone#somewhere.com')
$SendOn = (get-date).AddMinutes(5)
$defer = New-Object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition(
0x3FEF, # 'PR_DEFERRED_SEND_TIME',
[Microsoft.Exchange.WebServices.Data.MapiPropertyType]::SystemTime
)
$EmailMessage.SetExtendedProperty($defer,$SendOn.ToUniversalTime())
# $EmailMessage.SendAndSaveCopy([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Outbox)
$EmailMessage.SendAndSaveCopy()
Another thing I noticed was that if I open the message in Outlook while it's waiting to send, and I look at the delay delivery settings, it's not configured (in the Outlook UI). And if I hit send on that item, it immediately sends. I would assume that the config would be in the message and visible from the UI. (The expected behavior is the message in the Outbox list should be in italics until you open it, then it will return to italics if you hit send, otherwise it won't be italic and won't send when the defer time arrives).
Is there anyone who knows why the folder behavior doesn't match the MS doc?
The message.SendAndSaveCopy() line results in a call to the service. If the call is successful, the email message will be available in the caller’s Outbox folder. After the email message is sent, a copy of the message will be created in the Sent Items folder.
EDIT2: I ended up going with an alternative solution. Instead of queuing messages in the mailbox directly, I am exporting the Send-MailMessage parameter hash to XML, then using the Task Scheduler to execute at a later time, grabbing that object from cache and splatting it on the function call. Works great.
The docs you refer to are very old and the behaviour has changed. In Office 365, the deferred message is saved in Drafts folder until the time of sending, at which point it is sent and then saved to Sent Items.
Note that Outlook Object Model works against Outlook, while EWS works directly with the mailbox on Exchange.

AppleScript code for copying new email subject

I'm setting up a rule in my Mail app to execute the AppleScript below when an email from a specific sender arrives. My goal is to copy the incoming email's subject line, however, this script is copying the subject of the currently selected email in the main inbox and not the arriving email's.
Is there a better way to achieve my goal?
tell application "Mail"
set _msgs to selected messages of message viewer 0
if (_msgs is not equal to missing value) then
set _msg to first item of _msgs
set the clipboard to (subject of _msg) as string
end if
end tell
You need to use the built-in handlers that Mail exposes to access the message associated with a rule activation; selected messages of message viewer 0 just accesses the active Mail window (as you describe). Instead, use Mail's on perform mail action handler to correctly access the message. See this question (and this answer) for more information.
Here is your code, re-written to correctly copy the subject line of incoming emails that satisfy the provided rule criteria. It's working for me on macOS Catalina 10.15.5:
using terms from application "Mail"
on perform mail action with messages _msgs for rule _rule
if (_msgs is not equal to missing value) then
set _msg to first item of _msgs
set the clipboard to (subject of _msg) as string
end if
end perform mail action with messages
end using terms from

Microsoft Outlook Message When Emailing in Progress Application

There is a below code, does not work
FOR EACH customer where customer.contactmethod = 'E':
MESSAGE "EMAILING TO" customer.customerCode customer.CustomerName.
RUN Emaling.p (INPUT parameter 1,INPUT pramater 2 ....)
END.
When this above loop executes it, it messages the first customer only. The reason I found is the outlook message.
The Outlook message is below
"A program is trying to send an email message on your behalf. if this is unexpected, clikc Deny and verify your antivirus software is upto date......................................."
if user click allow/deny in the outlook message, it does not message the second customer as it is stuck in first customer.
How can I suppress this outlook message using 4gl code?
The key to that is inside your "Emaling.p" procedure. Whatever technique that code is using to send email needs to be adjusted to bypass the security check.
Or you could disable whatever it is that is popping up that message. It looks like some over-zealous Windows security setting.
In any case it has nothing much to do with the 4gl code that you have shown.
Having said that -- your code is obviously incomplete and as shown would not be expected to work at all. Maybe it doesn't really look anything like that but a more workable version of the code above would be:
FOR EACH customer NO-LOCK where customer.contactmethod = 'E': /* without the NO-LOCK you might be aggravating a transaction scoping problem... */
MESSAGE "EMAILING TO" customer.customerCode customer.CustomerName.
do on error undo, leave: /* this may help to keep processing even if errors occur */
RUN Emaling.p (INPUT parameter 1,INPUT pramater 2 ....). /* you forgot the "." and knowing the rest of the parameters might help to suggest ways to get around the reported problem */
end.
END.

Mavericks Mail Applescript Changes

Mavericks has been pretty good so far, but one truststy Applescript I'd been using for years decided it didn't wan to work anymore. The script is here:
tell application "Mail"
set the clipboard to (content of first message of ¬
inbox whose subject contains "2013-11-05") as string
end tell
The job of the script is to get the content from an email with a subject "J-List Reports 2013-11-05") (obviously this changes each day). If I change the script to look for "J-List reports" with no date it works fine, but it gets the wrong email since I can't specify the date (it looks for the first message that happens to have this string in the subject). If any numbers are in the Applescript, trying to force it to find the correct email, I get
"Mail got an error: can't get message 1 of inbox whose subject
contains 2013-11-05"
even though nothing else has changed.
Can anyone suggest a way to specify the correct mail, perhaps any mail whose subject contains "J-List reports" and whose month is 11 and whose day is 5? I spent a couple hours but couldn't get it to work for me.
This worked for me:
tell application "Mail"
content of message 1 of mailbox "[Gmail]/All Mail" of account "Gmail" where subject contains "2013-11-05"
end tell
set the clipboard to result
The messages are sorted from newest to oldest, so message 1 should be the newest message.
tell application "Mail" to messages of inbox and tell application "Mail" to messages of mailbox "INBOX" of account "Gmail" returned an empty list for some reason.
this works fine for me
tell application "Mail"
try
set the clipboard to (content of first message of ¬
inbox whose subject contains "2013-11-05") as string
on error errMsg
display dialog "an error: " & errMsg
end try
end tell
Try changing the string to something you know exists , I get the same error when I search for an email message where there are no matches. I suspect that you are not including the full error message here either
rror "Mail got an error: Can’t get message 1 of inbox whose subject contains \"2013-11-05\". Invalid index." number -1719
invalid index is important to a diagnosis because it tells us exactly what the problem is. There is no message that can be identified where the subject contains 2013-11-05
so you should use a try statement and then decided what to do from there.
Mail Version 7.0 (1816)
OS 10.9 build 13a603

AppleScript can't read Mail.app's messages

I've had a script that used to work perfectly to check if I've received an email with a certain subject (below):
tell application "Mail"
check for new mail
repeat until (background activity count) = 0
delay 0.5
end repeat
try
return subject of (first message whose read status is false and subject contains "New newsletter ordered by")
end try
end tell
Now AppleScript refuses to read emails' subjects. Any ideas why? I'm assuming there's been an update that's broken it but I can't find any information on that.
Try
return subject of (first message of inbox whose read status is false and subject contains "New newsletter ordered by")
I have a 10.7.4 computer and get an error when there is no message with those properties are found. If there is an unread message containing that subject, the script (the one that says "first message of inbox") works fine.
This seems to work for me, I first had to select the first message and then I could get the subject:
tell application "Mail"
set theInbox to inbox
set theMessage to first message of theInbox whose read status is false
tell front message viewer to set selected messages to {theMessage}
set theMessages to (get selection)
repeat with theMessage in theMessages
get subject of theMessage as string
end repeat
end tell