Mass mailing from PowerShell using EASendMail Service Queue
EASendMail SMTP component is useful for sending mass emails. For this, you donât have to code multiple threadings. All you need is EASendMail Service that can send messages with multiple threadings automatically in background queue. Take a look at the following script for mass mailing of a message with an HTML template:
[reflection.assembly]::LoadFile("C:\Program Files (x86)\EASendMail\Lib\net20\EASendMail.dll")
#change the path to the EASendMail.dll file if you have another build of run-time assembly for .NET Framework, .NET Core, or .NET Compact Framework
function SendMailToQueue($sender, $name, $address, $subject, $body, $htmlFormat) {
$mail = New-Object EASendMail.SmtpMail("TryIt")
$mail.From.Address = $sender
$recipient = New-Object EASendMail.MailAddress($name, $address)
$mail.To.Add($recipient) > $null
$mail.Subject = $subject
if($htmlFormat) {
$mail.HtmlBody = $body
}
else {
$mail.TextBody = $body
}
$server = New-Object EASendMail.SmtpServer("smtp.mailtrap.io")
$server.User = "*********"
$server.Password = "*********"
$server.Port = 587
$server.ConnectType = [EASendMail.SmtpConnectType]::ConnectTryTLS
# specify your settings of the SMTP server, username, password, port, and connection type
$smtp = New-Object EASendMail.SmtpClient
$smtp.SendMailToQueue($server, $mail)
}
function OpenConnection () {
$connectionString = "Server=localhost\AdminSystem;Database=test;Integrated security=SSPI;MultipleActiveResultSets=True;"
Write-Host(("Connecting database {0} ..." -f $connectionString))
$sqlConnection = New-Object System.Data.SqlClient.SqlConnection
$sqlConnection.ConnectionString = $connectionString
# You can change the connection string to yours by specifying user and password: $connectionString = "Server=localhost\AdminSystem;Database=dbname;User Id=user;Password=yourpassword;MultipleActiveResultSets=True;"
$sqlConnection.Open()
Write-Host 'Connected'
return $sqlConnection
}
function BuildHtmlBody ($sqlConnection) {
Write-Host "Building HTML body based on database ..."
$sqlQuery = "SELECT ID, Name, Email, Age, Department FROM users"
$sqlCommand = New-Object System.Data.SqlClient.SqlCommand($sqlQuery, $sqlConnection);
$reader = $sqlCommand.ExecuteReader()
$html = "<!DOCTYPE html><html><body>"
$html += "<div style=""font-family:'Segoe UI', Calibri, Arial, Helvetica; font-size: 14px; max-width: 768px;"">"
$html += "Dear {name}, <br /><br />This is a congrats email on Samhain. <br />"
$html += "Here is full data in table:<br /><br />"
$html +="<table style='border-spacing: 0px; border-style: solid; border-color: #ccc; border-width: 0 0 1px 1px;'>"
while ($reader.Read()) {
$name = $reader.GetString(1)
$address = $reader.GetString(2)
$age = $reader.GetInt32(3)
$department = $reader.GetString(4)
$html += "<tr>"
$html += "<td style='padding: 10px; border-style: solid; border-color: #ccc; border-width: 1px 1px 0 0;'>{0}</td>" -f $name
$html += "<td style='padding: 10px; border-style: solid; border-color: #ccc; border-width: 1px 1px 0 0;'>{0}</td>" -f $address
$html += "</tr>"
}
$reader.Close > $null
$reader.Dispose > $null
$sqlCommand.Close > $null
$sqlCommand.Dispose > $null
return $html
}
function SendMailFromDBToQueue () {
$sender = "mother-of-dragons@houseoftargaryen.net"
$subject = "Happy Samhain"
$sqlConnection = OpenConnection
$bodyTemplate = BuildHtmlBody($sqlConnection)
$sqlQuery = "SELECT ID, Name, Email, Age, Department FROM users"
$sqlCommand = New-Object System.Data.SqlClient.SqlCommand($sqlQuery, $sqlConnection);
$reader = $sqlCommand.ExecuteReader()
while ($reader.Read()) {
$name = $reader.GetString(1).Trim()
$address = $reader.GetString(2).Trim()
$body = $bodyTemplate.Replace("{name}", $name)
Write-Host(("Start to send email to {0} ..." -f $address))
SendMailToQueue $sender $name $address $subject $body "html"
Write-Host(("Email to {0} has been submitted to easendmail service!" -f $address))
}
$reader.Close > $null
$reader.Dispose > $null
$sqlCommand.Close > $null
$sqlCommand.Dispose > $null
$sqlConnection.Close > $null
$sqlConnection.Dispose > $null
}
catch [System.Exception] {
"Failed to send email: {0}" -f $_.Exception.Message
}
}
SendMailFromDBToQueue
Send emails from PowerShell using System.Net.Mail API
Send-MailMessage cmdlet is the most common option for sending emails from PowerShell. But this was not always the case. It became available starting from PowerShell 3.0 and was based on System.Net.Mail API. It is a namespace that contains classes to send electronic messages to the SMTP server. The delivery is carried out using the SmtpClient.Send
or .Send
method. Letâs take a look at the following example:
$EmailFrom = âmother-of-dragons@houseoftargaryen.netâ
$EmailTo = âjon-snow@winterfell.comâ
$Subject = âHappy Samhainâ
$Body = âJonny, congrats on Samhain!â
$SMTPServer = âsmtp.mailtrap.ioâ
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 587)
$SMTPClient.EnableSsl = $true
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential("<username>", "<password>");
$SMTPClient.Send($EmailFrom, $EmailTo, $Subject, $Body)
Check out Mailtrapâs Demo inbox and voila â itâs in. Alternatively, you can use the .Send
method and modified syntax like this one:
$smtpFrom = âmother-of-dragons@houseoftargaryen.netâ
$smtpTo = âjon-snow@winterfell.comâ
$messageSubject = âHappy Samhainâ
$messageBody = âJonny, congrats on Samhain!â
$smtpServer = âsmtp.mailtrap.ioâ
$smtp = New-Object Net.Mail.SmtpClient($SmtpServer, 587)
$smtp.EnableSsl = $true
$smtp.Credentials = New-Object System.Net.NetworkCredential("94b784b5970edf", "01a5d515011f6e");
$smtp.Send($smtpFrom , $smtpTo, $messageSubject, $messageBody)
Learn how exactly Mailtrap can help you streamline email testing processes from our case study with The Software House.
To wrap up
The System.Net.Mail namespace is also used to create and send messages in ASP.NET C# that weâve also blogged about. And thatâs it for today. We hope that this blog post broadened your skills in using PowerShell. Follow our blog and discover useful expertise for your projects.