我试图从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