问题
I have the following program:
Function Email{
param ($to, $Subject, $Body, $Attachment)
if($process=(get-process 'outlook'))
{
kill($process)
Stop-Process $process -Force
#$namespace = $outlook.GetNameSpace("MAPI")
#$namespace.Logon("outlook")
}
$Outlook = New-Object -Com Outlook.Application
$session = $outlook.Session
$session.Logon("Outlook")
$Mail = $Outlook.CreateItem(0)
foreach ($person in $to){
$Mail.Recipients.add($person)
}
$Mail.Subject = $Subject
$Mail.Body = $Body
$Mail.Attachments.Add($Attachment)
$Mail.Send()
}
When tested in ISE and in batch, it functions as expected. However, when used in another powershell script, it randomly causes the script to hang up and I cannot open outlook manually due to an error about multiple instances.
How can I re-write this to properly account for an instance of outlook running (or at least so that it doesn't cause a script that uses it to hang up)?
Update: I have also tried it as:
Function Email{
param ($to, $Subject, $Body, $Attachment)
$Creds = Import-CliXml c:\localdata\cred.clixml
$username= myemail
Send-MailMessage -To $to -subject $Subject -body $Body -Attachment $Attachment -UseSsl -Port 587 -SmtpServer smtp.office365.com -From $username -Credential $creds
}
and I cannot get past the "cannot connect to remote server" error
Running telnet smtp.office365.com 587 or telnet smtp.office365.com 25 doesn't seem to return anything.
来源:https://stackoverflow.com/questions/60296033/use-powershell-to-send-an-email-in-outlook-without-locking-up-if-outlook-is-alre