I need to send one unique email to different email addresses exporting
them from a .csv file. I have a code but it just sends the message to all
of the emails in one email.
#Import the file that store username and emails
$data = import-csv "C:.csv"
#Declare email content
$email = $data.Email | select -unique
ForEach ($email in $data)
{
$From = "***#gmail.com"
$To = $data.Email
$Subject = "Test"
$Body = "Test"
$SMTPServer = "smtp.gmail.com"
$SMTPPort = "587"
}
#Sending email
Send-MailMessage -From $From -to $To -Subject $Subject `
-Body $Body -SmtpServer $SMTPServer -port $SMTPPort -UseSsl `
-Credential (Get-Credential -Message "Please input valid credentials")
The code above works but as mentioned it sends just one email to all the email addresses in the file. I need it to send one for each email.
The main problem I see in your code is that you first create an array of unique email addresses from the csv file in a variable $email, but later on you overwrite that same value by using it in the foreach loop.
There, in every iteration, the $email variable will become a complete row from the CSV file which is obviously not what you expect it to be.
Below a slightly adjusted version of your code. Note that I also used Splatting to create a hashtable with all properties for the Send-MailMessage cmdlet, to avoid having to use the easy to overlook backtick.
#Import the file that store username and emails
$data = import-csv "D:\mail.csv"
# Get a unique array of email addresses
$addresses = $data.Email | Select-Object -Unique
# Declare Credentials
$creds = (Get-Credential -Message "Please input valid credentials")
# loop through the email addresses array and send a mail to each of them
foreach ($email in $addresses) {
$splat = #{
From = "***#gmail.com"
To = $email
Subject = "Test"
Body = "Test"
SmtpServer = "smtp.gmail.com"
Port = 587
Credential = $creds
UseSsl = $true
}
#Sending email
Send-MailMessage #splat
}
Note that the -Port parameter is of type Int32, so you should not quote that
Update
As requested in your comment, if you want to use more fields from the CSV file, then the code would change.
Let's assume your CSV looks anything like:
"User","Email","ManagerEmail"
"Tom","t.somebody#yourcompany.com","el.jeffe#yourcompany.com"
"Dick","d.somebody#yourcompany.com","el.jeffe#yourcompany.com"
"Harry","h.somebody#yourcompany.com","di.rector#yourcompany.com"
"Dick","d.somebody#yourcompany.com","el.jeffe#yourcompany.com"
(note, user Dick is duplicated)
Then the following will read the csv, deduplicate it on the Email property and send emails to each user:
# Import the file that store username and emails
# and uniquify the objectson property Email
$data = Import-Csv "D:\mail.csv" | Sort-Object -Property Email -Unique
# Declare Credentials
$creds = (Get-Credential -Message "Please input valid credentials")
# loop through the csv objects array and send a mail to each of them
foreach ($item in $data) {
# every item is an object with properties .User, .Email and .ManagerEmail
$splat = #{
From = "***#gmail.com"
To = $item.Email
Cc = $item.ManagerEmail
Subject = "Hi there {0}" -f $item.User
Body = "Test"
SmtpServer = "smtp.gmail.com"
Port = 587
Credential = $creds
UseSsl = $true
}
#Sending email
Send-MailMessage #splat
}
Hope that helps
As per comments, please find the adjusted script and reasoning.
You were looping through the CSV but only sending the email once. It looks like it would have originally sent the email to ONE person, that being the last in your CSV.
This version will loop through and send an email for each line in the CSV.
#Import the file that store username and emails
$data = import-csv "C:.csv"
#Declare email content
$email = $data.Email | select -unique
# Declare Credentials
$creds = (Get-Credential -Message "Please input valid credentials")
ForEach ($email in $data) {
$From = "***#gmail.com"
$To = $email.Email
$Subject = "Test"
$Body = "Test"
$SMTPServer = "smtp.gmail.com"
$SMTPPort = "587"
#Sending email
Send-MailMessage -From $From -to $To -Subject $Subject `
-Body $Body -SmtpServer $SMTPServer -port $SMTPPort -UseSsl `
-Credential $creds
}
Most important error you made is
$To = $data.Email
where you add all the emails to To: field. Drew's suggestion is almost what you want to follow but with one remark. Your $To= assignment should use $email which represents single object from array, instead of the whole array (which is $data).
$To = $email.Email
Edit: As #Theo suggested in the comments, it's worth mentioning that the line
$email = $data.Email | select -unique
won't work as you use the same variable name later in foreach loop. What I'd suggest is to save unique email addresses to other variable
$uniqueEmails = $data.Email | select -unique
then iterate that one
# Change this
ForEach ($email in $data) {
# To this
ForEach ($email in $uniqueEmails ) {
And of course as you already saved Email propert to $uniqueEmails:
# This line
$To = $email.Email
# Should be changed to
$To = $email
Related
I have a csv file with emp_first_name,Emp_Last_Name, employee#, upn, ManagerEmail.
Column examples "jon,doe,99,jd#fake.ca,FinManager#fake.ca"
i would like to send an email to the email addresses in the managermail column saying new employee's accounts are ready.
I want to inject the variables in the $emp_first_name the body of the email. I have it working without the variables.
Thank to anyone who can help.
$infile = "c:\sdk\import.csv"
$userlist = import-csv $infile
$subject= "New Employee Account"
$username = "crtusr#fake.ca"
$password = "$%t67Bgt##23$%t67Bgt##23hhgfhfghfghgfhgffgfgdhfghfggffgdgfdhgfhfgffsd"
$sstr = ConvertTo-SecureString -string $password -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential -argumentlist $username,
$sstr
$Emp_First_Name = $user.emp_first_name
$Emp_Last_Name = $user.Emp_Last_Name
$employee = $user.employee
$upn = $user.upn
$ManagerEmail = $user.ManagerEmail
$Body="
Hello
The account for $Emp_First_Name $Emp_Last_Name employee number $employee is ready. Her
user email and username is $upn.
"
foreach ($user IN $userList) {
Send-MailMessage –From crtusr#fake.ca –To $ManagerEmail –Subject $subject –Body $body -
SmtpServer smtp.office365.com -Credential $cred -UseSsl -Port 587
}
If string interpolation doesn't happen automatically, you can force it using the ExpandString method:
For example you might do something like this:
$employee = 12345
$Emp_First_Name = 'Jane'
$Emp_Last_Name = 'Doe'
$upn = 'jane.doe#example.com'
$bodyTemplate =
"Hello
The account for $Emp_First_Name $Emp_Last_Name employee number $employee is ready.
Her user email and username is $upn."
$body = $ExecutionContext.InvokeCommand.ExpandString($bodyTemplate)
Send-MailMessage -Body $body -From ....
In this case the contents of $body would be:
Hello
The account for Jane Doe employee number 12345 is ready.
Her user email and username is jane.doe#example.com.
Note that unless you are only dealing with women, you might want to use a more gender-neutral pronoun in your template :-)
Note: This likely won't work for more complex situations, but is fine for simple text replacement like this.
You can do string interpolation with the format operator -f, also your code would benefit greatly using splatting.
# $subject and $cred should be defined here as you already have them
$template = #'
Hello
The account for {0} {1} employee number {2} is ready.
Her user email and username is {3}.
'#
$mailParams = #{
From = 'crtusr#fake.ca'
Subject = $subject
SmtpServer = 'smtp.office365.com'
Credential = $cred
UseSsl = $true
Port = 587
}
foreach ($user in Import-csv "c:\sdk\import.csv") {
$body = $template -f #(
$user.emp_first_name
$user.Emp_Last_Name
$user.employee
$user.upn
)
$mailParams['To'] = $user.ManagerEmail
$mailParams['Body'] = $body
Send-MailMessage #mailParams
}
I'm creating a PS script to automate email blast to 17k users. Our exchange security baseline is set to only accept 60 requests per minute. Because I'm looping through the email list (CSV) line by line (sleep 1 sec), it took hours for my script to complete. What I'm trying to achieve now is to send the email to 100 users per request. I'm figuring out how to store the emails in an array of 100 & send the mail before going for the next 100. Any suggestion?
$recipients = Get-Content "mailinglist.csv"
foreach($rcpt in $recipients)
{
Write-Host "Attempt sending email to $rcpt ..."
Send-MailMessage -ErrorAction SilentlyContinue -ErrorVariable SendError -From $From -to $rcpt -Subject $Subject -SmtpServer $SMTPServer -port $SMTPPort -UseSsl -Credential $Cred -BodyAsHtml ($Body -f $Subject, $Date, $Venue, $Description, $Image)
$ErrorMessage = $SendError.exception.message
If($ErrorMessage)
{
Write-Host "Failure - $ErrorMessage" -ForegroundColor Red
Start-Sleep -Seconds 60
Send-MailMessage -ErrorAction SilentlyContinue -ErrorVariable SendError -From $From -to $rcpt -Subject $Subject -SmtpServer $SMTPServer -port $SMTPPort -UseSsl -Credential $Cred -BodyAsHtml ($Body -f $Subject, $Date, $Venue, $Description, $Image)
}
ElseIf($SendError.exception.message -eq $null)
{
Write-Host "Email has been sent to $rcpt" -ForegroundColor Green
Start-Sleep -Seconds 1
$n++
}
}
Write-Host "Total sent = $n"
You could use a traditional for loop and access your array elements by index.
$recipients = Get-Content "mailinglist.csv"
$To = <SomeValidEmailAddress>
$LastIndex = $recipients.GetUpperBound(0)
for ($i = 0; $i -le $LastIndex; $i+=100) {
$upperRange = [Math]::Min(($i+99),$LastIndex)
$Params = #{
ErrorAction = 'SilentlyContinue'
ErrorVariable = 'SendError'
Bcc = $recipients[$i..$upperRange]
To = $To
From = $From
Subject = $Subject
SmtpServer = $SMTPServer
Port = $SMTPPort
Credential $Cred
Body = $Body -f $Subject, $Date, $Venue, $Description, $Image
BodyAsHTML = $true
UseSsl = $true
}
"Attempt sending email to $($recipients[$i..$upperRange]) ..." # You may want to alter this to be more readable
Send-MailMessage #Params
# Other code
}
Explanation:
I've opted to use Splatting here for readability and manageability with the $Params hash table. It is entirely optional.
The -bcc parameter of Send-MailMessage supports a string array (string[]). Using this over the -To parameter will preserve privacy of the recipients. You can then easily send an email to multiple recipients provided you pass it an array. However, -To is required for Send-Mailmessage to work. It is recommended to make the email address passed into -To something that can be spammed or has a way of handling these types of emails. I have set up the $To variable for you to provide that email address. If privacy is of no concern whatsoever, -Bcc can just be replaced with -To.
Since $recipients is an array, you can access its elements by index, which supports the range operator ... $recipients[0..99] would be the first 100 items in the list.
$LastIndex stores the last index of the list, which is the value returned by the Array.GetUpperBound(Int32) method with dimension 0. Since the array is one-dimensional, 0 is the only dimension.
$upperRange is the beginning index ($i) plus 99. Should $upperRange ever be larger than $LastIndex, it will be set to $LastIndex. Depending on your PowerShell version, the $i+99 and $LastIndex comparison may not be necessary. Accessing an upperbound range beyond the size of the array, will just return all of the remaining elements of the array without throwing an error. This is likely just for completeness.
What I am hoping to do is once a new email hits a folder containing a specific subject. That email is then forwarded to another inbox and a specific file is automatically attached. The code I have been able to cobble together so far is this. Is a .Net method the appropriate method to achieve my goal or would using Send-MailMessge to a hastable be better method? I am new to PowerShell code I am able to get both methods to work. But was wondering A. which method is preferred. B. is there a better/more efficient way?
#####Define Variables########
$fromaddress = "donotreply#fromemail.com"
$toaddress = "blah#toemail.com"
$bccaddress = "blah#bcc.com"
$CCaddress = "blah#cc.com"
$Subject = "ACtion Required"
$body = get-content .\content.htm
$attachment = "C:\sendemail\test.txt"
$smtpserver = "smtp.labtest.com"
##############################
$message = new-object System.Net.Mail.MailMessage
$message.From = $fromaddress
$message.To.Add($toaddress)
$message.CC.Add($CCaddress)
$message.Bcc.Add($bccaddress)
$message.IsBodyHtml = $True
$message.Subject = $Subject
$attach = new-object Net.Mail.Attachment($attachment)
$message.Attachments.Add($attach)
$message.body = $body
$smtp = new-object Net.Mail.SmtpClient($smtpserver)
$smtp.Send($message)
(Example of the hashtable method
$emailHashSplat = #{ To = $toAddress
From = $fromAddress
Subject = $emailSubject
Body = $emailBody SMTPServer = $smtpServer BodyAsHtml =
$true Attachments = "C:\sendemail\test.txt" # Attachments =)
Stick with Powershell commands whenever possible, .NET might be faster in some cases but it is a best practice to use only Powershell commands when possible.
Also make sure your code is easy to read and understand by others, using hastables with splatting wil help with this, see the following example: Github Gist Link (Click Me!)
Copy of the code, in case of link failure.
### Script Global Settings
#Declare SMTP Connection Settings
$SMTPConnection = #{
#Use Office365, Gmail, Other or OnPremise SMTP Relay FQDN
SmtpServer = 'outlook.office365.com'
#OnPrem SMTP Relay usually uses port 25 without SSL
#Other Public SMTP Relays usually use SSL with a specific port such as 587 or 443
Port = 587
UseSsl = $true
#Option A: Query for Credential at run time.
Credential = Get-Credential -Message 'Enter SMTP Login' -UserName "emailaddress#domain.tld"
<#
#Option B: Hardcoded Credential based on a SecureString
Credential = New-Object -TypeName "System.Management.Automation.PSCredential" -ArgumentList #(
#The SMTP User Emailaddress
"emailaddress#domain.tld"
#The Password as SecureString encoded by the user that wil run this script!
#To create a SecureString Use the folowing Command: Read-Host "Enter Password" -AsSecureString | ConvertFrom-SecureString
"Enter the SecureString here as a single line" | ConvertTo-SecureString
)
#>
}
### Script Variables
#Declare Mailmessages.
$MailMessageA = #{
From = "emailaddress#domain.tld"
To = #(
"emailaddress#domain.tld"
)
#Cc = #(
# "emailaddress#domain.tld"
#)
#Bcc = #(
# "emailaddress#domain.tld"
#)
Subject = 'Mailmessage from script'
#Priority = 'Normal' #Normal by default, options: High, Low, Normal
#Attachments = #(
#'FilePath'
#)
#InlineAttachments = #{
#'CIDA'='FilePath'
#} #For more information about inline attachments in mailmessages see: https://gallery.technet.microsoft.com/scriptcenter/Send-MailMessage-3a920a6d
BodyAsHtml = $true
Body = "Something Unexpected Occured as no Content has been Provided for this Mail Message!" #Default Message
}
### Script Start
#Retrieve Powershell Version Information and store it as HTML with Special CSS Class
$PSVersionTable_HTLM = ($PSVersionTable.Values | ConvertTo-Html -Fragment) -replace '<table>', '<table class="table">'
#Retrieve CSS Stylesheet
$CSS = Invoke-WebRequest "https://raw.githubusercontent.com/advancedrei/BootstrapForEmail/master/Stylesheet/bootstrap-email.min.css" | Select-Object -ExpandProperty Content
#Build HTML Mail Message and Apply it to the MailMessage HashTable
$MailMessageA.Body = ConvertTo-Html -Title $MailMessageA.Subject -Head "<style>$($CSS)</style>" -Body "
<p>
Hello World,
</p>
<p>
If your recieved this message then this script works.</br>
</br>
<div class='alert alert-info' role='alert'>
Powershell version
</div>
$($PSVersionTable_HTLM)
</P>
" | Out-String
#Send MailMessage
#This example uses the HashTable's with a technique called Splatting to match/bind the Key's in the HashTable with the Parameters of the command.
#Use the # Symbol instead of $ to invoke Splatting, Splatting improves readability and allows for better management and reuse of variables
Send-MailMessage #SMTPConnection #MailMessageA
My powershell script currently handles sending an email from the command line to a list of users. I would like to add an attachment to the email and also a list of Cc so all emails don't come through the "To" email parameter. Here is my current function.
function SendEmail
{
$smtpServer = "smtp.server"
$smtpFrom = "PROD <email#gmail.com>"
$smtpTo = "me#gmail.com"
$messageSubject = "Weekly List "+$day
$messagebody = "Hi User, Please find attached document. Thank you."
$smtp = New-Object Net.Mail.SmtpClient($smtpServer)
$smtp.Send($smtpFrom,$smtpTo,$messageSubject,$messagebody)
}
My attempt was to add a variable called $attachment = "\PathtoFile"
and add $attachment into the Send function, but that didn't work...
Use Send-MailMessage with the Attachments and Cc parameter:
Send-MailMessage -Attachments "C:\path\to\attachment.ext" -Cc "myboss#gmail.com"
You can also specify an encoding (you mentioned special characters):
Send-MailMessage -Encoding UTF8
In general, I would recommend splatting the parameters, so it ends up looking like this:
$MyAttachments = ".\a\relative\path.ext","C:\another\file.ext"
$MailParams = #{
SmtpServer = "smtp.server"
From = "PROD <email#gmail.com>"
To = "me#gmail.com"
Subject = "Weekly List "+$day
Body = "Hi User, Please find attached document. Thank you."
Attachments = $MyAttachments
Encoding = [System.Text.Encoding]::UTF8
}
Send-MailMessage #MailParams
Here is my code that checks when users passwords will expire and emails them if it will expire in less than 14 days. Since the link in the body of the email has spaces in it, the link does not encompass the whole file name.
#Add the Quest PowerShell snapin
Add-PsSnapIn Quest.ActiveRoles.ADManagement -ErrorAction SilentlyContinue
#Clear the placeholder log file
Clear-Content O:\logs\network\passwordchangeemails.txt
#Set Email Variables
$today = Get-Date
$logdate = Get-Date -format yyyyMMdd
$emailFrom = "my.name#mycompany.com"
$body = "Good Morning, `n`n"
$body += "As a courtesy reminder, your Company password will be expiring soon. `n`n"
$body += "If you allow your password to expire, you will be unable to access our network, mail or QAD until you recieve assistance from the Helpdesk. `n`n"
**$body += "To avoid this, please change your network password as soon as possible. (Remote users, please follow the password change procedure for remote users. Click Here -> " + "\\mydfsshare.net\share\helpdesk\guides\Passwords - Change procedure for remote users.pdf ) `n`n"**
$body += "Feel free to contact the Help Desk by phone at 555-555-5555 or by email at Helpdesk#mycompany.com `n"
$body += "Thanks!"
#Get Active Directory Information
Get-QADUser -SizeLimit 0 | Select-Object samAccountName,mail,PasswordStatus |
Where-Object {$_.PasswordStatus -ne "Password never expires" -and $_.PasswordStatus -ne "Expired" -and $_.PasswordStatus -ne "User must change password at next logon." -and $_.mail -ne $null} |
#For each user, get variables
ForEach-Object {
$samaccountname = $_.samAccountName
$mail = $_.mail
$passwordstatus = $_.PasswordStatus
$passwordexpiry = $passwordstatus.Replace("Expires at: ","")
$passwordexpirydate = Get-Date $passwordexpiry
$daystoexpiry = ($passwordexpirydate - $today).Days
#If days to expire is lessthan 14 days, send email to user
if ($daystoexpiry -lt 14) {
$emailTo = "$mail"
$subject = "Company IT Notification: Your Network password will expire in $daystoexpiry day(s). "
Send-MailMessage -To $emailTo -From $emailFrom -Subject $subject -Body $body -SmtpServer 192.168.1.191
Write-Host "Email was sent to $mail on $today"
Add-Content O:\logs\network\passwordchangeemails.txt "Email was sent to $mail on $today"
}
}
$recipients = "my.name#mycompany.com"
#Copy contents of log file to email and send to IT Department
$content = [IO.File]::ReadAllText("O:\logs\network\passwordchangeemails.txt")
Send-MailMessage -To $recipients -From "my.name#mycompany.com" -Subject "Password change log for $today" -Body "This is the log from $today, $content" -SmtpServer 111.111.111.111
Sorry I can't test this right now but if HTML is OK to use, try wrapping the link as follows...
"Text you want the users to see goes here<br>`n
Then set -BodyAsHtml on Send-Mailmessage:
Send-MailMessage -To $emailTo -From $emailFrom -Subject $subject -Body $body -SmtpServer 192.168.1.191 -BodyAsHtml