Forward emails with PowerShell and EWS Managed API - powershell

I have a PowerShell Script that uses EWS Managed API to fetch and processes specific emails from an inbox. If an email doesn't meet a condition its then forwarded to another inbox. the script works fine, but if it finds emails with attachments (that don't meet condition), it gets stuck to Draft folder and doesn't get sent. Any ideas?
The part of the code that forwards the emails.
Else {
$mail = New-Object Microsoft.Exchange.WebServices.Data.EmailMessage($service)
$OriginalEmail = $findResults.Items[0]
$psPropset= new-object Microsoft.Exchange.WebServices.Data.PropertySet([Microsoft.Exchange.WebServices.Data.BasePropertySet]::IdOnly)
$psPropset.Add([Microsoft.Exchange.WebServices.Data.ItemSchema]::MimeContent)
$psPropset.Add([Microsoft.Exchange.WebServices.Data.ItemSchema]::Subject)
$OriginalEmail.Load($psPropset)
# Delete Received email after gathering the data
$findResults.delete([Microsoft.Exchange.WebServices.Data.DeleteMode]::MoveToDeletedItems,$True)
$AtColtype = ("Microsoft.Exchange.WebServices.Data.AttachmentCollection") -as "Type"
$Emailtype = ("Microsoft.Exchange.WebServices.Data.EmailMessage") -as "Type"
$methodInf = $AtColtype.GetMethod("AddItemAttachment");
$AddItmAttachMethod = $methodInf.MakeGenericMethod($Emailtype);
$EmailAttachment = $AddItmAttachMethod.Invoke($mail.Attachments,$null);
$EmailAttachment.Item.MimeContent = $OriginalEmail.MimeContent
$PR_Flags = new-object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition(3591, [Microsoft.Exchange.WebServices.Data.MapiPropertyType]::Integer);
$EmailAttachment.Item.SetExtendedProperty($PR_Flags,"1");
$EmailAttachment.Name = $OriginalEmail.Subject;
$mail.Subject = "$Subject";
$mail.ToRecipients.Add($ForwardToEmail);
$mail.SendAndSaveCopy();
$mail.Close()
}
Any help is appreciated.

Related

How to add a certificate to a local Outlook contact using Powershell?

I am trying to sort out current contacts in Outlook to replace encryption certificates. But it is not clear how to prepare the object?
# В var $contactList collect contacts from Outlook
foreach ( $name in $contactList ) {
$PR_x509_Certificate = ('http://schemas.microsoft.com/mapi/proptag/0x3A701102');
# Create new contact
$NewContact = $Outlook.CreateItem('olContactItem');
# Get email, name, fullname from old contact
$NewContact.Email1Address = $name.Email1Address;
$NewContact.FullName = $name.FullName;
$NewContact.FirstName = $name.FirstName;
# Import certificate from из .cer file
$NewCertUser = New-Object system.security.cryptography.x509certificates.x509certificate2;
$NewCertUser.Import($PathToCerFile);
# Try add sertificate, but no success :(
$result = $NewCertUser.RawData;
$o = New-Object BuildProperty($result);
$NewContact.PropertyAccessor.SetProperty($PR_x509_Certificate, $o);
# Save new contact
$NewContact.Save();
# Delete old
$name.Delete();
}
I'm trying to update this:
It should be possible to do that on the users certificate store certmgr.msc without even touching Outlook:

How to add signature to powershell code creating new mail?

I want signatures to show up when creating new message as they do with Ctrl+N?
Here is my code:
$Outlook = New-Object -ComObject Outlook.Application
$Mail = $Outlook.CreateItem(0)
$Mail.To = "random.dude#email.com"
$Mail.Subject = "data for Subject"
$Mail.Body ="Example of body..."
$Mail.Signature = "Primary"
$inspector = $mail.GetInspector
$inspector.Display()
You could refer to the below code:
$Signature = "`n`nBest Regards,`nYourName`nyour#email.com"
$Mail.Body = "Si comunica che i pacchetti harvest $esito.`nSi rimanda alle verifiche del caso `nSaluti$Signature"
For more information, Please refer to this link:
Powershell email signature
The signature is added when Display is called as long as the message body is unmodified.
This means you must call Display first, and then merge your data with the body that the message has at this moment.
Also keep in mind that to keep the signature formatting, you must use the HTMLBody property rather than plain text Body. And you cannot simply concatenate two HTML strings - they must be merged.
If using Redemption (I am its author) is an option, it exposes RDOSignature.ApplyTo method, which allows to insert signature into an existing message.

Create Outlook appointment on specific account with command line

I have 2 accounts in my outlook configured, one is for example foo.bar#test.com. When I try to create an appointment via commandline OUTLOOK.EXE /c ipm.appointment, the appointment dialog appears, but its not assigend one of my accounts.
I recognize that when I add participant and try to send the appointment. Then the following message appears (translated):
This appointment is not in the folder "Calendar" for this account. Responses to this appointment will not be recorded. Do you want to contiune?
How can I create an appointment which is assigend to the folder "Calendar" to one of the existing accounts?
You could refer to this code:
$fieldservices = "0000000038A1BB1005E5..."
$outlook = new-object -comobject outlook.application
$namespace = $outlook.GetNameSpace("MAPI")
$calendar = $namespace.GetStoreFromID($fieldservices).GetDefaultFolder(9)
$appt = $Outlook.CreateItem(“olAppointmentItem”)
$root=$store.GetRootFolder()
$cal=$root.Folders.Item(5)
$appt.Move($cal)
#Making the appointment a meeting
$appt.MeetingStatus = 1
#Meeting one hour from current date and time
$appt.Start = $starttime
$appt.End = $appt.Start.AddMinutes($duration)
#Adding required attendees
$appt.RequiredAttendees = $tech
$appt.Subject = "$tech - $company: $summary - $ticket"
$appt.Location = "$address1 $address2 $city $zip"
$appt.Body = $body
$appt.Send()
For more information , Please reference this link:
Powershell Create Outlook Appointment

Why might php mail sent but not received unless I manually call the script?

Why might php mail not be received in the second case where twilio is calling the page? Are there characters that might be returned from the api that make the email undeliverable?
1) If I type the URL into the broweser, it attempts to make a wav file in my recordings folder and I get the emails and text messages to all the recipients. The output below is served and the "1" indicates the message was sent.
2) If twilio calls the page and handles the xml, the actual message is recorded to my server, and the output below is served to twilio (which I have verified in my account), but no one receives the email or text. The body of the xml still shows "1" after good bye, indicating the message was sent.
My script:
<?php
date_default_timezone_set('America/New_York');
//copy the remote wav file to my server
$recording = file_get_contents($_REQUEST['RecordingUrl']);
$name = "recordings/".str_replace("+","",$_REQUEST['Caller'])."-".date('Y-m-d-G-i-s',time()).".wav";
$fh = fopen("../".$name, 'w') or die("can't open file");
$stringData = $recording;
fwrite($fh, $stringData);
fclose($fh);
//email the people that need to get the message
$to = "email1#yahoo.com";
$subject = "Voicemail from ".$_REQUEST['From'];
$message = "Click below to listen to your message:\n\r http://domain.com/twilio/".$name;
$from = "email2#domain.com";
$headers = "From:" . $from;
mail($to,$subject,$message,$headers);
$to = "email3#domain.com";
mail($to,$subject,$message,$headers);
$to = "9545555555#messaging.sprintpcs.com";
$sent = mail($to,$subject,$message,$headers);
header("content-type: text/xml");
echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n
<Response>
<Say>Thank you for your message. Good bye.".$sent."</Say>
<Hangup/>
</Response>";
?>
outputs:
<Response>
<Say>Thank you for your message. Good bye.1</Say>
<Hangup/>
</Response>
I just check to see what the contents of each variable in the php mail function are when twilio calls the script to see if there is a character present from a live twilio message. It comes out like this:
$to = 9545555555#messaging.sprintpcs.com
$subject = Voicemail from +19545555555
$message = Click below to listen to your message:
http://domain.com/twilio/recordings/19545555555-2013-10-12-22-57-03.wav
$headers = From:email2#domain.com
If I call the script manually in the browser they are:
$to = 9545555555#messaging.sprintpcs.com
$subject = Voicemail from
$message = Click below to listen to your message:
http://domain.com/twilio/recordings/-2013-10-12-23-04-37.wav
From:email2#domain.com
I tried removing the "+" out of the subject with no success, but when I removed the entire phone number from the subject it works every which way. The emails and texts are delivered appropriately. It makes no sense to me. Maybe its godaddy webhosting messing with my life again.
Perhaps the from string has bad characters that ruin the mail() call, but echo transparently. Try cleaning your string before putting it into mail().
Something like:
$subject= preg_replace("/[^a-zA-Z0-9]+/", "", $_REQUEST['From']);

how do i send an email through joomla

I have a system so folks can register for a class through my Joomla site (I believe it's 3.0). But from there, I would like to send folks an email filling variables from the registration. So something like:
Dear (name), thank you for registering for (class).
This is to remind you your class is tomorrow, (date), at (place).
I believe for the registration, the system uses authorize.net
How can I accomplish this?
Thanks for the help!!
You can use JFactory:getMailer like suggested in the following post. I'm copying here his code example (modified it a bit):
$subject = "Here is the subject of your message.";
$body = "Here is the body of your message.";
$user = JFactory::getUser();
$to = $user->email;
$from = array("me#mydomain.com", "Brian Edgerton");
# Invoke JMail Class
$mailer = JFactory::getMailer();
# Set sender array so that my name will show up neatly in your inbox
$mailer->setSender($from);
# Add a recipient -- this can be a single address (string) or an array of addresses
$mailer->addRecipient($to);
$mailer->setSubject($subject);
$mailer->setBody($body);
# If you would like to send as HTML, include this line; otherwise, leave it out
$mailer->isHTML();
# Send once you have set all of your options
$mailer->send();
That's all there is to it for sending a simple email. If you would like to add carbon copy recipients, include the following before sending the email:
# Add a blind carbon copy
$mailer->addBCC("blindcopy#yourdomain.com");
Another alternative is using JMail::sendMail: http://docs.joomla.org/API17:JMail::sendMail
Fetch the Mail Object:
`$mailer = JFactory::getMailer();`
Set a Sender
$user = JFactory::getUser();
$recipient = $user->email;
$mailer->addRecipient($recipient);
$mailer->setSender($sender);
Recipient
$user = JFactory::getUser();
$recipient = $user->email;
$mailer->addRecipient($recipient);
Create the Mail
$body = 'Body Text';
$mailer->isHtml(true);
$mailer->Encoding = 'base64';
$mailer->setBody($body);
Sending the Mail
$send = $mailer->Send();
if ( $send !== true ) {
echo 'Error sending email: ';
} else {
echo 'Mail sent';
}
https://docs.joomla.org/Sending_email_from_extensions