简体   繁体   中英

Send email via SMTP Mail server

I have installed SMTP Virtual Server in windows server 2012 r2. Later I have used following PowerShell script to send the email. Which was successful

 $email = "xxxxxxxxxx@xxxxxx.com" $pass = "xxxxxxx" $smtpServer = "smtp.office365.com" $smtpPort = "25" $msg = new-object Net.Mail.MailMessage $smtp = new-object Net.Mail.SmtpClient($smtpServer) $smtp.EnableSsl = $true $msg.From = "$email" $attachment = New-Object Net.Mail.Attachment("C:abcd/123.txt"); $msg.Attachments.Add($attachment); $msg.To.Add("xxxx@xxxxx.com") $msg.BodyEncoding = [system.Text.Encoding]::Unicode $msg.SubjectEncoding = [system.Text.Encoding]::Unicode $msg.IsBodyHTML = $true $msg.Subject ="List of users" $msg.Body=$msg.Body = "<h2> hi everyone </h2> $SMTP.Credentials = New-Object System.Net.NetworkCredential("$email", "$pass"); $smtp.Send($msg) 

here my question is can I send email without using from address in the above script(Is there any chance to save from email address and credentials somewhere in SMTP virtual server settings so that script can take credentials directly). I don't want to use from email address and credentials in above script

I'd suggest using Send-MailMessage instead of manual .NET manipulation:

$Creds = Import-CliXml -Path 'C:\mycreds.xml'

$MailArgs = @{ 'SmtpServer'  = 'smtp.office365.com'
               'Port'        = 25

               'To'          = 'xxxx@xxxxx.com'
               'From'        = $Creds.UserName
               'Subject'     = 'List of users'

               'Attachments' = 'C:\abcd\123.txt'
               'Body'        = '<h2> hi everyone </h2>'
               'Encoding'    = [Text.Encoding]::Unicode
               'BodyAsHtml'  = $true

               'UseSsl'      = $true
               'Credential'  = $Creds
             }
Send-MailMessage @MailArgs

And you would create your $Creds object as follows:

Get-Credential -Credential 'xxxxxxxxxx@xxxxxx.com' | Export-CliXml -Path 'C:\mycreds.xml'

There are a couple extra options you might be interested in (such as notification of delivery) you can read about in the doc linked above.

Additionally, your password is encrypted when exported using Export-CliXml specific to that device and account utilizing DPAPI .

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