Sending E-mail to Multiple Recipients with Authentication - email

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.

Related

Multiple Office 365 logon prompt box while running automated script

I am in the process of automating a piece of our user creation. I am trying to automate an email notification. When I pull the list of names from the CSV through PowerShell, It prompts every time for the username and password, even though I have it in the code. Is there a way around this? Code below.
$FromEmail = ""
$SmtpServer = "smtp.office365.com"
$Port = 587
$Password = ""
$SecurePassword = ConvertTo-SecureString $Password -AsPlainText -Force
# Create Credential Object
$Credentials = New-Object System.Management.Automation.PSCredential ($FromEmail, $SecurePassword)
foreach($row in $CsvData)
{
$ToEmail = "$($row."Manager Email")"
$Subject = "New User Created"
$Body = "<html><body>
<h2>Attention $($row.Manager),</h2>
<div>The following user has been created in the IT systems. </div>
<div>User: $($row."EE FIRST NAME") $($row."EE LAST NAME")</div>
<div>Title: $($row."Title")</div>
<div>Employee ID: $($row."EE ID")</div>
<div>Email: $($row."Email")</div>
<p>useful info</p>
<p>some more useful info</p>
<p>Thank you,</p>
<p>IT</p>"
[System.Net.ServicePointManager]::SecurityProtocol = 'TLS12'
Send-MailMessage -From $FromEmail -To $ToEmail -SmtpServer $SmtpServer -UseSsl -Port $Port -Credential $Credential -Subject $Subject -Body $Body -BodyAsHtml
} ```

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

Email sending using 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.

Pass Subject and Body parameter to a powershell Email script using batch file

I have a powershell script ,
[System.Net.ServicePointManager]::SecurityProtocol = 'TLS12'
$Mail_to="Jill.maclaurin#ca.ibm.com"
$Mail_from="shuddha.roy#gmail.com"
$Subject = "Test"
$Body = "Test Body"
$SMTPServer = "smtp.sendgrid.com"
Send-MailMessage -SmtpServer $SMTPServer -Port 587 -UseSsl -From $Mail_from -To $Mail_to -Subject $Subject -BodyAsHtml $body -Encoding ([System.Text.Encoding]::UTF8)
Now i want the $subject and $Body value to be obtained from a batch file and run the powershell script using that batch file, How to do it?
Add to the start of the script a Param Section, you can use default value for the required parameters, save the file.
Param(
$Subject = "Test",
$Body = "Test Body"
)
[System.Net.ServicePointManager]::SecurityProtocol = 'TLS12'
$Mail_to="Jill.maclaurin#ca.ibm.com"
$Mail_from="shuddha.roy#gmail.com"
$SMTPServer = "smtp.sendgrid.com"
Send-MailMessage -SmtpServer $SMTPServer -Port 587 -UseSsl -From $Mail_from -To $Mail_to -Subject $Subject -BodyAsHtml $body -Encoding ([System.Text.Encoding]::UTF8)
Call the PS1 file from the batch file using the required paramters, e.g:
powershell script.ps1 MySubject MyBody

Email Subject showing Encoding

I am using send-mail message to send email to our Support System.
But when it send email it shows the subject line like this screen!
=?us-ascii?Q?R899076:Aman:System Summary ?=
In Subject I am using the variable:
$vUserName = (Get-Item env:\username).Value
$vComputerName = (Get-Item env:\Computername).Value
$subject = "$vComputerName : $vUserName : System Summary"
and then
send-MailMessage -SmtpServer Smtp-local -To $to -From $from -Subject $subject -Body $body -BodyAsHtml -Priority High
But when I recieve this email in Outlook it looks fine any Idea?
Actually this a approx 150 lines script and the body of email and smtp server are already specified in the server.
yes I tried the $subject = "$env:ComputerName : $env:UserName : System Summary" variable and the result is same.
yes I have tried the - encoding option and it gives an error
Send-MailMessage : Cannot bind parameter 'Encoding'. Cannot convert the "utf8" value of type "Syste
m.String" to type "System.Text.Encoding".
At D:\PowerShell\MyScripts\SystemInfo\SysInfo-V6-test[notfinal].ps1:151 char:84
+ send-MailMessage -SmtpServer $smtp -To $to -From $from -Subject $subject -Encoding <<<< utf8 -B
ody $body -Attachments "$filepath\$name.html" -BodyAsHtml -Priority High
+ CategoryInfo : InvalidArgument: (:) [Send-MailMessage], ParameterBindingException
+ FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Microsoft.PowerShell.Commands.SendMai
lMessage
Any clue?
You could write a custom function to send using .net instead of using the Send-MailMessage cmdlet. It's a lot clunkier, but gets round the problem.
Something like this:
Function SendEmail ($emailFrom, $emailTo, $subject, $body, $attachment) {
# Create from/to addresses
$from = New-Object System.Net.Mail.MailAddress $emailFrom
$to = New-Object System.Net.Mail.MailAddress $emailTo
# Create Message
$message = new-object System.Net.Mail.MailMessage $from, $to
$message.Subject = $subject
$message.Body = $body
$attachment = new-object System.Net.Mail.Attachment($attachment)
$message.Attachments.Add($attachment)
# Set SMTP Server and create SMTP Client
$server = <your server>
$client = new-object system.net.mail.smtpclient $server
# Send the message
"Sending an e-mail message to {0} by using SMTP host {1} port {2}." -f $to.ToString(), $client.Host, $client.Port
try {
$client.Send($message)
"Message to: {1}, from: {0} has beens successfully sent" -f $from, $to
}
catch {
"Exception caught in CreateTestMessage: {0}" -f $Error.ToString()
}
}
(Thanks to Thomas Lee (tfl#psp.co.uk) - I tweaked this from his code at http://powershell.com/cs/media/p/357.aspx)
The Send-MailMessage cmdlet doesn't have any output after you send emails, I wonder where the output comes from? Can you include the command you use and the output?
As to your subject line, you can reduce it to one line only:
$subject = "$env:ComputerName : $env:UserName : System Summary"
The Send-MailMessage has an Encoding parameter, have you tried it?
This happened to me when I used Send-MailMessage with the default encoding (ASCII) when there were spaces in the subject.
First, to answer the question about the Encoding parameter: You are trying to pass it as a string (ie "-Encoding ASCII"), when you should be using this type of syntax instead: "-Encoding ([System.Text.Encoding]::ASCII)".
This "encoding in the subject" issue happened to me, and I narrowed it down to spaces in the subject. To demonstrate:
This will not contain encoding in the subject:
Send-MailMessage -To "alice#example.com" -From "bob#example.com" -Smtp "localhost" -Subject "one" -BodyAsHtml "body1" -Encoding ([System.Text.Encoding]::ASCII)
But this will:
Send-MailMessage -To "alice#example.com" -From "bob#example.com" -Smtp "localhost" -Subject "one two" -BodyAsHtml "body1" -Encoding ([System.Text.Encoding]::ASCII)
Note that the only material difference is the space in the subject.
If I specify UTF8 as the encoding, there is no encoding in the subject:
Send-MailMessage -To "alice#example.com" -From "bob#example.com" -Smtp "localhost" -Subject "one" -BodyAsHtml "body1" -Encoding ([System.Text.Encoding]::UTF8)
But as you say, it looks fine in Outlook, so I presume that the subject is correct. I'm not an expert on email formats or text-encoding, so I won't speculate as to why.