Result of Powershell Script sent via email - powershell

On the result of running the below script, it returns the following:
How could I get this result sent via email? I'm not sure how to get the result into a parameter that I can pass into the Body of an email script:
https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/send-mailmessage?view=powershell-6
$azPath = "C:\Program Files (x86)\Microsoft SDKs\Azure\AzCopy\"
Set-Location $azPath
$StorageAccountName = "#"
$StorageAccountKey = "#"
$ContainerName = "#"
$SourceFolder = "#"
$DestURL = "https://$StorageAccountName.blob.core.windows.net/$ContainerName"
$Result = .\AzCopy.exe /source:$SourceFolder /dest:$DestURL /BlobType:block /destkey:$StorageAccountKey /Y /S /XO
$Result

You can either store your result in a file and send it as an attachment:
$Result | Out-File Result.txt
Send-MailMessage -From 'User01 <user01#fabrikam.com>' -To 'User02 <user02#fabrikam.com>' -Subject 'Sending the Attachment' -Body "Forgot to send the attachment. Sending now." -Attachments .\Result.txt -SmtpServer 'smtp.fabrikam.com'
Or send the content of $Result (=string[]) as a string in the -Body:
$body = $Result -join '`n' # Join result to a single string with line breaks
Send-MailMessage -From 'User01 <user01#fabrikam.com>' -To 'User02 <user02#fabrikam.com>' -Subject 'Sending the Attachment' -Body $body -SmtpServer 'smtp.fabrikam.com'
Or (as stated in #Olfa's comment) convert it to HTML and add the -BodyAsHtml switch:
$body = $Result | ConvertTo-Html
Send-MailMessage -From 'User01 <user01#fabrikam.com>' -To 'User02 <user02#fabrikam.com>' -Subject 'Sending the Attachment' -Body $body -SmtpServer 'smtp.fabrikam.com' -BodyAsHtml

Related

Not able to send the mail through powershell script

Below is the code:
$TLS12Protocol = [System.Net.SecurityProtocolType] 'Tls12'
[System.Net.ServicePointManager]::SecurityProtocol = $TLS12Protocol
$smtpencryption = 'tls'
$From = "JIT.Batch#duckcreek.com"
$To = "abhishek.chawla#duckcreek.com”
$recipients = "<abhishek.chawla#duckcreek.com>"
[string[]]$To = $recipients.Split(',')
$Cc = "abhishek.chawla#duckcreek.com"
$Subject = "JITAppointment batch Started on StateAuto Production"
$Body = "JITAppointment batch Started on SA Production for latest file"
$SMTPServer = "smtp.office365.com"
$SMTPPort = "587"
$secpasswd = ConvertTo-SecureString "*******" -AsPlainText -Force
$mycreds = New-Object System.Management.Automation.PSCredential($from, $secpasswd)
Send-MailMessage -From $From -to $To -Cc $Cc -Subject $Subject -Body $Body -BodyAsHtml -SmtpServer $SMTPServer -Port $SMTPPort -UseSsl -Credential $mycreds
#Send-MailMessage -From $From -to $To -Cc $Cc -Subject $Subject -Body $Body -SmtpServer $SMTPServer
and i am getting below error when i run this on server:
enter image description here
I wont be able to send the mail through this code.
I can see you're sending via smtp.office365.com. Microsoft 365 no longer supports basic authentication which means you cannot use Send-MailMessage. Alternatives include Send-MgUserMail which is part of Module Microsoft.Graph.Users.Actions

Send-MailMessage asking for credentials

Send-Mailmessage prompts for my credentials when executed.
I've tried creating a $from variable to provide Powershell with my credentials (technically this is working since I'm only being asked for my password but want it to send the email without authenticating)
$from = (Get-ADUser $env:UserName -Properties emailaddress).emailaddress
$To = "example#example.org"
$Subject = "test2"
$Body = "Test2"
$SMTPServer = "10.98.0.20"
$SMTPPort = "25"
Send-MailMessage -From $From -to $To -Subject $Subject -Body $Body -SmtpServer $SMTPServer -port $SMTPPort -Credential $from
Don’t use -Credential. Just pass -From an address as a string. SMTP doesn’t care. This is happening because you are including -Credential, or your mail server doesn’t accept anonymous relay access.

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

Can I use TLS with Send-MailMessage cmdlet?

I am trying to send an email using PowerShell, but need to use TLS. Any way I can do that using Send-MailMessage cmdlet?
This is my code:
$file = "c:\Mail-content.txt"
if (test-path $file)
{
$from = "afgarciact#gmail.com"
$to = "<slopez#comfama.com.co>","<carloscu#comfama.com.co>"
$pc = get-content env:computername
$subject = "Test message " + $pc
$smtpserver ="172.16.201.55"
$body = Get-Content $file | Out-String
[System.Net.ServicePointManager]::ServerCertificateValidationCallback = { return $true }
foreach ($recipient in $to)
{
write-host "Sent to $to"
Send-MailMessage -smtpServer $smtpserver -from $from -to $recipient -subject $subject -bodyAsHtml $body -Encoding ([System.Text.Encoding]::UTF8)
}
}
else
{
write-host "Configuración"
}
Thanks a lot!
Make sure your specify the -UseSsl switch:
Send-MailMessage -SmtpServer $smtpserver -UseSsl -From $from -To $recipient -Subject $subject -BodyAsHtml $body -Encoding ([System.Text.Encoding]::UTF8)
If the SMTP server uses a specific port for SMTP over TLS, use the -Port parameter:
Send-MailMessage -SmtpServer $smtpserver -Port 465 -UseSsl -From $from -To $recipient -Subject $subject -BodyAsHtml $body -Encoding ([System.Text.Encoding]::UTF8)
If you want to make sure that TLS is always negotiated (and not SSL 3.0), set the SecurityProtocol property on the ServicePointManager class:
[System.Net.ServicePointManager]::SecurityProtocol = 'Tls,TLS11,TLS12'
I have been fighting this all day. The fix for me ended up being needing to run this in a separate line first, and then I was able to run my Send-MailMessage commands:
[System.Net.ServicePointManager]::SecurityProtocol = 'Tls,TLS11,TLS12'
Thank you for the suggestion!

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