I'd like to send email from PowerShell, so I use this command:
$EmailFrom = ""
$EmailTo = ""
$Subject = "today date"
$Body = "TODAY SYSTEM DATE=01/04/2016 SYSTEM TIME=11:32:05.50"
$SMTPServer = "smtp.mail.yahoo.com"
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 587)
$SMTPClient.EnableSsl = $true
$SMTPClient.Credentials = New-Object
System.Net.NetworkCredential("", "password")
$SMTPClient.Send($EmailFrom, $EmailTo, $Subject, $Body)This command didn't work for Yahoo mail or Outlook mail, but works for my Gmail. Is there anything wrong that I have done?
34 Answers
Following code snippet really works for me:
$Username = "MyUserName";
$Password = "MyPassword";
$path = "C:\attachment.txt";
function Send-ToEmail([string]$email, [string]$attachmentpath){ $message = new-object Net.Mail.MailMessage; $message.From = ""; $message.To.Add($email); $message.Subject = "subject text here..."; $message.Body = "body text here..."; $attachment = New-Object Net.Mail.Attachment($attachmentpath); $message.Attachments.Add($attachment); $smtp = new-object Net.Mail.SmtpClient("smtp.gmail.com", "587"); $smtp.EnableSSL = $true; $smtp.Credentials = New-Object System.Net.NetworkCredential($Username, $Password); $smtp.send($message); write-host "Mail Sent" ; $attachment.Dispose(); }
Send-ToEmail -email "" -attachmentpath $path; 5 I use this:
Send-MailMessage -To -from -Subject 'hi' -SmtpServer 10.1.1.1 2 You can simply use the Gmail smtp.
Following is The powershell code to send a gmail message with an Attachment:
$Message = new-object Net.Mail.MailMessage $smtp = new-object Net.Mail.SmtpClient("smtp.gmail.com", 587) $smtp.Credentials = New-Object System.Net.NetworkCredential("", "password"); $smtp.EnableSsl = $true $smtp.Timeout = 400000 $Message.From = "" $Message.To.Add("") $Message.Attachments.Add("C:\foo\attach.txt") $smtp.Send($Message)On the sender Google Account (),
Make sure you have Turned ON Access for less-secure apps option, from google Account Security Dashboard.
Finally, Save this Script As mail.ps1
To invoke the above Script Simple run below on Command Prompt or batch file:
Powershell.exe -executionpolicy remotesigned -File mail.ps1By Default, For sending Large Attachments Timeout is Around 100 seconds or so. In this script, it is increased to Around 5 or 6 minutes
1Sometimes you may need to set the EnableSsl to false (in this case the message will be sent unencrypted over the network)
3