Send email via Powershell and Outlook - email

I have a .msg file on my filesystem. With powershell I can open a Outlook window with the message simply like this:
Invoke-Item "MY MAIL.msg"
How to change the subject and forward it to a given address via Powershell?
Thanks in advance

We had a problem that required the email to be forwarded from Outlook, there was 3000~ emails to do.
The answer Iain had given led me down the path to success, so thank you.
However it did not work for me as given, it failed. I noticed that you need to save the method of the forward to a variable and then execute the code from that, below is my complete script for looping through each msg file in a folder and forwarding it to a person.
I also left the subject as it was and gave no body as this was not needed.
#Open Outlook and get a list of emails to forward
$Outlook = New-Object -comObject Outlook.Application
$Emails = Get-ChildItem -Path C:\Users\APerson\Documents -Filter *.msg
#Loop through each email and open it up
Foreach($Email IN $Emails){
$Message = $Outlook.Session.OpenSharedItem($($Email.FullName))
$Forward = $Message.Forward()
$Forward.Recipients.Add('a.person#gmail.com')
$Forward.Send()
#Sleep is optional :D
Start-Sleep -Seconds 1
}
#Close Outlook
$Outlook.Quit()
Also noticed if you have a security policy applied to Outlook that is stopping you from running this script, for example it will remove the Add() on recipients, just import these registry settings (can be saved as a reg file):
Windows Registry Editor Version 5.00
[HKEY_CURRENT_USER\Software\Policies\Microsoft\office\14.0\outlook\security]
"PromptOOMSend"=dword:00000002
"PromptOOMAddressBookAccess"=dword:00000002
"PromptOOMAddressInformationAccess"=dword:00000002
"PromptOOMMeetingTaskRequestResponse"=dword:00000002
"PromptOOMSaveAs"=dword:00000002
"PromptOOMFormulaAccess"=dword:00000002
"PromptSimpleMAPISend"=dword:00000002
"PromptSimpleMAPINameResolve"=dword:00000002
"PromptSimpleMAPIOpenMessage"=dword:00000002

You could try something like this, works with outlook 2010
$ol = New-Object -comObject Outlook.Application
gm -InputObject $ol
$mail = $ol.Session.OpenSharedItem("C:\Users\fred\Desktop\Test Email Subject.msg")
$mail.Forward()
$Mail.Recipients.Add("fred#bloggs.com")
$Mail.Subject = "Test Mail"
$Mail.Body = " Test Mail 22222 "
$Mail.Send()

In PowerShell 2.0 there is a Send-MailMessage cmdlet that allows you to attach files, specify a subject and a recipient e.g.:
Send-MailMessage -smtpServer smtp.doe.com -from 'joe#doe.com' `
-to 'jane#doe.com' -subject 'Testing' -attachment foo.txt
Not sure how that plays with .msg files but you might give it a try.

Related

Simple Email Message to an 0365 email Acccount

I know that the Send-MailMessage ins powershell is already obsolete based on the https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/send-mailmessage?view=powershell-7.3
enter image description here
Is there any alternate way to send email message? its fine if there is no attachment, just an email message that successfully received by recipient like Hello World? I will appreciate any sample or assistance. I'm still learning PowerShell.
I've tried using the Mimekit and MailKit but it seems it doesn't work for me. Maybe there is other way which is much simpler. Thank you in advance guys
Based on the Youtube Video - https://www.youtube.com/watch?v=wy5vs0gEei0
Mimekit and Mailkit works for me fine.
Below the Example from the Youtube Video, hope it will help you
Add-Type -Path "C:\Temp\MailKit\mimekit.3.4.2\lib\netstandard2.0\MimeKit.dll"
Add-Type -Path "C:\Temp\MailKit\mailkit.3.4.2\lib\netstandard2.0\MailKit.dll"
$SMTP = New-Object MailKit.Net.Smtp.SmtpClient
$Message = New-Object MimeKit.MimeMessage
$Builder = New-Object MimeKit.BodyBuilder
# Create Credentials File
Get-Credential | Export-Clixml -Path C:\Temp\SendMail.xml
$Account = Import-Clixml -Path C:\Temp\SendMail.xml
$Message.From.Add("from#from.com")
$Message.To.Add("to#to.com")
$Message.Subject = "Test Message"
$Builder.TextBody = "This is a test Email message"
$Message.Body = $Builder.ToMessageBody()
$SMTP.Connect("smtp.office365.com", 587, $false)
$SMTP.Authenticate($Account)
$SMTP.Send($Message)
$SMTP.Disconnect($true)
$SMTP.Dispose()

Suppressing Outlook "This program is trying to access E-mail" pop-up for specific powershell script only

When I run the following powershell script to send an e-mail :
$Outlook = New-Object -ComObject Outlook.Application
$file = Get-ChildItem -Path "H:\TP65655\IDX CVA\UAT" -Include *.idx -Recurse | Where {$_.CreationTime -gt (Get-Date).AddDays(-1)}
$atts = $file.fullname
$Mail = $Outlook.CreateItem(0)
$Mail.To = "email#domain.com"
$Mail.Subject = "Testing E-mail Automation"
$Mail.Body = "UAT TEST"
Try
{
$Mail.Attachments.Add($atts)
$Mail.Send()
Write-Host "Mail Sent Successfully"
Read-Host -Prompt “Press Enter to exit”
}
Catch
{
Write-Host "File Not Attached Successfully, Please Try Again"
Read-Host -Prompt “Press Enter to exit”
Exit
}
The following pops up from Outlook :
Pop Up from Outlook
Is there any way I can remove this without changing the programmatic access in Trust Center to "Never" as this is an organization desktop and that option is not feasible.
You get a standard security prompt in Outlook. Your options are:
Use the Outlook Security Manager component which allows to disable such warnings at run-time dynamically.
Use a low-level API on which Outlook is based on - Extended MAPI. It doesn't throw security warnings or pop-ups. Or just consider using any wrapper around a low-level API such as Redemption.
Develop a COM add-in which has access to the trusted Application object. COM add-ins don't trigger such security prompts.
Deploy security settings via GPO.
Install any antivirus software with latest updates.
You may find the "A program is trying to send an e-mail message on your behalf" warning in Outlook article in MSDN helpful.

Send email with Powershell from different mailbox

I have created a small PS script to create an email for my pipeline to send out whenever there is a deployment. the problem is i dont want the email to be sent from my personal email but from the company outlook email. i searched and saw different SMTP server names and using mail.from but i cant get it to work. can someone help me out?
param(
[Parameter(Mandatory=$true,Position=0)]
[string]$Address1,
[Parameter(Mandatory=$true,Position=1)]
[string]$Address2,
[switch]$Recurse,
[switch]$Force
)
$ol = New-Object -comObject Outlook.Application
$mail = $ol.CreateItem(0)
$Mail.Recipients.Add($Address1)
$Mail.Recipients.Add($Address2)
$Mail.Subject = "DSC Deployment in Progress"
$Mail.Body = "There is a DSC install beginning. . ."
$Mail.Send()
You need to assign a value to the SendUsingAccount property. The account can be found in the (outlook).Session.Accounts collection.
$sendSmtpAddress = "some.name#somedomain.com"
$account = $ol.session.acounts | ? { $_.smtpAddress -eq $sendSmtpAddress }
then, assign to the SendUsingAccount property before sending
$mail.SendUsingAccount = $account
$mail.Send()
Full example
$sendSmtpAddress = "some.name#somedomain.com"
$ol = new-object -comobject "outlook.application"
$account = $ol.session.accounts | ? { $_.smtpAddress -eq $sendSmtpAddress }
$mail = $ol.CreateItem(0)
$mail.recipients.add("target.user#somedomain.com") | out-null
$mail.subject = "test email"
$mail.body = "test email"
$mail.SendUsingAccount = $account
$mail.Send()
For what it's worth, I gave up trying to send email via Outlook a long time ago, it's much easier to use plain SMTP. Depending on the security policy on your local SMTP server (Exchange?), you may be able to 'send as' any user on your local domain. Ask your IT people for the name/IP of an internal SMTP server that you can use to send email, and then it's as easy as:
send-mailmessage -smtpServer (servername or IP) -from sender.name#domain.com -to #(recipient1#domain.com, recipient2#domain.com) -subject "Email Subject" -body "Email Body"
If using send-mailmessage, it's possible to set a Display Name for the sender by using the form "Display Name <sender.name#domain.com>" e.g.
-from "Deployment Alerts <sender.name#domain.com>"
Recipients will see the Display Name in their email client, rather than the SMTP address.
A couple of points that I consider to be good practice:
Depending on the config of the SMTP server, there may be little, or no verification of the 'sender' address. It is worth using a genuine account that you have access to, so that you have sight of any bounce / non-delivery reports.
Consider including something in the mail body (perhaps a footer) that mentions where the alert came from and what process generated it. This can help your successor or colleague track down the script in the future.
The assignment like
$mail.SendUsingAccount = $account
worked for me since Windows Server 2000 till Windows Server 2008 and from Outlook 2007 till Outlook 2016. Since Windows Server 2016 I've got an exception (The server threw an exception. (Exception from HRESULT: 0x80010105 (RPC_E_SERVERFAULT))).
But there is an alternative way to assign this property.
[Void] $mail.GetType().InvokeMember("SendUsingAccount","SetProperty",$NULL,$mail,$account)

Script to send new files via email from monitored folder

I'm wondering if anyone can point me in the direction of how to automate the sending of newly added files located in a monitored folder via email (Exchange), ideally without Outlook installed on the server.
I use scripts daily to notify me of changes in a watched folder via email, but none of these actually attach the files on the email, and at best only list the new files names etc.
We have software that outputs 3 small text files at roughly the same time day, but someone then has to email those manually to the same external address each day. I'd like to automate that process.
I'm running Server 2008 R2, and don't mind PowerShell and VB etc. Any help is appreciated.
Thank you.
This should get you going.
$watchPath = "c:\folder\"
$sendToList = #("toUser#domain.com")
$sendFrom = "fromUser#domain.com"
$emailSubject = "File '{0}' changed"
$smtpHost = "smtp.server"
$watcher = New-Object System.IO.FileSystemWatcher
$watcher.Path = $watchPath
$watcher.IncludeSubdirectories = $false
$watcher.EnableRaisingEvents = $true
$changed = Register-ObjectEvent $watcher "Changed" -Action {
Send-MailMessage -SmtpServer $smtpHost -To $sendToList -from $sendFrom -Subject ($emailSubject -f $eventArgs.Name) -Attachments $eventArgs.FullPath
}

Sending mail with Powershell Windows 7

I cant get this to work on a windows 7 client with powershell 2
$smtpServer = "smtp.example.com"
$msg = new-object Net.Mail.MailMessage
$smtp = new-object Net.Mail.SmtpClient($smtpServer)
$msg.From = "fromID#example.com"
$msg.ReplyTo = "replyto#example.com"
$msg.To.Add("toID#example.com")
$msg.subject = "My Subject"
$msg.body = "This is the email Body."
$smtp.Send($msg)
I am getting an exception that says "Exception calling "Send with "1" arguments" Failure Sending mail"
Anyone have any idea?
I have tried Send-MailMessage but it also fails, if I run the command on a server based windows it executes fine.
I use the same account for the procedures.
This could be due to many reasons, but one issue that I had seen this exact same error was because an anti-virus program was blocking Powershell from sending the email. Check if this is the case by looking at your anti virus logs.
Beyond that, you might want to check if firewall is fine, you can connect to the SMTP server etc.
This might work:
$ol = New-Object -comObject Outlook.Application
$mail = $ol.CreateItem(0)
$Mail.Recipients.Add("XXX#YYY.ZZZ")
$Mail.Subject = "PS1 Script TestMail"
$Mail.Body = "Test Mail"
$Mail.Send()
# you can use this for HTML-Mails
# $Mail.HTMLBody = "<HTML><HEAD>Text<B>BOLD</B> <span style='color:#E36C0A'>Color Text</span></HEAD></HTML>"
# you can use this for attache a file
# $Mail.Attachments.Add("D:\scripte\ol.txt")
For further reference.
Changing port to 25 works, but why ?