Im sending a testemail via powershell like
$messageParameters = #{
Subject = "Email Tool"
Body = Get-Content "C:\body.txt" | out-string
From = "Info <info#xy.de>"
To = "Me <me#xy.de>"
SmtpServer = "mail.xy.de"
Encoding = New-Object System.Text.UTF8Encoding
}
send-mailmessage #messageParameters -BodyAsHtml
everything is working find except the encoding.
if i don't use encoding some characters are send as ??
and if i use it, what i actually want to do, than i get this Ä Ö Ü
but it should be ä ö ü and not this above.
If i don't send the mail as HTML it works.
How can i send the mail with the right encoding AND as html ?
I believe the problem is that your text-file is getting jumbled when you are reading it into a variable as non-utf8.
I would try getting the text file as UTF-8 and keeping the Encoding line.
Body = Get-Content "C:\body.txt" -Encoding UTF8 | Out-String
EDIT: Added Out-String per Dwza.
Related
Please help.
In console look hebrew correct but in spreadsheet is not correctenter image description here
$import = New-Object System.Collections.ArrayList($null)
$import.Add( #("route_id"))
$import.Add( #( 'אבא אבן 1 הרצליה' )) | Out-NULL
try {
$Response = Set-GSheetData -accessToken $accessToken -rangeA1 "A1:X$($import.Count)" -sheetName "23-07-21" -spreadSheetID $SpreadsheetID -values $import -Verbose
$Response | ConvertTo-Json
} catch {
$err = $_.Exception
$err | Select-Object -Property *
"Response: "
$err.Response
}
Hebrew might not be supported in Sheets, you would need to install a font. You can try with this one
https://fonts.google.com/noto/specimen/Noto+Sans+Hebrew?query=hebrew
Update
After testing using the Rest API, it works, so the issue might be related on how the PowerShell process hebrew characters.
I've found some information on how to process hebrew characters in the Windows Powershell
[Console]::OutputEncoding = [Text.Encoding]::GetEncoding(1255)
Make sure the console is outputting the right characters and the POST a request to Google Sheets
It's bug in the psmodule. Author must specify encoding UTF8.
https://github.com/umn-microsoft-automation/UMN-Google/pull/50
I'm attempting to create a Send-Email function in a script which can change the email address each time the script is used. However, I'm currently suck being forced to use a static email:
function Send-Email (
$recipientEmail = "EMAIL",
$subject = "Ticket" + $type,
$body
) {
$outlook = New-Object -ComObject Outlook.Application
$mail = $outlook.CreateItem(0)
$mail.Recipients.Add("EMAIL")
$mail.Subject = ("Ticket - " + $type)
$mail.Body = $body # For HTML encoded emails
$mail.Send()
Write-Host "Email sent!"
}
I'd like to set it up so that I can define $recipientEmail and then later use this input with $mail.Recipients.Add("EMAIL") - I've beend doing $mail.Recipients.Add("$receipientemail") and the like without any luck and wondering if I'm approaching this completely wrong?
I'd like it to be set up in a way that it could use
[void] $listBox.Items.Add("Email1")
[void] $listBox.Items.Add("Email2")
[void] $listBox.Items.Add("Email3")
And accept that as the email to send to instead of only working with one email.
This whole thing rang a bell with me, and I went "code dumpster diving". I wrote this same function (more or less) a year ago. I'm not using $mail.recipients.add(); I'm using $Mail.To = $RecipientEmail; if I want multiple recipients, I simply -join ";" them and assign to $mail.To. The members $mail.CC and $mail.BCC work the same way:
Function Send-Email {
<#
.Synopsis
Sends Email using Microsoft Outlook
.DESCRIPTION
This cmdlet sends Email using the Outlook component of a locally-installed
Microsoft Office. It is not expected to work with the "Click-to-run" versions.
This version requires that Outlook be running before using the cmdlet.
.PARAMETER To
Must be a quoted string or string array, may not be omitted.
Specifies the address to send the message to. If an array, it will
be converted to a semicolon-delimited string. May contain contact
groups.
.PARAMETER Subject
Must be a quoted string, may not be omitted.
Specifies the subject of the message to be sent.
.PARAMETER Body
Must be a string or a string array, may not be omitted.
Contains the text of the message to be sent. If supplied as a string in double
quotes, any PowerShell variables will be expanded unless the leading $ is
escaped. If supplied in a script via a variable containing a here-doc, will
reproduce the here-doc. If supplied as an array, either by variable or by the
Get-Content cmdlet, the array elements will be joined with `r`n as "separators".
A body supplied via Get-Content will not have expanded variables; arrays created
in scripts using double quotes or via here-docs willl have expanded variables.
.PARAMETER CC
Must be a quoted string or string array, may be omitted.
Specifies an address to send a copy of the message to. If an array, it will be
converted to a semicolon-delimited string. All recipients can see that a copy
of the message was sent to the addresses here.
.PARAMETER BCC
Must be a quoted string or string array, may be omitted.
Specifies an address to send a copy of the message to. If an array, it will be
converted to a semicolon-delimited string. The recipients named here are not
displayed as a recipient of the message, even though they do receive the message.
.PARAMETER Attachments
Must be a quoted string or string array, may be omitted.
Specifies one or more files to be included with the message as attachments.
.INPUTS
This version of the cmdlet does not accept input from the pipeline
.OUTPUTS
No output to the pipeline is generated. The cmdlet does return an error code.
.EXAMPLE
Send-Email -To "boss#example.com" -Subject "Personnel Issue - John M. Ployee" -Body "I need a raise."
Sends an email with the indicated subject and body to the stated address.
.EXAMPLE
$messagebody = #"
Roses are red
Violets are blue
I need a raise
And so do you
"#
$others = "boss-of-boss#example.com","hr#example.com"
Send-Email -To "boss#example.com" -Subject "Personnel Issue - John M. Ployee" -cc $others -Body $messagebody
Sends an email with the indicated subject to the stated address. The body
will be composed of the lines in the variable $messagebody as shown; the
line breaks are preserved. A copy of the message is sent to the two addresses
listed in $others.
.EXAMPLE
Send-Email -To "boss#example.com" -Subject "Personnel Issue - John M. Ployee" -Body (Get-Content -Path "C:\Request-for-raise.txt")
Sends an email with the indicated subject and body to the stated address.
The body is drawn from the indicated file, and line breaks are preserved.
.EXAMPLE
Send-Email -To "boss#example.com" -Subject "Personnel Issue - John M. Ployee" -Body "Please see attached for rationale for raise" -Attachments (Get-Content -Path "C:\Request-for-raise.txt")
Sends an email with the indicated subject and body to the stated address.
The indicated file is included as an attachment.
.NOTES
Planned Future Enhancements:
1. Allow the cmdlet to accept input (message body text) from the pipe.
2. Allow the cmdlet to accept the body from a file (parameter -BodyFromFile)
3. Allow the cmdlet to start up Outlook if it is not already running.
This includes shutting it down afterward.
4. Allow the body to be formatted as HTML or RTF, and properly handle this.
Initially, switches (e.g., -BodyAsHTML or -BodyAsRTF); better would be to
use file name (e.g., -BodyFromFile "C:\Test.html" would still set the message
format to HTML even in the absence of -BodyAsHTML); best would be to inspect
content of file.
Based on a script from http://www.computerperformance.co.uk/powershell/powershell_function_send_email.htm
#>
[cmdletbinding()]
Param (
[Parameter(Mandatory=$True)]
[String[]]$To,
[String[]]$CC,
[String[]]$BCC,
[Parameter(Mandatory=$True)]
[String]$Subject,
[Parameter(Mandatory=$True)]
[String[]]$Body,
[String[]]$Attachments
)
Begin {
# Future Enhancement: Start Outlook if it's not already running
} # End of initialization
Process {
# Create an instance Microsoft Outlook
$Outlook = New-Object -ComObject Outlook.Application
# Create a new mail message
$Mail = $Outlook.CreateItem(0)
# Set up the email
$Mail.To = $To -join ";"
if ($CC -ne $null) {
$Mail.CC = $CC -join ";"
}
if ($bcc -ne $null) {
$Mail.BCC = $BCC -join ";"
}
$Mail.Subject = "$Subject"
$Mail.Body = $Body -join "`r`n"
if ($attachments -ne $null) {
foreach ($Attachment in $Attachments) {
$silencer = $Mail.Attachments.Add($Attachment)
}
}
# I need to investigate scripting Outlook more.
# The next three comments may be all that's needed
# to handle HTML and/or attachments.
# $Mail.HTMLBody = "When is swimming?"
# $File = "D:\CP\timetable.pdf"
# $Mail.Attachments.Add($File)
# Place message in outbox.
$Mail.Send()
} # End of Process section
End {
# Clean up after ourselves. This prevents Outlook from reporting
# an error on exit.
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($Outlook)
$Outlook = $null
# If Outlook settings are to Send/Receive only on command rather
# than as-needed, force the send at this time.
# NOTE TO SELF: CHECK THIS!
# $Outlook.GetNameSpace("MAPI").SendAndReceive(1)
# If we launched Outlook at the beginning, close it here.
# $Outlook.Quit()
} # End of End section!
} # End of function
<#
Note 2: Look in Outlook's outbox for a newly-created message.
Note 3: If you really want to send the email then append this command:
$Outlook.GetNameSpace("MAPI").SendAndReceive(1)
#>
This question already has answers here:
Word Document.SaveAs ignores encoding, when calling through OLE, from Ruby or VBS
(3 answers)
Closed 5 years ago.
I'm working on a PowerShell script to convert a docx to HTML, and also to change the encoding of the HTML, because by default it saves it as windows-1252.
I need this because later on I send this HTML saved as the body for an email also send by PowerShell. As I am Spanish I need accents and tildes to show up (those are appearing as ? right now).
I tried the SaveAs method with all the parameters, but I couldn't get it to work.
This is my script:
$MSWord = New-Object -ComObject Word.Application
$MSWord.Documents.Open(“C:\Users\USER\Videos\CAMBIO_TURNO.docx”)
$MSWord.Visible = $false
# Save HTML
$saveFormat = [Enum]::Parse([Microsoft.Office.Interop.Word.WdSaveFormat], “wdFormatHTML”);
$path = “C:\Users\USER\Videos\CAMBIO_TURNO.html”
$MSWord.ActiveDocument.SaveAs([ref]$path, [ref]$saveFormat)
# Close File
$MSWord.ActiveDocument.Close()
$MSWord.Quit()
Then, to send it to me, I use this other code on PowerShell:
$OutputEncoding = [System.Text.Encoding]::UTF8
$body = [IO.File]::ReadAllText(“C:\Users\USER\Videos\CAMBIO_TURNO.html”)
Send-MailMessage -To “EMAIL#EMAIL” -From “EMAIL#EMAIL” -Subject “CAMBIO” -Body $body -Encoding $OutputEncoding -BodyAsHtml -Attachments “C:\Users\USER\Videos\CAMBIO_TURNO.xlsx” -Dno onSuccess, onFailure -SmtpServer smtp.gmail.com -Credential EMAIL#EMAIL
SECOND UPDATE
(Although I went to the page that is marked as duplicate: Word Document.SaveAs ignores encoding, when calling through OLE, from Ruby or VBS it didn't solve my problem. that word configuration doesn't work)
Here is what I tried after saving my document with the web options as utf-8:
#DEFINE outputencoding FOR THE CONSOLE - IT SEEMS THAT IT DOESN'T WORK. I typed ñ and ó and they appear as ?? becasue it doesn't convert the hexadecimal values to the right charset
$OutputEncoding= New-Object -typename System.Text.ASCIIEncoding
# Open word to add input into the signature file
$MSWord = New-Object -ComObject word.application
$MSWord.Documents.Open('C:\Users\USER\Videos\CAMBIO_TURNO.docx')
# Save HTML
$saveFormat = [Enum]::Parse([Microsoft.Office.Interop.Word.WdSaveFormat], 'wdFormatFilteredHTML');
$path = 'C:\Users\USER\Videos\CAMBIO_TURNO.html'
$default = [Type]::Missing
$MSWord.ActiveDocument.SaveAs2([ref]$path, [ref]$saveFormat, [ref]$default, [ref]$default, [ref]$default, [ref]$default, [ref]$default, [ref]$default, [ref]$default, [ref]$default, [ref]$default, [ref]28591)
# Close File
$MSWord.ActiveDocument.Close()
$MSWord.Quit()
$HTMLw = Get-Content -Path 'C:\Users\USER\Videos\CAMBIO_TURNO.html' -Encoding ASCII -Force
$HTMLw -replace 'charset=windows-1252','charset=ISO-8859-1' | Set-Content -Path 'C:\Users\USER\Videos\CAMBIO_TURNO.html' -Encoding ASCII -Force
For one thing you should avoid typographic quotes (“). Always use straight quotes in code (").
With that said, the problem you're facing is most likely that passing a string with the name of a symbolic constant doesn't work. Either use the numeric value of the constant or define a constant yourself:
New-Variable -Name wdFormatHTML -Value 8 -Option Constant
$MSWord.ActiveDocument.SaveAs($path, $wdFormatHTML)
Alternatively you should be able to resolve the constants via the Interop API, but I don't have an Office installation at hand right now, so I can't test.
You also didn't specify the desired encoding of the output file when saving.
New-Variable -Name wdFormatHTML -Value 8 -Option Constant
$default = [Type]::Missing
$MSWord.ActiveDocument.SaveAs($path, $wdFormatHTML, $default, $default, $default, $default, $default, $default, $default, $default, $default, 65001)
I have a requirement to send email to thousands of different recipients with a different attachment to each of them.
I have the list of recipients in a text file and the list of attachment paths in another text file.
For the first recipient in the text file, first attachment path should be used.
For the second recipient in the text file, second attachment path should be used.
The code below sends all attachments to all recipients separately.
But I would like this to work as I described above. Only one email should be sent to each recipient with the corresponding attachment.
Please let me know if this is achievable. I can also copy the recipients and paths to attachments in two different columns of an Excel spreadsheet if it is possible with Excel.
I can achieve this by constructing thousand different send-mailmessage lines with Excel but that looks like an ugly way of doing. That's why I would like to know if there is a better way of doing this.
$attachments = get-content C:\attach.txt
$recipients = get-content C:\recip.txt
foreach ($attachment in $attachments)
{
foreach ($recipient in $recipients)
{
Send-MailMessage -From "recipient#target.com" -To $recipient -subject "Test" -smtpServer smtp.server.com -attachments $attachment
}
}
One possibility:
$MailParams =
#{
From = "recipient#target.com"
Subject = "Test"
SmtpServer = 'smtp.server.com'
}
$recipients = get-content C:\recip.txt
get-content C:\attach.txt |
foreach { $i=0 } { $_ | Send-MailMessage #MailParams -To $recipients[$i++] }
Use a for loop to iterate through both files in tandem:
for ($i = 0; $i -lt $recipients.Count; $i++) {
Send-MailMessage -From "recipient#target.com" -To $recipients[$i] -Subject "Test" -SmtpServer smtp.server.com -Attachments $attachments[$i]
}
Presumably the number of lines in both files should be the same, so $recipients.Count is the number of lines in both recip.txt and attach.txt; you could use $attach.Count in the for loop just as well.
You could also go the Excel route, but then save the file as a CSV to make things simpler. With a CSV file, you could use this code, where Recipient and Attachment are the column names:
Import-Csv <path_to_csvfile> | %{Send-MailMessage -From "recipient#target.com" -To $_.Recipient -Subject "Test" -SmtpServer smtp.server.com -Attachments $_.Attachment}
That's probably a better idea, because you're less likely to have mistakes matching the attachments to the right recipients if they're in the same file. With separate lists, one error could result in all recipients after that point receiving the wrong attachments.
I want to encode a string into UTF8 in PowerShell.
This is what I tried:
$consumer_key ="xvz1evFS4wEEPTGEFPHBog"
$enc_consumer_key = System.Text.UTF8Encoding($consumer_key)
But I get an error:
System.Text.UTF8Encoding in not recognize as the name of cmdlet
Try this instead:
$enc = [System.Text.Encoding]::UTF8
$consumerkey ="xvz1evFS4wEEPTGEFPHBog"
$encconsumerkey= $enc.GetBytes($consumerkey)
Encode/Decode:
$enc = [System.Text.Encoding]::UTF8.GetBytes("â")
# 195 162
[System.Text.Encoding]::UTF8.GetString($enc)
# â
[System.Text.Encoding]::ASCII.GetString($enc)
# ??
[System.Text.Encoding]::Default.GetString($enc) # Windows-1252
# â
This is the best question I search that lead me to the above solution for text encoding/decoding characters in PowerShell. In my case I was trying to debug malformed UTF8 characters. Hope it helps someone in the future.
-Check that BOM
If you just want to write the string to file:
$consumer_key ="xvz1evFS4wEEPTGEFPHBog"
$consumer_key | Out-File c:\path\utf8file.txt -Encoding UTF8