Sometimes we want to blind copy (BCC) a group of users into an email, without specifying the To address. In this blog post we find a solution to send bulk emails with PowerShell using only BCC.
In an earlier post we discussed how to send an email using PowerShell. This approach used the
Send-MailMessage
cmdlet and even ventured into sending an email using Outlook with voting buttons!
The issue with using the
Send-MailMessage
cmdlet is that the To field is mandatory. You cannot just specify the BCC field. And this is problematic when we want to send bulk emails.
The solution is to use the
System.Net.Mail.SmtpClient
.
[System.Net.ServicePointManager]::SecurityProtocol = 'Tls,TLS11,TLS12'
$From = "Alkane User <xxx@alkanesolutions.co.uk>"
$Subject = "Alkane Subject"
$Body = "<html><head></head><body><p>This is a HTML email.</p></body></html>"
$SmtpServer = "mail.alkanesolutions.co.uk"
$SmtpPort = 587
#create a MailMessage object with only Bcc
$MailMessage = New-Object System.Net.Mail.MailMessage
$MailMessage.From = $From
$MailMessage.IsBodyHtml = $true
#Add BCC addresses
$MailMessage.Bcc.Add("example1@wherever.com")
$MailMessage.Bcc.Add("example2@wherever.com")
$MailMessage.Subject = $Subject
$MailMessage.Body = $Body
#create a SmtpClient object
$SmtpClient = New-Object System.Net.Mail.SmtpClient
$SmtpClient.Host = $SmtpServer
$SmtpClient.Port = $SmtpPort
$SmtpClient.EnableSsl = $true
#create credentials to authenticate
$secpasswd = ConvertTo-SecureString "PasswordHere" -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential ("xxx@alkanesolutions.co.uk", $secpasswd)
$SmtpClient.Credentials = $cred
#send the email
$SmtpClient.Send($MailMessage)
#dispose of the MailMessage and SmtpClient objects
$MailMessage.Dispose()
$SmtpClient.Dispose()
The
SMTPClient
class in PowerShell enables us to specify the BCC field without specifying the To field. Similarly to the
Send-MailMessage
cmdlet, we can also use it to send HTML emails, add attachments, specify a port and more.