我試圖從PowerShell腳本發送一封電子郵件,但我似乎無法讓它正確驗證我的SMTP服務器。爲什麼SmtpClient不能在我的powershell腳本中進行身份驗證?
$fromEmail = '[email protected]';
$toEmail = '[email protected]';
$mailUser = 'myUsername';
$mailPassword = 'myPassword';
$smtpServer = 'smtp.example.com';
$smtpPort = 587;
$content = 'Email message content';
$subject = 'Email message subject';
$credentials = New-Object System.Net.NetworkCredential $mailUser, $mailPassword;
$server = New-Object System.Net.Mail.SmtpClient $smtpServer, $smtpPort;
$server.UseDefaultCredentials = $false;
$server.EnableSSL = $true;
$server.Credentials = $credentials
$server.Send($fromEmail, $toEmail, $subject, $content);
當我嘗試在PowerShell提示符下運行上述內容時,它會導致指定中繼訪問被拒絕的錯誤。
Exception calling "Send" with "4" argument(s): "Client does not have permission to submit mail to this server. The
server response was: 4.7.1 <[email protected]>: Relay access denied"
At line:1 char:1
+ $server.Send($fromEmail, $toEmail, $subject, $content);
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : SmtpException
如果我嘗試發送使用Thunderbird或PHP的Swiftmailer和相同的服務器和憑證設置的電子郵件,它工作正常。從查看後綴日誌看來,好像SmtpClient甚至不嘗試進行身份驗證,而只是試圖匿名發送郵件。
這是雷鳥取得了良好的日誌條目的樣子:
Jun 14 21:17:42 services postfix/submission/smtpd[16653]: connect from unknown[xxxx]
Jun 14 21:17:43 services postfix/submission/smtpd[16653]: 59074F96E: client=unknown[xxxx], sasl_method=PLAIN, [email protected]
而由SmtpClient該數據項的樣子:
Jun 14 22:11:16 services postfix/submission/smtpd[16824]: connect from unknown[xxxx]
Jun 14 22:11:16 services postfix/submission/smtpd[16824]: NOQUEUE: reject: RCPT from unknown[xxxx]: 454 4.7.1 <[email protected]>: Relay access denied; from=<[email protected]> to=<[email protected]> proto=ESMTP helo=<WTFv2>
作爲測試,我也嘗試通過Gmail地址發送郵件使用我的gmail憑證,並且由於沒有驗證也失敗了。
Exception calling "Send" with "4" argument(s): "The SMTP server requires a secure connection or the client was not
authenticated. The server response was: 5.5.1 Authentication Required. Learn more at"
At line:1 char:1
+ $server.Send($fromEmail, $toEmail, $subject, $content);
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : SmtpException
我在這裏錯過了什麼?爲什麼.net SmtpClient不發送驗證以允許郵件通過?
可能重複的[如何將憑證傳遞給Send-MailMessage命令以發送電子郵件](https://stackoverflow.com/questions/12460950/how-to-pass-credentials-to-the-send-mailmessage-命令發送電子郵件) - 特別是你可能需要使用SSL,或者你需要把你的參數放在新對象的$ param中:$ credentials = New-Object System.Net.NetworkCredential($ mailUser,$ mailPassword) ' – TessellatingHeckler
我啓用了SSL。添加括號沒有任何區別。 – kicken