Email sending using PowerShell - powershell

I am trying to send the mail from PowerShell.
$EmailFrom = "xxxxxx#gmail.com"
$EmailTo = "xxxxx#gmail.com"
$Subject = "Subject"
$Body = "Body"
$filenameAndPath = "C:\Desktop\EE.txt"
$SMTPServer = "smtp.gmail.com"
$SMTPMessage = New-Object System.Net.Mail.MailMessage($EmailFrom, $EmailTo, $Subject, $Body)
$attachment = New-Object System.Net.Mail.Attachment($filenameAndPath)
$SMTPMessage.Attachments.Add($attachment)
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 587)
$SMTPClient.EnableSsl = $true
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential("xxxx#gmail.com", "password");
$SMTPClient.Send($SMTPMessage)
When I run this code I get the following exception:
Exception calling "Send" with "1" argument(s): "Failure sending mail."
At line:13 char:1
+ $SMTPClient.Send($SMTPMessage)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : SmtpException
How can I make $SMTPClient.Send() work correctly?

Is Send-MailMessage not an option for you?
You could do the following:
$EmailFrom = "xxxxxx#gmail.com"
$EmailTo = "xxxxx#gmail.com"
$Subject = "Subject"
$Body = "Body"
$filenameAndPath = "C:\Desktop\EE.txt"
$SMTPServer = "smtp.gmail.com"
Send-MailMessage -From $EmailFrom -To $EmailTo -Subject $Subject -body $Body -Attachments $filenameAndPath -SmtpServer $SMTPServer

Would this example work?
##############################################################################
$From = "YourEmail#gmail.com"
$To = "AnotherEmail#YourDomain.com"
$Cc = "YourBoss#YourDomain.com"
$Attachment = "C:\temp\Some random file.txt"
$Subject = "Email Subject"
$Body = "Insert body text here"
$SMTPServer = "smtp.gmail.com"
$SMTPPort = "587"
Send-MailMessage -From $From -to $To -Cc $Cc -Subject $Subject `
-Body $Body -SmtpServer $SMTPServer -port $SMTPPort -UseSsl `
-Credential (Get-Credential) -Attachments $Attachment
##############################################################################
Notice that it asks for credentials and also specifies to UseSSL.
It's from https://www.pdq.com/blog/powershell-send-mailmessage-gmail/

I have found when using Powershell script to send emails in Gmail you have to first log into the Gmail account and allow the location/IP address of the sending PC to send Emails. From the same PC running the script log into Gmail and there should be a security email. Click allow and then test.

Related

PowerShell - Send-MailMessage with AWS SES - Intermittent

I've been using the below script to send email and sometimes it works, sometimes it does not. I'm not sure exactly why it is intermittent and with this error:
"ERROR: The SMTP server requires a secure connection or the client was not authenticated. The server response was: Authentication required"
This is the script I'm using:
$AWS_ACCESS_KEY = "KEYYYYYYYYYY"
$AWS_SECRET_KEY = "SECRET_KEYYYYYYYYYYYYYY"
$SECURE_KEY = $(ConvertTo-SecureString -AsPlainText -String $AWS_SECRET_KEY -Force)
$creds = $(New-Object System.Management.Automation.PSCredential ($AWS_ACCESS_KEY, $SECURE_KEY))
$smtp = "email-smtp.us-east-1.amazonaws.com"
$from = "noreply#domain.com"
$to = "to_you#domain.com"
$bcc = "its_me#domain.com"
$subject = "Hello There"
$body = "Hey Friend!<br><br>"
$body += "Body<br><br>"
$body += "Regards,<br>"
$body += "Bye<br>"
#Sending email
Sleep 2
Send-MailMessage -From $from -To $to -Bcc $bcc -Subject $subject -Body $body -BodyAsHtml -SmtpServer $smtp -Credential $creds -UseSsl -Port 587
What could be the issue? Has anyone seen this before? Any log in AWS console that I could look at?
Thanks!
I also faced a similar issue managed to resolve with the below codes.
$smtpServer = "email-smtp.us-east-1.amazonaws.com"
$smtpPort = 587
$username = "************"
$password = "***********************"
$from = "alerts#test.com"
$to = "recipient#domain.com"
$subject = "Amazon SES Test Email"
$body = "Body Amazon SES Test Email"
$cc = "xyz#domain.com"
$smtp = new-object Net.Mail.SmtpClient($smtpServer, $smtpPort)
$smtp.EnableSsl = $true
$smtp.Credentials = new-object Net.NetworkCredential($username, $password)
$msg = new-object Net.Mail.MailMessage
$msg.From = $from
$msg.To.Add($to)
$msg.CC.Add($cc)
$msg.Subject = $subject
$smtp.Send($msg)
$msg.Body = $body

Sending E-Mail with attachment in PowerShell

I want to send a CSV file in this e-mail.
I can send the email with no problem, but I tried a lot to send attachment with it, but at the end the e-mail was sent without the attachment.
function sendmail($Body) {
$Smtp = New-Object System.Net.Mail.SmtpClient
$MailMessage = New-Object System.Net.Mail.MailMessage
$Smtp.Host = "smtp-server"
$MailMessage.From = "sender#example.com"
$MailMessage.To.Add("recipient#example.org")
$MailMessage.Subject = "Hello"
$MailMessage.Body = $Body
$smtp.Port = 25
$smtp.EnableSsl = $false
$Smtp.Send($MailMessage)
}
$Body = "12334"
sendmail $Body
The e-mail just have to look like this:
Hello, all the information are in the file Example.csv
Send-MailMessage has a direct way of handling the attachments. Below is the sample.
Send-MailMessage -From "User01 <user01#example.com>" `
-To "User02 <user02#example.com>", `
"User03 <user03#example.com>" `
-Subject "Sending the Attachment" `
-Body "Forgot to send the attachment. Sending now." `
-Attachment "data.csv" -SmtpServer smtp.fabrikam.com
OR, you should use System.Net.Mail.MailMessage, then you have to use:
$EmailFrom = "<user#domain.tld>"
$EmailTo = "<user#domain.tld>"
$EmailSubject = "<email subject"
$SMTPServer = "smtphost.domain.tld"
$SMTPAuthUsername = "username"
$SMTPAuthPassword = "password"
$emailattachment = "<full path to attachment file.csv>"
function send_email {
$mailmessage = New-Object System.Net.Mail.MailMessage
$mailmessage.From = ($emailfrom)
$mailmessage.To.Add($emailto)
$mailmessage.Subject = $emailsubject
$mailmessage.Body = $emailbody
$attachment = New-Object System.Net.Mail.Attachment($emailattachment, 'text/plain')
$mailmessage.Attachments.Add($attachment)
#$mailmessage.IsBodyHTML = $true
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 25)
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential("$SMTPAuthUsername", "$SMTPAuthPassword")
$SMTPClient.Send($mailmessage)
}
Refer THIS if required.

Sending Email Issue

While trying to attach the .CSV file and run the code, i get the error as "Exception calling "Send" with "1" argument(s): "Unable to send to all recipients."
I have tried with .txt file ($attachment = "\path1\test.txt") and the same code is executed without any error (but I have not received any mail)
$date_value = Get-Date -format yyyy_MM_dd
$file_Name = 'test_'+ $date_value.ToString() + '.csv'
$attachment = "\\path1\test.CSV"
$smtpserver = "server.com"
$size=((Get-item $attachment ).length) -as [Int]
$from = "mail.com"
[string[]]$To= "xyz#xyz.com"
$CC="xyz#xyz.com"
$Subject = "Test"
$body=#"
Hi,
Test
Regards,
Team
"#
$message = new-object System.Net.Mail.MailMessage ( $From , $To )
$message.CC.Add($cc)
$message.Subject = $Subject
$attach = new-object Net.Mail.Attachment($attachment)
$message.Attachments.Add($attach)
$message.body = $body
$smtp = new-object Net.Mail.SmtpClient($smtpserver)
if ($size -gt 0){
$smtp.Send($message)
}
$attach.Dispose()
$message.Dispose()
$smtp.Dispose()
Expectation: .CSV file should get attached and send in the email
Have you tried the Send-MailMessage cmdlet with the -Attachment option? Its really simple.
Send-MailMessage -To $To -From $from -Cc $CC -Subject $Subject -Attachments $attachment -Body $body -SmtpServer $smtpserver

Send-MailMessage Attachment from memory

I am trying to send attachments in Send-MailMessage without saving to disk first by using the answer I found in this thread, which points to this URL.
It says to use:
$attachment = [System.Net.Mail.Attachment]::CreateAttachmentFromString($attachmenttext,"test.txt")
But when I try to do that with Send-MailMessage instead of the complicated way it shows, I get this error:
Send-MailMessage -From "email#email.com" -To "email#email.com" -Subject "Subject" -Body $body -SmtpServer "smtp.server.local" -Port 25 -BodyAsHtml -Attachments $attachment
Send-MailMessage : Could not find file 'C:\Windows\system32\System.Net.Mail.Attachment'.
At line:3 char:1
+ Send-MailMessage -From "email#email.com" -To "email#e ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Send-MailMessage], FileNotFoundException
+ FullyQualifiedErrorId : System.IO.FileNotFoundException,Microsoft.PowerShell.Commands.SendMailMessage
Is there anyway to continue using Send-MailMessage with this method? Or is there a different method that will allow me to attach files without first saving to disk while still using send-mailmessage?
Let me first go over whats wrong. [System.Net.Mail.Attachment]::CreateAttachmentFromString outputs type System.Net.Mail.Attachment while send-mailmessage -attachments is looking for an array of strings string[]. Thats why the example will fail.
I have written a simple function so you can use the attachment you have posted in the example which creates a MailMessage and looks for attachments of type [System.Net.Mail.Attachment].
Function Try-SendMail([string[]]$To, [string]$From, [string]$SmtpServer, [int]$Port = 25, [pscredential]$SmtpCredential, [string]$Subject, [string]$Body, [System.Net.Mail.Attachment[]]$attachment, [switch]$IsBodyHTML){
[System.Net.Mail.MailMessage]$Mail = new-object System.Net.Mail.MailMessage
$To | %{$Mail.To.Add($_)}
$Mail.From = $From
$Mail.IsBodyHtml = $IsBodyHTML
$Mail.Body = $Body
$Mail.Subject = $Subject
$Attachment | %{$mail.Attachments.Add($_)}
[System.Net.Mail.SmtpClient]$SMTP = new-object System.Net.Mail.SmtpClient
$SMTP.Host = $SmtpServer
$SMTP.Port = $Port
If($SmtpCredential){
$NetCredential = New-Object System.Net.NetworkCredential
$NetCredential.UserName = $SmtpCredential.GetNetworkCredential().UserName
$NetCredential.Password = $SmtpCredential.GetNetworkCredential().Password
$SMTP.Credentials = $NetCredential
}
try{
$SMTP.Send($Mail)
}catch{
$_ | select *
}
}
you can use it like
$To = #("Person1#Test.com","Person2#Test.com")
$From = "MainGuy#PErson.com"
$Server = "SMTPSERVER.NET"
$Port = 587
$Attachments = #(
$([System.Net.Mail.Attachment]::CreateAttachmentFromString("HELLO", "Test.txt")),
$([System.Net.Mail.Attachment]::CreateAttachmentFromString("HELLO2", "Test2.txt"))
)
$SmtpCredential = Get-Credential
Try-SendMail -to $To -From $From -Subject "Hello" -Body "World" -Attachment $Attachments -SmtpServer $Server -port $Port -SmtpCredential $SmtpCredential
*Edited forgot to make [System.Net.Mail.Attachment] to [System.Net.Mail.Attachment[]] in the function parameters

Sending E-mail to Multiple Recipients with Authentication

I am trying to send an e-mail through Powershell. I can send e-mails to one recipient without a problem using the code below. However, when I add a second recipient to the $EmailTo variable, I do not get the e-mail. I do not get any errors either. I did some research and it appears that the SMTP Client way of sending e-mails does not take multiple recipients.
$EmailFrom = "sender#email.com"
$EmailTo = "recipient1#email.com"
$EmailBody = "Test Body"
$EmailSubject = "Test Subject"
$Username = "carlos#email.com"
$Password = "12345"
$Message = New-Object Net.Mail.MailMessage($EmailFrom, $EmailTo, $EmailSubject, $EmailBody)
$SMTPClient = New-Object Net.Mail.SmtpClient("smtp.com", 123) #Port can be changed
$SMTPClient.EnableSsl = $true
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential($Username, $Password);
$SMTPClient.Send($Message)
I tried with the Send-MailMessage command but it is giving me issues.
Send-MailMessage -from $EmailFrom -to $EmailTo -Subject $EmailSubject `
-smtpserver smtp.com -usessl `
-credential (new-object System.NetworkCredential("$Username","$Password"))
The error I get with this is
Cannot find type [System.NetworkCredential]...
Any ideas on what the best way to send emails to multiple recipients with authentication would be?
Make sure you separate your $EmailTo address list with commas and don't pass as an array. i.e:
Do this:
$EmailTo = "recipient1#email.com,recipient2#email.com"
Don't do this:
$EmailTo = "recipient1#email.com","recipient2#email.com"
or this:
$EmailTo = "recipient1#email.com;recipient2#email.com"
That last one would throw the following exception which you'd easily notice:
New-Object : Exception calling ".ctor" with "4" argument(s): "The specified string is not in the form required for an e-mail address."
The class name is System.Net.NetworkCredential, not System.NetworkCredential.
Change this:
Send-MailMessage -from $EmailFrom -to $EmailTo -Subject $EmailSubject `
-smtpserver smtp.com -usessl `
-credential (new-object System.NetworkCredential("$Username","$Password"))
into this:
Send-MailMessage -From $EmailFrom -To $EmailTo -Subject $EmailSubject `
-SmtpServer smtp.com -UseSsl `
-Credential (New-Object Net.NetworkCredential($Username, $Password))
and the problem should disappear.