Table of Contents
In some cases, we need to email to numerous people from person to person. PowerShell script can be an easier solution for you.
Send Emails in Bulk using PowerShell
Below is the sample PowerShell Script to send bulk emails. It is fetching data from CSV file (represented in below screenshot). This script will send individual email to every single person listed in CSV.
You need to create a CSV file featuring the fields as required.
$Cred = (Get-Credential)
Import-Csv -Path "C:\Contacts.csv" |
ForEach-Object {
$Name = $_.Name
$Att = $_.Path
Send-MailMessage `
-To $_.Email `
-From "[email protected]" `
-Subject "This is a message from PowerShell" `
-Body "Hello $Name!" `
-Attachments $Att `
-Credential $Cred `
-SmtpServer "smtp.office365.com" `
-Port 587 `
-UseSsl
Write-Host "Email sent to" $_.Email
}
The output:
PS C:\Windows\system32> Import-Csv -Path "C:\Contacts.csv" |
>> ForEach-Object {
>> $Name = $_.Name
>> $Att = $_.Path
>> Send-MailMessage `
>> -To $_.Email `
>> -From "[email protected]" `
>> -Subject "This is a message from PowerShell" `
>> -Body "Hello $Name!" `
>> -Attachments $Att `
>> -Credential $Cred `
>> -SmtpServer "smtp.office365.com" `
>> -Port 587 `
>> -UseSsl
>> Write-Host "Email sent to" $_.Email
>> }
Email sent to [email protected]
Email sent to [email protected]
Email sent to [email protected]
Email sent to [email protected]
Email sent to [email protected]
As you can see, emails are delivered automatically.
Another script to sending emails in bulk using System.Net.Mail API.
<#Script for bulk emailing by getting data from CSV#>
$MailingList = Import-Csv E:\MailingList.csv
#SMTP Server and port may differ for different email service provider
$SMTPServer = "smtp.gmail.com"
$SMTPPort = "587"
#Your email id and password
$Username = "[email protected]"
$Password = "Password"
#Iterating data from CSV mailing list and sending email to each person
foreach ( $person in $MailingList)
{
$iName = $person.Name
$iEmail = $person.Email
$iPassword = $person.Password
$to = $person.Email
$cc = "[email protected]"
$subject = "Email Subject"
$body = @"
Hi $iName,
Your password is : $iPassword
Regards,
Your Name
"@
$attachment = "C:\test.txt"
$message = New-Object System.Net.Mail.MailMessage
$message.subject = $subject
$message.body = $body
$message.to.add($to)
$message.cc.add($cc)
$message.from = $username
$message.attachments.add($attachment)
$smtp = New-Object System.Net.Mail.SmtpClient($SMTPServer, $SMTPPort);
$smtp.EnableSSL = $true
$smtp.Credentials = New-Object System.Net.NetworkCredential($Username, $Password);
$smtp.send($message)
Write-Host Mail Sent to $iName
}
ADVERTISEMENT
5/5 - (2 votes)
How to add the HTML for Email Body