I want to encrypt the mail using S/MIME standard using powershell. I am able to send mail with attachment(without the encryption from powershell). But when i tried to encrypt it with the following code. It doesn't work as it just remove the file and send the body unencrypted. I am using powershell version 5. For testing purposes I want to use previously generated certificates rather than fetching from somewhere. Please advise on my problem or if there is any better approach.
$email = "*********#gmail.com"
$pass = "*******"
$smtpServer = "smtp.gmail.com"
$msg = new-object Net.Mail.MailMessage
$smtp = new-object Net.Mail.SmtpClient($smtpServer)
$smtp.EnableSsl = $true
$msg.From = "$email"
$msg.To.Add("*****b#***.com")
$msg.BodyEncoding = [system.Text.Encoding]::Unicode
$msg.SubjectEncoding = [system.Text.Encoding]::Unicode
$msg.Headers.Add('MIME-Version','asd')
$msg.Headers.Add("From","**abc**")
$msg.Headers.Add("To","**xyz**")
$msg.Headers.Add("Date","11-11-1111")
$msg.Headers.Add("Subject","asfasdd")
$msg.HeadersEncoding =[system.Text.Encoding]::UTF8
$msg.IsBodyHTML = $true
$msg.Subject = "Test mail from PS"
$msg.Body = "<h2> Test mail from PS </h2>
</br>
Hi there
"
$file= get-item -Path "E:\siddhant\abc.txt"
$SMTP.Credentials = New-Object System.Net.NetworkCredential("$email", "$pass");
$Certname="helloo"
$Cert = New-SelfSignedCertificate -certstorelocation E:\siddhant -dnsname $Certname
$pw = ConvertTo-SecureString -String "Pazzword" -Force -AsPlainText
$thumbprint = $Cert.Thumbprint
$MIMEMessage = New-Object system.Text.StringBuilder
$MIMEMessage.AppendLine("MIME-Version: 1.0") | Out-Null
$MIMEMessage.AppendLine("Content-Type: multipart/mixed; boundary=unique-boundary-1") | Out-Null
$MIMEMessage.AppendLine() | Out-Null
$MIMEMessage.AppendLine("This is a multi-part message in MIME format.") | Out-Null
$MIMEMessage.AppendLine("--unique-boundary-1") | Out-Null
$MIMEMessage.AppendLine("Content-Type: text/plain") | Out-Null
$MIMEMessage.AppendLine("Content-Transfer-Encoding: 7Bit") | Out-Null
$MIMEMessage.AppendLine()
$MIMEMessage.AppendLine($Body) | Out-Null
$MIMEMessage.AppendLine() | Out-Null
$MIMEMessage.AppendLine("--unique-boundary-1") | Out-Null
$MIMEMessage.AppendLine("Content-Type: application/octet-stream; name="+ $file.Name) | Out-Null
$MIMEMessage.AppendLine("Content-Transfer-Encoding: base64") | Out-Null
$MIMEMessage.AppendLine("Content-Disposition: attachment; filename="+ $file.Name) | Out-Null
$MIMEMessage.AppendLine() | Out-Null
[Byte[]] $binaryData = [System.IO.File]::ReadAllBytes($file)
[string] $base64Value = [System.Convert]::ToBase64String($binaryData, 0, $binaryData.Length)
[int] $position = 0
while($position -lt $base64Value.Length)
{
[int] $chunkSize = 100
if (($base64Value.Length - ($position + $chunkSize)) -lt 0)
{
$chunkSize = $base64Value.Length - $position
}
$MIMEMessage.AppendLine($base64Value.Substring($position, $chunkSize))
$MIMEMessage.AppendLine()
$position += $chunkSize;
}
$MIMEMessage.AppendLine("--unique-boundary-1--") | Out-Null
[Byte[]] $BodyBytes = [System.Text.Encoding]::ASCII.GetBytes($MIMEMessage.ToString())
$ContentInfo = New-Object -TypeName System.Security.Cryptography.Pkcs.ContentInfo -
ArgumentList(,$BodyBytes)
$CMSRecipient = New-Object System.Security.Cryptography.Pkcs.CmsRecipient $Cert
$EnvelopedCMS = New-Object System.Security.Cryptography.Pkcs.EnvelopedCms $ContentInfo
$EnvelopedCMS.Encrypt($CMSRecipient)
[Byte[]] $EncryptedBytes = $EnvelopedCMS.Encode()
$MemoryStream = New-Object System.IO.MemoryStream #(,$EncryptedBytes)
$AlternateView = New-Object System.Net.Mail.AlternateView($MemoryStream, "application/pkcs7-mime;
smime-type=enveloped-data;name=smime.p7m")
$msg.AlternateViews.Add($AlternateView)
$smtp.Send($msg)
Related
I'm trying to write a PowerShell script that would email as attachments, all files in each subfolder of C:\Reports\ together. For instance, if the subfolders are C:\Reports\ABC having a.txt, b.xml and c.jpg and C:\Reports\DEF having d.txt, e.xml and f.pdf, the code should email a.txt, b.xml and c.jpg in one email and d.txt, e.xml and f.pdf in another.
#Connection Details
$username = ”vallabhherlekar#gmail.com”
$password = ”Appya1979!”
$smtpServer = “smtp.gmail.com”
$Directory = Get-ChildItem “C:\Reports\” -Directory
foreach ($d in $Directory) {
$msg = New-Object Net.Mail.MailMessage
$smtp = New-Object Net.Mail.SmtpClient($SmtpServer, 587)
#Uncomment Next line for SSL
$smtp.EnableSsl = $true
$smtp.Credentials = New-Object System.Net.NetworkCredential ($username, $password)
$msg.From = "vallabhherlekar#gmail.com"
$msg.To.Add(“vallabhherlekar#gmail.com”)
$msg.Body=”Please See Attached Files”
$msg.Subject = “Email with Multiple Attachments”
Write-Host "Working on directory $($d.FullName)..."
$files = Get-ChildItem -Path "$($d.FullName)" -File
foreach ($file in $files) {
Write-Host “Attaching File :- ” $file.FullName
$attachment = New-Object System.Net.Mail.Attachment –ArgumentList
$file.FullName
$msg.Attachments.Add($attachment)
}
$smtp.Send($msg)
$attachment.Dispose();
$msg.Dispose();
}
I try to send an email using code based on this example: https://blog.victorsilva.com.uy/credenciales-con-powershell/, but the email is not sending:
$emailSmtpServer = "smtp.mail.yahoo.com"
$emailSmtpServerPort = "587"
$password = Get-Content -Path "C:\Users\USUARIOPC\password2.txt" |
ConvertTo-SecureString -String $password
$credential = New-Object
System.Management.Automation.PsCredential("jrosh.01#yahoo.com", $password)
$emailMessage = New-Object System.Net.Mail.MailMessage
$emailMessage.From = "jrosh.01#yahoo.com"
$emailMessage.To.Add( "jrosh.01#yahoo.com" )
$emailMessage.subject = "Notificacion de: $($env:computername)"
$emailMessage.IsBodyHtml = $true
$evento = Get-WinEvent –FilterHashTable #{logname="System"} -MaxEvents 1 |
Where {$_.ID -Match "1020"}
$emailMessage.Body = #"
<H1>Alerta Scope DHCP</H1>
<p>Evento a revisar en: <strong>$($evento.MachineName)</strong>.</p>
<p>Identificador: <strong>$($evento.Id)</strong>.</p>
<p>Fecha / Hora: <strong>$($evento.TimeCreated)</strong>.</p>
<p>Texto: <strong>$($evento.Message)</strong>.</p>
<br>
<H5><i>$(get-date)</i></H5>
"#
$SMTPClient = New-Object System.Net.Mail.SmtpClient( $emailSmtpServer ,
$emailSmtpServerPort )
$SMTPClient.EnableSsl = $true
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential(
$emailSmtpUser , $credential );
$SMTPClient.Send( $emailMessage )
Write-Host "Correo Enviado..."
From the error messages you submitted it looks like there's a problem with password file. Please make sure that you export your password like this:
"P#ssword1" | ConvertTo-SecureString -AsPlainText -Force | ConvertFrom-SecureString | Out-File C:\Users\USUARIOPC\password2.txt
Where P#ssword1 is your password.
I'm new to PowerShell, I'm running Windows Server 2012 R2. The following Script gives me Output what I want but in the message the output is not appearing and it saying the Body cannot be "null" or "empty".
$fileToLocate = "*"
$Directories = #(
"C:\CtvFTPSite\AE1\ASN\Undelivered\",
"C:\CtvFTPSite\AE1\Invoices\Undelivered\",
"C:\CtvFTPSite\AE1\SO\Undelivered\",
"C:\CtvFTPSite\AE2\ASN\Undelivered\",
"C:\CtvFTPSite\AE2\Invoices\Undelivered\",
"C:\CtvFTPSite\AE2\SO\Undelivered\",
"C:\CtvFTPSite\BH1\ASN\Undelivered\",
"C:\CtvFTPSite\BH1\Invoices\Undelivered\",
"C:\CtvFTPSite\BH1\SO\Undelivered\",
"C:\CtvFTPSite\KW1\ASN\Undelivered\",
"C:\CtvFTPSite\KW1\Invoices\Undelivered\",
"C:\CtvFTPSite\KW1\SO\Undelivered\",
"C:\CtvFTPSite\OM1\ASN\Undelivered\",
"C:\CtvFTPSite\OM1\Invoices\Undelivered\",
"C:\CtvFTPSite\OM1\SO\Undelivered\",
"C:\CtvFTPSite\SA1\ASN\Undelivered\",
"C:\CtvFTPSite\SA1\Invoices\Undelivered\",
"C:\CtvFTPSite\SA1\SO\Undelivered\"
)
$filesUndelivered = Join-Path -Path $Directories -ChildPath $fileToLocate | Where-Object{Test-Path $_} | ForEach-Object{
Get-ChildItem $Directories -Recurse | % { Write-Host $_.FullName }
}
$Max_mins = "-5"
$Curr_date = get-date
$username = "myusername#myemail.com"
$password = Get-Content C:\security\string.txt | ConvertTo-SecureString
$cred = new-object -typename System.Management.Automation.PSCredential `
-argumentlist $username, $password
$localIpAddress = $(ipconfig | where {$_ -match 'IPv4.+\s(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' } | out-null; $Matches[1])
[string]$messagebody ="$filesUndelivered"
[string]$titlefailed ="Urgent You Have Files in Undelivered Folder in $localIpAddress in $env:computername"
$portno = "25"
$smtpsrv = "mail.server.com"
$smtpto = "myusername#myemail.com"
$smtpfrom ="myusername#myemail.com"
if ($filesfailed.Count)
{
foreach ($file in $filesUndelivered) {[string]$messagebody += $file.FullName + "`r`n"}
Send-MailMessage -To $smtpto -From $smtpfrom -port $portno -SmtpServer $smtpsrv -Credential $cred -Subject $titlefailed -Body $messagebody
}
Fixed
$fileToLocate = "*"
$failedpath = #(
"C:\CtvFTPSite\AE1\ASN\Undelivered\",
"C:\CtvFTPSite\AE1\Invoices\Undelivered\",
"C:\CtvFTPSite\AE1\SO\Undelivered\",
"C:\CtvFTPSite\AE2\ASN\Undelivered\",
"C:\CtvFTPSite\AE2\Invoices\Undelivered\",
"C:\CtvFTPSite\AE2\SO\Undelivered\",
"C:\CtvFTPSite\BH1\ASN\Undelivered\",
"C:\CtvFTPSite\BH1\Invoices\Undelivered\",
"C:\CtvFTPSite\BH1\SO\Undelivered\",
"C:\CtvFTPSite\KW1\ASN\Undelivered\",
"C:\CtvFTPSite\KW1\Invoices\Undelivered\",
"C:\CtvFTPSite\KW1\SO\Undelivered\",
"C:\CtvFTPSite\OM1\ASN\Undelivered\",
"C:\CtvFTPSite\OM1\Invoices\Undelivered\",
"C:\CtvFTPSite\OM1\SO\Undelivered\",
"C:\CtvFTPSite\SA1\ASN\Undelivered\",
"C:\CtvFTPSite\SA1\Invoices\Undelivered\",
"C:\CtvFTPSite\SA1\SO\Undelivered\"
)
$Max_mins = "-5"
$Curr_date = get-date
$username = "username#email.com"
$password = Get-Content C:\security\string.txt | ConvertTo-SecureString
$cred = new-object -typename System.Management.Automation.PSCredential `
-argumentlist $username, $password
$filesfailed = Get-ChildItem -Path $failedpath | Where{$_.CreationTime -lt ($Curr_date).addminutes($Max_mins)}
$localIpAddress = $(ipconfig | where {$_ -match 'IPv4.+\s(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' } | out-null; $Matches[1])
[string]$messagebody =""
[string]$titlefailed ="Urgent You Have Files in Undelivered Folder in $localIpAddress in $env:computername"
$portno = "25"
$smtpsrv = "mail.server.net"
$smtpto = "username#email.com"
$smtpfrom ="username#email.com"
if ($filesfailed.Count)
{
foreach ($file in $filesfailed) {[string]$messagebody += $file.FullName + "`r`n"}
Send-MailMessage -To $smtpto -From $smtpfrom -port $portno -SmtpServer $smtpsrv -Credential $cred -Subject $titlefailed -Body $messagebody
}
How can I use powershell to embed an HTML file in email body? This is what I have so far:
##Connect to the data source using the connection details and T-SQL command we provided above, and open the connection
$connection = New-Object System.Data.OleDb.OleDbConnection $connectionDetails
$command = New-Object System.Data.OleDb.OleDbCommand $sqlCommand,$connection
$connection.Open()
##Get the results of our command into a DataSet object, and close the connection
$dataAdapter = New-Object System.Data.OleDb.OleDbDataAdapter $command
$dataSet = New-Object System.Data.DataSet
$dataAdapter.Fill($dataSet)
$connection.Close()
$body = $TableHeader
$dataSet.Tables | Select-Object -Expand Rows |
Select-Object * -ExcludeProperty Comment, RowError, RowState, Table, ItemArray, HasErrors |
ConvertTo-HTML -head $a –body $body |
Out-File $OutputFile
$ReportLink = "file://serverr/c$/Output/Report.Html"
Write-Output " Reporting"
$MailUsername = "you"
$MailPassword = "your pasword"
$cred = New-Object System.Management.Automation.PSCredential -ArgumentList #($MailUsername,(ConvertTo-SecureString -String $MailPassword -AsPlainText -Force))
Send-MailMessage -To "abc#ymail.com" -From "xyz#ymail.com" -SmtpServer Ymail -Credential $cred -Subject " Report:" -Body $ReportLink -BodyAsHtml
I am still new to powershell. Thank you in advance
Assuming the data whichever you want to change to HTML format is in $Result Array
$EmailFrom = ""
$EmailTo = ""
$SMTPServer = ""
$EmailSubject =""
$Report = "<HTML><TITLE>Title</TITLE><BODY background-color:peachpuff><font color =""#99000"" face=""Microsoft Tai le""><H2> Heading </H2></font><Table border=1 cellpadding=0 cellspacing=0><TR bgcolor=gray align=center><TD><B>Row1</B></TD><TD><B>Row2</B></TD><TD><B>Row3</B></TD><TD><B>Row4</B></TD></TR>"
Foreach($Entry in $Result)
{
$Report += "<TR>"
$Report += "<TD>$($Entry.Value1)</TD><TD>$($Entry.Value2)</TD><TD>$($Entry.Value3)</TD><TD align=center>$($Entry.Value4)</TD></TR>"
}
$Report += "</Table></BODY></HTML>"
$mailmessage = New-Object system.net.mail.mailmessage
$mailmessage.from = ($EmailFrom)
$mailmessage.To.add($EmailTo)
$mailmessage.Subject = $EmailSubject
$mailmessage.Body = $Report
$mailmessage.IsBodyHTML = $true
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer)
$SMTPClient.Send($mailmessage)
I needed to add this script, it works like magic
$message = new-object System.Net.Mail.MailMessage
$message.From = $from
$message.To.Add($to)
$message.CC.Add($CC)
$Subject = " put subject here"
$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)
I've written a PowerShell script that searches a folder for a file that matches a keyword eg Japan and then adds the file as an attachment to an email.
The email sends correctly, however the file isn't attached.
Add-PSSnapin Microsoft.Exchange.Management.Powershell.Admin -ErrorAction
SilentlyContinue
$dir = "C:\Users\user\Desktop"
$file = Get-ChildItem -Path $dir | -Filter "$keyword" -Recurse | Select-Object
$keyword = "Japan"
$mailboxdata = (Get-MailboxStatistics | select DisplayName,TotalItemSize,TotalDeletedItemSize, ItemCount, LastLoggedOnUserAccount, LastLogonTime)
$mailboxdata | Export-Csv "$file"
$smtpServer = "192.168.1.100"
$att = New-Object Net.Mail.Attachment($file)
$msg = New-Object Net.Mail.MailMessage
$smtp = New-Object Net.Mail.SmtpClient($smtpServer)
$msg.From = "email#mail.com"
$msg.To.Add("email#othermail.com")
$msg.Subject = "Notification from email server"
$msg.Body = "Attached is the email server mailbox report for Japan"
$msg.Attachments.Add($att)
$smtp.Send($msg)
$att.Dispose()
You've modified a script from another source (that sends Mailbox Statistics from Microsoft Exchange) and you've left in parts of it that you do not need.
$dir = "C:\Users\user\Desktop"
$keyword = "Japan"
$smtpServer = "192.168.1.100"
$file = Get-ChildItem -Path $dir -Filter "*$keyword*" -Recurse
$att = New-Object Net.Mail.Attachment($file)
$msg = New-Object Net.Mail.MailMessage
$smtp = New-Object Net.Mail.SmtpClient($smtpServer)
$msg.From = "email#mail.com"
$msg.To.Add("email#othermail.com")
$msg.Subject = "Notification from email server"
$msg.Body = "Attached is the email server mailbox report for Japan"
$msg.Attachments.Add($att)
$smtp.Send($msg)
$att.Dispose()
I would use Send-MailMessage instead as it's syntax is much easier to use:
$dir = "C:\Users\user\Desktop"
$keyword = "Japan"
$Attachment = Get-ChildItem -Path $dir -Filter "*$keyword*" -Recurse
$From = "email#mail.com"
$To = "email#othermail.com"
$Subject = "Files matching: $keyword"
$Body = "Attached is the file for: $keyword"
$SMTPServer = "192.168.1.100"
Send-MailMessage -From $From -To $To -Subject $Subject -Body $Body -SmtpServer $SMTPServer -Attachments $Attachment.FullName