简体   繁体   中英

Send outlook email from powershell script

When I write the following script into the powershell command line one by one, it successfully sends the email, but when I run the script, it returns a bunch of errors. I'm guessing something syntactically needs to be changed in order to run it as a script? Any ideas?

Start-Process Outlook

$o = New-Object -com Outlook.Application


$mail = $o.CreateItem(0)

#2 = high importance email header
$mail.importance = 2

$mail.subject = “Auto Build Test“

$mail.body = “This is a test“

#for multiple email, use semi-colon ; to separate
$mail.To = “myemail@company.com"
$mail.Send()

# $o.Quit()
Param(
[parameter(Mandatory=$true)]
[alias("e")]
[string]$RecipientEmailAddress
)

if($RecipientEmailAddress -notmatch  "\b[A-Za-z0-9._%+-]+@BLAHH.com")
{
    Write-Output "the email address for the receipient of log reports is not a valid       email address, hence will not send the report via email. They can still be accessed at "   |Out-String ;
}else
{
    $returnVal= New-Object PSObject ;
    $returnVal |Add-Member -Name is_Success -MemberType NoteProperty -Value $null;
    $returnVal |Add-Member -Name Explanation -MemberType NoteProperty -Value $null;
    try{
            $Attachments =Get-ChildItem -Path "C:\FOLDERWHEREYOURAATACHMENTS ARESTORED";
            if($Attachments.count -eq 0)
            {
                 $returnVal.Explanation="Error sending log report email to the user: $RecipientEmailAddress. Please check if the C:\FOLDERWHEREYOURAATACHMENTS is accessible and there are indeed log files present";
            #Write-Output "Error sending log report email to the user: $RecipientEmailAddress" |Out-String ;
            #Write-Output "Please check if the C:\FOLDERWHEREYOURAATACHMENTS is accessible and there are indeed log files present "|Out-String;
            $returnVal.is_Success= $false;
            return $returnVal;
        }
        $TestedAttachmentsList = new-Object System.Collections.ArrayList;
        for($i=0;$i -lt $Attachments.count;$i++)
        {
           $TestedAttachmentsList.add($Attachments[$i].FullName);
        }
        Send-MailMessage -From "<FROM@BLAHH.COM>" -To "<$RecipientEmailAddress>" -SmtpServer "mail.BLAHH.com" -Attachments $TestedAttachmentsList -Subject "BLAHH SUBJECT" -Body "BLAHH BLAHH";
        $returnVal.is_Success=$true;  
        $returnVal.Explanation="An email has been sent to the $RecipientEmailAddress containing the log of the setup and configuration." 
        return $returnVal ; 
}Catch [System.Exception]
   {
        #Write-Output "Error sending log report email to the user: $RecipientEmailAddress" |Out-String ;
        #Write-Output "Please check communication between your host machine and mail.BLAHH.com on port 25 is possible"|Out-String;
        $returnVal.is_Success= $false;
        $returnVal.Explanation="Error sending log report email to the user: $RecipientEmailAddress Please check communication between your host machine and mail.BLAHH.com on port 25 is possible";
        return $returnVal ; 
}
}

The syntax doesn't change between the command line and a script file. What changes is how fast the commands are executed. If you're typing them in then there is plenty of delay between each command. But if they run from a script they get presented to Outlook much more quickly.

A simple way to fix this is add Sleep 1 (or similar) before the command that fails. Without seeing your error output I would guess that you want to sleep after CreateItem and maybe before Send. But if you look at the error messages closely you'll see they identify which line of the script failed. Put Sleep before the first line that failed. Retry the script. If a new line fails, then put a delay before it as well. If the first line still fails you can try Sleep 2 . You can also make the Sleep shorter. For 1/2 second: Sleep -milliseconds 500 .

IF adding Sleeps fixes the problems - in other words the problem is a synchronization issue, there may be something in the Outlook object model you could use that wouldn't be as hackish as using Sleeps.


I wasn't able to repro this on my Outlook 2010 installation. However I did look up an alternate method for sending email from PS (below). Maybe this method will work.

$i=$o.Session.folders.item(2).folders.item("Outbox").items.add(0)
$i.to="me@whereiwork.com"
$i.Subject="a wittle testy"
$i.Body="some body"
$i.send()

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