【发布时间】:2017-06-15 02:52:56
【问题描述】:
我正在尝试从 PowerShell 脚本发送电子邮件,但我似乎无法让它正确地通过我的 SMTP 服务器进行身份验证。
$fromEmail = 'local@example.com';
$toEmail = 'remote@example.net';
$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 <remote@example.net>: Relay access denied"
At line:1 char:1
+ $server.Send($fromEmail, $toEmail, $subject, $content);
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : SmtpException
如果我尝试使用 Thunderbird 或 PHP 的 Swiftmailer 以及相同的服务器和凭据设置发送电子邮件,它工作正常。从后缀日志来看,似乎 SmtpClient 甚至没有尝试进行身份验证,而只是尝试匿名发送邮件。
这就是 Thunderbird 制作的一个好的日志条目的样子:
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, sasl_username=local@example.com
而 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 <remote@example.net>: Relay access denied; from=<local@example.com> to=<remote@example.net> 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 不发送认证让邮件通过?
【问题讨论】:
-
How to pass credentials to the Send-MailMessage command for sending emails 的可能重复项 - 特别是您可能需要使用 SSL,或者您可能需要将新对象的参数放在括号中
$credentials = New-Object System.Net.NetworkCredential ($mailUser, $mailPassword) -
我启用了 SSL。添加括号没有任何区别。
标签: powershell email authentication smtpclient