Passing network credential to System.Net.NetworkCredential - powershell

How to pass the network credentials of machine (domain\machine$) to send the mails.
I have below script but its not accepting domain\Machine$, and its looking for pwd as well. Machine accounts are with network credentials and don't have pwd.
$smtpClient = New-Object System.Net.Mail.SmtpClient
$smtpClient.Host = "smtpx-dc1.msn.com"
$smtpClient.Port = 25029
$smtpClient.UseDefaultCredentials = $false
$smtpClient.Credentials = New-Object System.Net.NetworkCredential("dc\AServer$")
$smtpClient.EnableSsl = $true
$message = New-Object System.Net.Mail.MailMessage
$message.From = "abc#abc.com"
$message.To.Add("abc#abc.com")
$message.Subject = "Test from Aserver"
$message.Body = "Is this working?"
$smtpClient.Send($message)

thank you Maxwellb...
here is how it works
$smtpClient = New-Object System.Net.Mail.SmtpClient
$smtpClient.Host = "smtpx-dc1.msn.com"
$smtpClient.Port = 25029
$smtpClient.UseDefaultCredentials = $true
$smtpClient.EnableSsl = $false
$message = New-Object System.Net.Mail.MailMessage
$message.From = "abc#abc.com"
$message.To.Add("abc#abc.com")
$message.Subject = "Test from Aserver"
$message.Body = "Is this working?"
$smtpClient.Send($message)

Related

Script for sending email doesn't work with Gmail account

here there is a simple script to send an email.
If I run it using Gmail settings (ie smtp.gmail.com on port 465 or 587) the script doesn't work returning the error
Server error response: 5.7.0 Authentication Required
# graphical stuff
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing
Add-Type -AssemblyName PresentationFramework
# import modules
$workdir = Get-Location
Import-Module -Name "$workdir\Modules\Forms.psm1" # module for windows forms
$answ = [System.Windows.MessageBox]::Show("Configure for sending mail alerts?",'ALERTS','YesNo','Info')
if ($answ -eq "Yes") {
# dialog box
$formail = New-Object System.Windows.Forms.Form
$formail.Text = "CONFIG"
$formail.Size = "500,300"
$formail.StartPosition = 'CenterScreen'
$formail.Topmost = $true
$address = New-Object System.Windows.Forms.Label
$address.Location = New-Object System.Drawing.Size(10,20)
$address.Size = New-Object System.Drawing.Size(120,20)
$address.Text = "Mail address:"
$formail.Controls.Add($address)
$addressbox = New-Object System.Windows.Forms.TextBox
$addressbox.Location = New-Object System.Drawing.Point(130,20)
$addressbox.Size = New-Object System.Drawing.Size(300,20)
$formail.Add_Shown({$addressbox.Select()})
$formail.Controls.Add($addressbox)
$passwd = New-Object System.Windows.Forms.Label
$passwd.Location = New-Object System.Drawing.Size(10,50)
$passwd.Size = New-Object System.Drawing.Size(120,20)
$passwd.Text = "Password:"
$formail.Controls.Add($passwd)
$passwdbox = New-Object System.Windows.Forms.MaskedTextBox
$passwdbox.PasswordChar = '*'
$passwdbox.Location = New-Object System.Drawing.Point(130,50)
$passwdbox.Size = New-Object System.Drawing.Size(300,20)
$formail.Add_Shown({$passwdbox.Select()})
$formail.Controls.Add($passwdbox)
$smtp = New-Object System.Windows.Forms.Label
$smtp.Location = New-Object System.Drawing.Size(10,80)
$smtp.Size = New-Object System.Drawing.Size(120,20)
$smtp.Text = "SMTP server:"
$formail.Controls.Add($smtp)
$smtpbox = New-Object System.Windows.Forms.TextBox
$smtpbox.Location = New-Object System.Drawing.Point(130,80)
$smtpbox.Size = New-Object System.Drawing.Size(300,20)
$formail.Add_Shown({$smtpbox.Select()})
$formail.Controls.Add($smtpbox)
$port = New-Object System.Windows.Forms.Label
$port.Location = New-Object System.Drawing.Size(10,110)
$port.Size = New-Object System.Drawing.Size(120,20)
$port.Text = "Port:"
$formail.Controls.Add($port)
$portbox = New-Object System.Windows.Forms.TextBox
$portbox.Location = New-Object System.Drawing.Point(130,110)
$portbox.Size = New-Object System.Drawing.Size(300,20)
$portbox.Text = '587'
$formail.Add_Shown({$portbox.Select()})
$formail.Controls.Add($portbox)
$OKButton = New-Object System.Windows.Forms.Button
$OKButton.Location = "150,160"
$OKButton.Size = '100,30'
$OKButton.Text = "Ok"
$OKButton.DialogResult = [System.Windows.Forms.DialogResult]::OK
$formail.AcceptButton = $OKButton
$formail.Controls.Add($OKButton)
$result = $formail.ShowDialog()
# setting credentials
$usr = $addressbox.Text
$pwd = ConvertTo-SecureString $passwdbox.Text -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential($usr, $pwd)
# define email content
$subject = 'TestMail.ps1'
$body = "Questa mail è stata mandata da uno script PowerShell"
# sending email
$ErrorActionPreference= 'Stop'
Try {
Send-MailMessage -From $addressbox.Text `
-To $addressbox.Text `
-Subject $subject `
-Body $body `
-SmtpServer $smtpbox.Text `
-UseSsl `
-Port $portbox.Text `
-Credential $credential
$ErrorActionPreference= 'Inquire'
}
Catch {
Write-Output "`nError: $($error[0].ToString())"
$answ = [System.Windows.MessageBox]::Show("Sending alert email failed",'WARNING','Ok','Warning')
}
}
In the cmdlet Send-MailMessage I haven't found any parameter to force authentication. How can I effectively send an email?
The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required:
Solutions in order of likely hood to help.
Check if the user has 2fa enabled if so you will need an apps password
Check your Captcha loc
Look into Xoauth2
I solved the issue. As stated here, I have to:
1 - Force the script to use TLS 1.2
2 - Turn off two-factor authentication and allow access to insecure apps
Thank you DaImTo for the inspiration

Powershell RDS CAL email Report

I have a PowerShell command that will get an output of how many CAL's I have installed and how many are used. I would like to instead of write-host, change it to a variable so that I can add it to the body of an email and have it run on a schedule, to email me weekly reports on usage, I would like to have the variable something like $report as shown in the $body of the email, this is what I have so far..
$fileName = (Invoke-WmiMethod Win32_TSLicenseReport -Name GenerateReportEx).FileName
$summaryEntries = (Get-WmiObject Win32_TSLicenseReport|Where-Object FileName -eq $fileName).FetchReportSummaryEntries(0,0).ReportSummaryEntries
$summaryEntries|ForEach {Write-Host $_.ProductVersion $_.TSCALType "Installed:" $_.InstalledLicenses "Issued:" $_.IssuedLicenses}
$EmailTo = "itgroup#contonso.com"
$EmailFrom = "admin#contonso.com"
$user = 'admin#contonso.com'
$password = Unprotect-CmsMessage -Path C:\Scripts\Powershell\EncryptedSecret.txt
$Subject = "Alert: CAL USAGE "
$Body = "Alert; $Report"
$SMTPServer = "smtp#contonso.com"
$SMTPMessage = New-Object System.Net.Mail.MailMessage($EmailFrom,$EmailTo,$Subject,$Body)
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 25)
$SMTPClient.EnableSsl = $false
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential($user, $password)
$SMTPClient.Send($SMTPMessage)
I have used both parts of this script separately, but I would like to join them together, to make more useful. Thanks in advance PowerShell newbie..
Here is the full code that I used to get this to work, simply changing 'Write-Host' to 'Write-Output'
$fileName = (Invoke-WmiMethod Win32_TSLicenseReport -Name GenerateReportEx).FileName
$summaryEntries = (Get-WmiObject Win32_TSLicenseReport|Where-Object FileName -eq $fileName).FetchReportSummaryEntries(0,0).ReportSummaryEntries
$Report = $summaryEntries|ForEach {Write-Output $_.ProductVersion $_.TSCALType "Installed:" $_.InstalledLicenses "Issued:" $_.IssuedLicenses}
$EmailTo = "itgroup#contonso.com"
$EmailFrom = "admin#contonso.com"
$user = 'admin#contonso.com'
$password = Unprotect-CmsMessage -Path C:\Scripts\Powershell\EncryptedSecret.txt
$Subject = "RDS CAL USAGE REPORT"
$Body = "Alert; $Report"
$SMTPServer = "smtp#contonso.com"
$SMTPMessage = New-Object System.Net.Mail.MailMessage($EmailFrom,$EmailTo,$Subject,$Body)
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 25)
$SMTPClient.EnableSsl = $false
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential($user, $password)
$SMTPClient.Send($SMTPMessage)

Powershell email add CC field

I found this code here for sending emails and attachments with Powershell and works great for that but I'm trying to add the email CC to it. I can't figure it out. Please give me a hand if you can. I tried various ways of adding $message.Cc.Add("email_address"); but can't get it working. Thank you.
$Username = "MyUserName";
$Password = "MyPassword";
$path = "C:\attachment.txt";
function Send-ToEmail([string]$email, [string]$attachmentpath){
$message = new-object Net.Mail.MailMessage;
$message.From = "YourName#gmail.com";
$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 "reciever#gmail.com" -attachmentpath $path;
$Username = "MyUserName";
$Password = "MyPassword";
$path = "C:\attachment.txt";
function Send-ToEmail([string]$email, [string]$emailCc, [string]$attachmentpath){
$message = new-object Net.Mail.MailMessage;
$message.From = "YourName#gmail.com";
$message.To.Add($email);
$message.Cc.Add($emailCc);
$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 "reciever#gmail.com" -emailCc "CCreciever#gmail.com" -attachmentpath $path;
It works to me. Please try.
$smtpCred = (Get-Credential)
$ToAddress = 'to#outlook.com'
$CcAddress = 'cc#outlook.com'
$FromAddress = 'from#outlook.com'
$SmtpServer = 'smtp.office365.com'
$SmtpPort = '587'
$mailparam = #{
To = $ToAddress
Cc = $CcAddress
From = $FromAddress
Subject = 'Test Subject'
Body = 'Test Body'
SmtpServer = $SmtpServer
Port = $SmtpPort
Credential = $smtpCred
}
Send-MailMessage #mailparam -UseSsl

How to send email with PowerShell

I'd like to send email from PowerShell,
so I use this command:
$EmailFrom = "customer#yahoo.com"
$EmailTo = "receiver#ymail.com"
$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("customer#yahoo.com", "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?
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 = "YourName#gmail.com";
$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 "reciever#gmail.com" -attachmentpath $path;
I use this:
Send-MailMessage -To hi#abc.com -from hi2#abc.com -Subject 'hi' -SmtpServer 10.1.1.1
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("From#gmail.com", "password");
$smtp.EnableSsl = $true
$smtp.Timeout = 400000
$Message.From = "From#gmail.com"
$Message.To.Add("To#gmail.com")
$Message.Attachments.Add("C:\foo\attach.txt")
$smtp.Send($Message)
On the sender Google Account (From#gmail.com),
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.ps1
By Default, For sending Large Attachments Timeout is Around 100 seconds or so.
In this script, it is increased to Around 5 or 6 minutes
Sometimes you may need to set the EnableSsl to false (in this case the message will be sent unencrypted over the network)

Powershell Email: How to send email with High Importance?

I am trying to send an email with High Importance using Powershell. But when mail comes to inbox it does not mark with High Importance.
Following is email script:
$EmailFrom = "monitoring#mydomainname.no"
$EmailTo = "fatherazrael#tcs.com"
$Subject = "Disk Space Low: $server"
$Body = "Server Name: $server, <NEED NEW LINE> Drive: C, <NEED NEW LINE> Total Size: $sizeGB, <NEED NEW LINE> Space Left: $freeSpaceGB"
$SMTPServer = "scan.opinergo.fn"
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 25)
#$SMTPClient.Credentials = New-Object System.Net.NetworkCredential("<From mail ID>", "Password");
$SMTPClient.Send($EmailFrom, $EmailTo, $Subject, $Body)
For High Importance i have added following but none is working when mail comes to outlook:
1) $EmailPriority = [System.Net.Mail.MailPriority]::High
Mail Comes but no importance
2) $Priority = [System.Net.Mail.MailPriority]::High
Mail Comes but no importance
3) $Priority = "high"
Mail Comes but no importance
4) $EmailPriority = "high"
Mail Comes but no importance
This code would send out a high priority email:
$smtp = new-object Net.Mail.SmtpClient("yourDomain.com")
$email = New-Object System.Net.Mail.MailMessage
$email.From = "fromEmail#email.com"
$email.To.Add("ToEmail#email.com")
$email.Subject = "Enter your Email Subject"
$email.Body = "Enter the body of your email"
$email.Priority = [System.Net.Mail.MailPriority]::High
$smtp.Send($email)
Try using the Send-MailMessage cmdlet and specify the -Priority parameter:
$password = "pass" | ConvertTo-SecureString -AsPlainText -Force
$credentials = New-Object PSCredential("username", $password)
Send-MailMessage `
-To recipient#example.com `
-From sender#example.com `
-Subject Example `
-SmtpServer smtp.example.com `
-Credential $credentials
-Priority High
$emailMessage.Priority = 2
$emailSmtpServer = “xyz”
$emailSmtpServerPort = “587”
$emailSmtpUser = “x#y.z”
$emailSmtpPass = “abc”
$emailMessage = New-Object System.Net.Mail.MailMessage
$emailMessage.From = “x#y.z”
$emailMessage.To.Add( “x1#y.z” )
$emailMessage.To.Add( “x2#y.z” )
$emailMessage.Subject = “EMAIL CHECK!”
$emailMessage.IsBodyHtml = “True”
#Low Priority
#$emailMessage.Priority = 1
#High Priority
$emailMessage.Priority = 2
$emailMessage.Body = #”
Email body... <br />
<br />
<br />
Message Sent from Power Shell.
“#
$SMTPClient = New-Object System.Net.Mail.SmtpClient( $emailSmtpServer , $emailSmtpServerPort )
$SMTPClient.EnableSsl = $true
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential( $emailSmtpUser , $emailSmtpPass );
$SMTPClient.Send($emailMessage )