2016-09-12 63 views
-1

我正在研究一個通過PowerShell向人們發送電子郵件的腳本。它在一些計算機上發送得很好,但在其他計算機上它卻不發送,我知道兩臺計算機的配置都不完全相同。通過PowerShell發送電子郵件不起作用

我不明白爲什麼。

我試着在命令的末尾添加2 >> c:\ error.txt並且它沒有記錄任何東西。

我的代碼(我換筒出於保密原因SMTP和電子郵件):

  File.Delete(@"C:\Temp\Email2Send.ps1"); 
      var strVar_EMAIL_BOX = "m[email protected]"; 
      TextWriter tw = new StreamWriter(@"C:\Temp\Email2Send.ps1"); 
      tw.WriteLine("$OutputEncoding = [Console]::OutputEncoding"); 
      tw.WriteLine("$smtp = \"forwarder.mail.xxxxxx.com\""); 
      tw.WriteLine("$to = \"" + To + "\""); 
      tw.WriteLine("$from = \"" + strVar_EMAIL_BOX + "\""); 
      tw.WriteLine("$enc = [System.Text.Encoding]::UTF8"); 
      tw.WriteLine("$subject = \"Suivi\""); 
      tw.WriteLine("$body = \"" + Body + "\""); 
      tw.WriteLine(@"send-MailMessage -SmtpServer $smtp -To $to -From $from -Subject $subject -Body $body -BodyAsHtml -Encoding $enc 2>> c:\errors.txt"); 
      tw.Close(); 
     } 

     System.Diagnostics.Process process = new System.Diagnostics.Process(); 
     System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo(); 
     startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; 
     startInfo.FileName = "cmd.exe"; 
     startInfo.Arguments = @"/C powershell -ExecutionPolicy Bypass -WindowStyle Hidden -command c:\Temp\Email2Send.ps1"; 
     process.StartInfo = startInfo; 
     process.Start(); 

編輯:沒關係我找到了解決辦法2秒發佈之後。出於某種原因,PowerShell在Windows路徑中的某些計算機上未正確鏈接。將PowerShell更改爲:%SYSTEMROOT%\ System32 \ WindowsPowerShell \ v1.0 \ powershell.exe

+1

爲什麼使用cmd運行powershell? powershell已經是一個可執行文件。運行cmd只是爲了運行powershell是多餘的。 –

+1

爲什麼當C#有一個完美的[SmtpClient]時,你使用C#通過PowerShell發送郵件(https://msdn.microsoft.com/en-us/library/system.net.mail.smtpclient(v = vs.110) ).aspx)類? – itsme86

+0

是的,我使用Powershell,因爲使用c#發送的電子郵件在此網絡上被阻止。這只是奇怪的... – Guillaume

回答

0

我在發佈後2秒找到解決方案。出於某種原因,PowerShell在Windows路徑中的某些計算機上未正確鏈接。將PowerShell更改爲:%SYSTEMROOT%\ System32 \ WindowsPowerShell \ v1.0 \ powershell.exe