Powershell Automated Email - powershell

new to the forum, so apologises if this in the wrong area.
I am looking to create a powershell script which emails a list (.txt) file consisting of 200 emails, the text file will be updated aswell with new email addresses. The email body which will be send is a standard (generic) email, nothing specific to each email address.
Is this possible?
This is the script I have so far, but its not sending the email..
$emails = #()
ForEach ($recipient in Get-Content "\\FILE Location")
{
$emails += "$recipient"
}
$to = "TO EMAIL"
$smtp = "SMTP Server"
$from = "FROM EMAIL"
$subject = "Subject"
$body = "EMAIL BODY"
send-MailMessage -SmtpServer $smtp -To $to -Bcc $emails -From $from -Subject $subject -Body $body -BodyAsHtml -Priority high
Thanks in advance
Matt.

In these situations it may be best to create the objects yourself. I would set it up like so:
$smtpServer = "SMTP Server"
$smtp = new-object Net.Mail.SmtpClient($smtpServer)
$smtpCredentialsUsername = "blah#blah.com"
$smtpCredentialsPassword = ConvertTo-SecureString -String $smtpPwd -AsPlainText -Force
$Credentials = New-Object –TypeName System.Management.Automation.PSCredential –ArgumentList
$smtpCredentialsUsername, $smtpCredentialsPassword
$smtp.Credentials = $Credentials
$msg = new-object Net.Mail.MailMessage
$msg.Body = $body
$msg.Subject = $subject
$msg.From = $from
$msg.To.ADD($to)
$msg.IsBodyHtml = $true
ForEach ($recipient in Get-Content "\\FILE Location")
{
$msg.Bcc.ADD($recipient)
}
$smtp.Send($msg)
$msg.Dispose();

Related

Powershell to send mail

Error
New-Object : Cannot find an overload for "PSCredential" and the
argument count: "2". At D:\Scripts\gsend.ps1:12 char:15
Code
#Create Password File (Only need once)
#$Credential = Get-Credential
#$Credential.Password | ConvertFrom-SecureString | Set-Content "D:\scripts\gsendcred.txt"
#Send Email
$EncryptedCredential = "D:\scripts\gsendcred.txt"
$EmailUsername = "me#gmail.com"
$EncryptedPW = Get-Content "D:\scripts\gsendcred.txt"
$EncryptedCredential = ConvertTo-SecureString -String $EncryptedCredential -
AsPlainText -Force
$Credential = New-Object Management.Automation.PSCredential ($EmailUsername,
$EncryptedPW)
$EmailFrom = "me#gmail.com"
$EmailTo = "me#gmail.com"
$EmailSubject = "GSEND Test Subject"
$EmailBody = "Test Body"
$SMTPServer = "smtp.gmail.com"
$SMTPPort = 587
$SMTPSsl = $true
I believe your issue is handling credentials. Here is how I handle the smtp credentials:
$smtpPwd = "password"
$smtpCredentialsUsername = "jdonnelly#xxxxx.com"
$smtpCredentialsPassword = ConvertTo-SecureString -String $smtpPwd -AsPlainText -Force
$Credentials = New-Object –TypeName System.Management.Automation.PSCredential
–ArgumentList $smtpCredentialsUsername, $smtpCredentialsPassword
Then:
$smtp.Credentials = $Credentials
Or if you are using Send-MailMessage store your email credentials locally by running this short script by itself beforehand:
Get-Credential | Export-Clixml C:\fso\myemailcreds.xml
It will prompt you to enter your credentials and then store them locally in (in this case) a folder called fso. Then in any Send-MailMessage cmdlet use the locally stored credentials as follows:
Send-MailMessage -To 'Recipient <recipient#yahoo.com>' -from 'John Donnelly <jdonnelly#xxx.com>'
-cc 'whoever <whoever#xxx.com>' -Subject $subject -Body $body
-BodyAsHtml -smtpserver "smtp.office365.com" -usessl
-Credential (Import-Clixml C:\fso\myemailcreds.xml) -Port 587
You Can use below Powershell script for send mail
Send-MailMessage -To "abc#abc.com" -From "def#abc.com" -Cc "gef#abc.com","hij#abc.com" -Subject Test Mail -BodyAsHtml $htmlbody -SmtpServer "mailhost.abc.com"
where $htmlbody is string variable that contain html.

Send SQL Query output to email using PowerShell

I want to send SQL query output to email using PowerShell, how can I do this?
Here is what I have so far:
$query = select name, surname, gender, accountNumber from table1
$Report = Invoke-Sqlcmd -ServerInstance "instance" -Database "db2" -Query $query
$MailUsername = "mail"
$MailPassword = "1234"
$cred = New-Object System.Management.Automation.PSCredential -ArgumentList #($MailUsername,(ConvertTo-SecureString -String $MailPassword -AsPlainText -Force))
Send-MailMessage -To "me#yahoo.com" -From "you#yahoo.com" -SmtpServer mail.net -Credential $cred -Subject "weekly Report:" -Body "$Report"
I want to be able to send the report in form of a table or something that looks nice? How can I do that?
My code above is running into errors, can anyone help me please?
Adding an attachment was all I needed, please see below:
$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)

Sending a email with powershell

I want to send a email with powershell. The script works fine if I type my credential in manualy. But I want to give the credential parameters within the script. My script looks like this:
$From = "test#yahoo.de"
$To = "test2#yahoo.de"
$Cc = "test#yahoo.de"
$Attachment = "C:\Users\test\test\test.ini"
$Subject = "Email Subject"
$Body = "Insert body text here"
$SMTPServer = "smtp.mail.yahoo.com"
$SMTPPort = "587"
Send-MailMessage -From $From -to $To -Cc $Cc -Subject $Subject `
-Body $Body -SmtpServer $SMTPServer -port $SMTPPort -UseSsl `
-Credential (
$MyClearTextUsername=’test#yahoo.de’
$MyClearTextPassword=’test123’
$SecurePassword=Convertto-SecureString –String $MyClearTextPassword –AsPlainText –force
$MyCredentials=New-object System.Management.Automation.PSCredential $MyClearTextPassword,$SecurePassword) -Attachments $Attachment
Here's how you can create a credentials object:
$cred = ([pscredential]::new('test#yahoo.de',(ConvertTo-SecureString -String 'test123' -AsPlainText -Force)))
so in your case use:
Send-MailMessage -From $From -to $To -Cc $Cc -Subject $Subject `
-Body $Body -SmtpServer $SMTPServer -port $SMTPPort -UseSsl `
-Credential $cred -Attachments $Attachment
I see no point in trying to fit that into the Send-MailMessage, just create it before and reference it. easier to read.
If you're using Office365 to send email, you might want to try this:
# Sending an email from PowerShell 5.1 script through outlook.office365.com
#
# 1. Create an encrypted password file
# PS > Read-Host -AsSecureString | ConvertFrom-SecureString | Out-File -FilePath <passwordfile>
# This will prompt you for a password, encrypt and save in <passwordfile>
# 2. Obtain Outlook Office365 SMTP server name.
# Go to your ISP and find the value of the MX record. For example <yourdomain>.mail.protection.outlook.com
# 3. If after running the script you get this error:
# Send-MailMessage : Mailbox unavailable. The server response was: 5.7.606 Access denied, banned sending IP [X.X.X.X].
# You will need to delist your IP by going here: https://sender.office.com/
# Note: Removing you IP from the block list could take up to 30 minutes.
#
$User = "<SMPT loging username>"
$PasswordFile = "<passwordfile>"
$SMTPCredentials=New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $User, (Get-Content $PasswordFile | ConvertTo-SecureString)
$EmailTo = "<to email address>"
$EmailFrom = "<from email address>"
$Subject = "<email subject>"
$Body = "<email body>"
$SMTPServer = "<Outlook STMP Server from MX record>"
Send-MailMessage -From $EmailFrom -To $EmailTo -Subject $Subject -Body $Body -SmtpServer $SMTPServer -Port 25 -Credential $SMTPCredentials -UseSsl

PowerShell Send Email

See this question's first two answers (have tried both, both generate the below error):
Code (changed necessary pieces):
$EmailFrom = "notifications#somedomain.com"
$EmailTo = "me#earth.com"
$Subject = "Notification from XYZ"
$Body = "this is a notification from XYZ Notifications.."
$SMTPServer = "smtp.gmail.com"
$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)
Other way (changed necessary pieces):
$credentials = new-object Management.Automation.PSCredential “mailserver#yourcompany.com”, (“password” | ConvertTo-SecureString -AsPlainText -Force)
Send-MailMessage -From $From -To $To -Body $Body $Body -SmtpServer {$smtpServer URI} -Credential $credentials -Verbose -UseSsl
I'm getting this error:
The SMTP server requires a secure connection or the client was not
authenticated. The server response was: 5.5.1 Authentication Required.
Learn more at
On the first script, the port is explicitly specified, while it's not using PS's built in function (though I haven't had problems with this function in the past).
Thanks!
We send mail with Powershell through Office365. This is what we use (works perfectly). Remember that the user you authenticate with must have "send as"-permissions of the from-address:
$PSEmailServer = "smtp.office365.com"
$credentials = new-object Management.Automation.PSCredential “UserLogonName#domain.com”, (“password” | ConvertTo-SecureString -AsPlainText -Force)
$enc = New-Object System.Text.utf8encoding
$from = "FromAddress"
$to = "ToAddress","ToAdress2"
$body = "Test"
$subject = "Test"
Send-MailMessage -port 587 -From $from -BodyAsHtml -Encoding $enc -To $to -Subject $subject -Body $body -UseSsl -Credential $credentials
Try this function to send an email via Gmail:
Function batchsend-mailmessage ($to, $subject, $body, $attachments)
{
$smtpServer = "smtp.gmail.com"
$smtpServerport = "587"
$emailSmtpUser = "TheBatch#gmail.com"
$emailSmtpPass = "PasswordOfTheBatch"
$emailMessage = New-Object System.Net.Mail.MailMessage
$emailMessage.From = $emailSmtpUser
foreach ($addr in $to)
{
$emailMessage.To.Add($addr)
}
foreach ($attachment in $attachments)
{
$emailMessage.Attachments.Add($attachment)
}
$emailMessage.Subject = $subject
$emailMessage.IsBodyHtml = $true
$emailMessage.Body = $body
$smtpClient = New-Object System.Net.Mail.SmtpClient($smtpServer , $smtpServerport)
$smtpClient.EnableSsl = $true
$smtpClient.Credentials = New-Object System.Net.NetworkCredential($emailSmtpUser , $emailSmtpPass);
$SMTPClient.Send( $emailMessage )
}
Like this :
batchsend-mailmessage -to $DesAdressesDest -subject $Subject -body $body -attachments $xlsFile

Attaching to an email in powershell script

I have the following powershell script:
$csv = Import-Csv -Path D:\temp\Audit.csv | Where-Object {$_.PrivateLabelSeqId -eq "602"} | Measure-Object
$Fun = $csv.Count
$mailBody =
#"
There are <b> $Fun </b> available!
"#
Send-MailMessage -Body $mailBody -BodyAsHtml `
-From "mail#mail.com" -To "mailto#mail.com" `
-Subject "Audit - FUN" -Encoding $([System.Text.Encoding]::UTF8) `
-Attachment "D:\temp\Audit.csv" `
-SmtpServer "192.0.0.20"
Yet I do not get any email sent out. Without the attachment however, it seems to work just fine. Any ideas on how to resolve this?
Thanks
I encountered the same problem once, i solved it by using System.Net.Mail instead.
$filenameAndPath = (Resolve-Path .\$file).ToString()
$from = 'mail#mail.com'
$to = "mailto#mail.com" `
$Subject "Audit - FUN" -Encoding $([System.Text.Encoding]::UTF8)
[void][Reflection.Assembly]::LoadWithPartialName('System.Net') | out-null
$message = New-Object System.Net.Mail.MailMessage($from, $to, $subject, $subject)
$attachment = New-Object System.Net.Mail.Attachment($filenameAndPath, 'text/plain')
$message.Attachments.Add($attachment)
$smtpClient = New-Object System.Net.Mail.SmtpClient
$smtpClient.host = '192.0.0.20'
$smtpClient.Send($message)
To read more about System.Net.Mail.Attachement Class
http://msdn.microsoft.com/en-us/library/system.net.mail.attachment.aspx