简体   繁体   中英

How to send an email from Powershell script without authentication?

I'm trying to use Powershell to send an email automatically without authenticating, as the From id that i use is a service account and doesn't require a password.

Below is my Powershell code

$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)

When i execute this powershell script i get the below error

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

Any pointers?

Thanks in advance.

You'll need to check the mail server logs to find out why the mail wasn't accepted.

BTW: You could also use the built-in Send-MailMessage command, which uses the same library. However both System.Net.Mail, and the Send-MailMessage command are marked as obsolete by Microsoft and they recommend to no longer use it.

Im using New-Object System.Net.Mail.MailMessage but my SMTP server is configured to send from local network without passwords (only if username and mailbox exists).

$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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM