如何通过Powershell脚本发送电子邮件而无需身份验证?

发布时间:2020-07-06 06:03

我正在尝试使用Powershell在不进行身份验证的情况下自动发送电子邮件,因为我使用的发件人ID是服务帐户,不需要密码。

下面是我的Powershell代码

$smtpServer = "<SMTP Server>"
$smtpFrom = "<from email id - this is a service account and has no password>"
$smtpTo = "<to email id>"
$messageSubject = "Test"
$messageBody = "Test"

$smtp = New-Object Net.Mail.SmtpClient($smtpServer)
$smtp.Send($smtpFrom,$smtpTo,$messagesubject,$messagebody)

当我执行此powershell脚本时,出现以下错误

Exception calling "Send" with "4" argument(s): "Failure sending mail."
At <Script_Locaion>\email1.ps1:13 char:1
+ $smtp.Send($smtpFrom,$smtpTo,$messagesubject,$messagebody)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : SmtpException

有指针吗?

谢谢。

回答1

您需要检查邮件服务器日志,以找出不接受邮件的原因。

BTW:您还可以使用内置的Send-MailMessage命令,该命令使用相同的库。但是,Microsoft都将System.Net.Mail和Send-MailMessage命令标记为过时的,建议不要再使用它。

回答2

我正在使用New-Object System.Net.Mail.MailMessage,但我的SMTP服务器已配置为从本地网络发送而没有密码(仅当用户名和邮箱存在时)。

$Encoding = [System.Text.Encoding]::UTF8

$MailFromSup = "from@mail.com"
$MailToSup = "to@mail.com"
$MailSubj = "SUBJECT"
$MailTextSup = "MAIL BODY"
$MailSMTPServer = "ourserver.mail.com"
$MailSMTPPort = "25"

$SMTPMessageSup = New-Object System.Net.Mail.MailMessage $MailFromSup, $MailToSup, $MailSubj, $MailTextSup
$SMTPMessageSup.BodyEncoding = $Encoding
$SMTPMessageSup.SubjectEncoding = $Encoding
$SMTPClient = New-Object net.mail.smtpclient($MailSMTPServer,$MailSMTPPort)
$SMTPClient.Send($SMTPMessageSup)