使用 Send-MailMessage 发送电子邮件有效,但不适用于 SmtpClient

E-Mail sending with Send-MailMessage works, but not with SmtpClient

以下 Powershell 脚本适用于我的 Windows Server 2012:

send-mailmessage -from "from@domain.com" -to "to@domain.com" -Subject "test" -Body "test body" -smtpserver myhostip -credential "mydomain\myuser"

当我执行它时,出现 window 提示输入指定用户的密码。我输入密码并发送电子邮件。

但是,以下脚本不起作用:

$smtp = New-Object Net.Mail.SmtpClient("myhostip")
$smtp.usedefaultcredentials = $false
$smtp.enablessl = $false
$smtp.credentials = new-object net.networkcredential("myuser", "mypassword", "mydomain")
$smtp.send("from@domain.com", "to@domain.com", "test", "test body")

它导致错误消息

Exception calling "Send" with "4" argument(s): "Mailbox unavailable. The server response was: 5.7.1
<to@domain.com>... Relaying denied. IP name lookup failed [ip-address-of-my-web-server]"

有什么区别?我怎样才能让第二个脚本工作?

您是否尝试过将其全部转换为变量并将变量插入到第一个脚本中,这行不通吗?