Use powershell to send an email in outlook without locking up if Outlook is already running

*爱你&永不变心* 提交于 2020-02-25 04:20:55

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!