简体   繁体   中英

Send email via Powershell and Outlook

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM