PowerShell/EWS Send message with Delayed/Deferred delivery - powershell

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.

Related

Powershell S/MIME

Currently, each day my business needs to send and encrypted email using MS Outlook. The process works, but obviously the whole 'doing it every day thing' sucks. I've tried looking up ways to automate the process which has helped me solve the surrounding processes, but i still can't find anything, or whip up anything myself which will handle the email side. The flow of events are;
Receive
Encrypted email is received
Email is opened and attachment is dragged to UNC share 1 (repeated for each email recieved)
Attachment is picked up and processed by surrounding script
Send
Browse UNC share 2
Copy 1 of x files to a new email
Set subject as full file name
Select email to be signed/encrypted in top ribbon
Send email and repeat for each file in UNC share 2
I can get emails to send with attachment via powerhsell and by using S/MIME, but once I combine the two I get stuck and the script turns to rubble :(
Any help at all would be greatly appreciated
If I'm not mistaken, Powershell can load and use .NET assemblies, correct? (I'm not a powershell user, so my knowledge is limited).
Given that, I would recommend taking a look at using the MimeKit and MailKit libraries.
Check out the MimeKit README for some examples on how to use the S/MIME API's.
MimeKit comes with a WindowsSecureMimeContext which you might be able to use out of the box, but that depends on where your private keys and certificates are stored. If they aren't in the X509Store, then you could use the TemporarySecureMimeContext and simply load the certificate(s) and private key(s) into that and use it.
Got a similar problem and here's my solution so far, still testing:
$Outlook = New-object -ComObject Outlook.Application
$Mail = $Outlook.CreateItem(0)
$Mail.To = "me#company.tld"
$Mail.Subject ="Test"
$Mail.Body ="Test Body"
# 0 = nothing, 1 = encrypt, 2 = sign, 3 = both!
$PR_SECURITY_FLAGS = "http://schemas.microsoft.com/mapi/proptag/0x6E010003"
$Mail.PropertyAccessor.SetProperty($PR_SECURITY_FLAGS, 3)
$Mail.Send()
If Outlook is running, everything works fine. But when I start Outlook afterwards, I will find the created Mail in the Outbox without encryption and not signed.
Without Outlook running, the Code would produce an "InvokeMethodOnNull"-Error. Putting a $Mail.Display() before the SetProperty()-Part would take care of that and the buttons seem to be checked in the opening E-Mail, but the result will be the same: Start Outlook and your mail is in Outbox without encryption and not signed.

Email notification upon ticket modification in Fossil

I need to receive an email notification whenever a user creates a ticket or a ticket gets updated. Fossil has something called ticket hook, which is accessible in the UI from admin -> transfers -> Ticket. I have tried the following code from here:
set project simpletask
tclInvoke package require http
query {SELECT title, status
FROM ticket
WHERE tkt_uuid=$uuid} {
set title [tclInvoke http::formatQuery $title]
http -asynchronous -- http://127.0.0.1/cgi-bin/tkt-hook?uuid=$uuid&title=$title&status=$status&project=$project
}
I expect this code to be executed once a ticket is modified, but I don't really know how to modify it to send an email, and how I can specify to whom the email should be sent to.
Does anyone have a sample TH1 code for sending email notifications that can share?
TH1 is not able to do this on its own; it's too limited (and deliberately so). If you've got invocation of Tcl enabled in TH1 (it's not enabled by default) then you can use something like:
### THIS IS TH1 ###
tclInvoke source /some/dir/scripts/emailsender.tcl
query {SELECT title, status
FROM ticket
WHERE tkt_uuid=$uuid} {
tclInvoke send_email $title $status $uuid
}
Then you just need to make sure that your emailsender.tcl script (in the above location) defines a procedure send_email that does what you want. You're talking about something like this:
### THIS IS TCL ###
package require mime
package require smtp
# Where to route messages through; IMPORTANT!
variable smtp_host smtp.example.com
proc send_email {title status uuid} {
variable smtp_host
set t [mime::initialize -canonical text/plain \
-string "state is now $status for $uuid"]
mime::setheader $t Subject "Change to '$title'"
smtp::sendmessage $t -recipients you#example.com -servers $smtp_host
mime::finalize $t
}
You'll need to pass across more fields, insert more logic to generate a message, choose who to send the message to (a mailing list is a good start!) and so on, but that's the core of it all. You may also need to explicitly lappend the directory containing the Tcllib packages to the global auto_path; that script is going to be very specific to your configuration.
Or you could make a script that listens to that port you push a notification to using the sample script and work with that. That would be easier to abuse though; not recommended.
I just followed IFTTT approach, where we used IFTTT service to connect rss feed of Fossil scm to Gmail channel. It worked.
Please refer:
http://lists.fossil-scm.org:8080/pipermail/fossil-users/2013-August/013330.html
https://ifttt.com/recipes/109526
https://ifttt.com/recipes/109526 --> is for email notification for New ticket, that can be modified (change keyword or simple phrase) to send email for any ticket modification.

Sending a notification when an email is received in Exchange 2007

One of our departments is requesting to receive a notification whenever an email is sent to a particular inbox. So every time an email is sent to mailbox#mycompany.com, they want an email sent to a distribution list saying "A message has arrived."
Is this possible in Exchange 2007 using a Powershell script?
Sounds to me like this is just a matter of creating a rule in Exchange.
Running through the "Rules Wizard":
Check messages when they arrive
through the specified account (select account associated with mailbox#mycompany.com)
run a script (something that will send out the new "A message has arrived." email)
OR forward/redirect it to people or distribution list
Use a transport rule
$condition = Get-TransportRulePredicate From
$condition.addresses = 'someone#contoso.com'
$action = Get-TransportRuleAction CopyTo
$action.addresses = 'otherperson#contoso.com'
New-TransportRule -Name "Notify New Message Recieved" -Conditions $condition -Actions $action

how to notice if a mail is a forwarded mail?

I have a very special problem.
If we create a mail in Outlook, we add a UserProperty which contains a DataBase-ID of our System, so we can Link the mail to the representing DataBase-Item. On the service which reads the mails in each Mailbox and imports them automatically I can read this property by using ExtendedPropertyDefinitions. So far everything is fine...
If the User now forwards the message in Outlook, Olk copies the UserProperty to the new message. And now my problems beginn. Now my Service thinks the new message is also linked to our database and updates DB-Entry with the new Body and new Subject.
So does anyone now how to find out if a message is a forwarded one or how to tell Outlook not to copy the userproperty to the forwarded (new) message?
thx. Jay
What we thought about, but isnt working for our case
- a second userproperty containing a simple tag linke "fromSystem". Cause this would be copied too.
- a second userproperty containing a hashsum calculated from subject and Body. Cause both could be changed by the user. We just create the message, add all properties and Display it. from this Point on we no longer have control what is Happening to the mail until the Service handles it.
Your service consuming EWS should check the ConversationIndex and only update the database if it's 22 bytes long (original source message). Forward emails and reply emails keep appending 5 bytes (10 chars) to the ConversationIndex extending it beyond 22 bytes.
Sample ConversationIndexes
Original: 01CDD15D80E51C1D4522172840ACA96287DA28A15D97
Reply: 01CDD15D80E51C1D4522172840ACA96287DA28A15D970000018630
Forward: 01CDD15D80E51C1D4522172840ACA96287DA28A15D970000018630000000FC30
ConversationIndex represents the sequential ordering of the ConversationTopic (essentially GUID + timestamp). See Working with Conversations on MSDN. ConversationIndex is explicitly defined on MSDN here.
if (message.ConversationIndex.Length == 22)
{
// update DB body, subject, etc.
}
Also make sure you load the EmailMessageSchema.ConversationIndex before trying to access its value.

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

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 :)