Send-MailMessage -From - bad formatting - powershell

Quite simple question. I'm sending an email with send-mailmessage, which works fine. But i'm not entirely happy with the format of the sender.
Send-MailMessage -to "User01 <User01#example.com>" -from "USER02 <USER02#example.com>" -subject "Test mail" -SmtpServer 'mysmtp'
When receiving the Mail (IBM Lotus Notes) the sender is shown as "user02" in lower case, although i'm running the command with the sender in upper case - as shown above.
Is there by purpose any simple way to solve my little problem? Should be shown as "USER02" not as "user02". Reason of Powershell or cause of Lotus Notes?

Related

Send emails with Powershell mailto with formated text

My current script creates (after an account modification) a .ps1 file that is send to another computer and there it is executed opening a new Gmail tab with some information hosted in several variables. I need this email to have format like bold, hyper-link, etc.
Im using the start-process 'mailto' for this but i can not find the way to give this email a format (believe me, i have tried), is this even possible?
I appreciate any insights on this.
My current script creates (after an account modification) a .ps1 file that is send to another computer and there it is executed opening a new Gmail tab with some information hosted in several variables. I need this email to have format like bold, hyper-link, etc.
Im using the start-process 'mailto' for this but i can not find the way to give this email a format (believe me, i have tried), is this even possible?
Additional information:
Code:
$outPut = 'Start-Process'
$outPut+= '"mailto:'+$userMail+"?Subject=Password Reset"+"&Body=Hi, your password is $Password"
$outPut+= '";'
$mailFile = "Path" + $user.SAM + ".ps1"
$outPut | Out-File $mailFile
So, this takes the information this way and stored it in a ps1 file, then executed, opening a new Gmail tab with proper data.
I need that some words has format, bold for the password or hyper-link for guideness link...
Regards!
You haven't provided any indication of what you are doing. But the way to send emails via PowerShell is with the Send-MailMessage cmdlet. If you are using Send-MailMessage and formatting the body of the message with HTML, you just need to make sure you are using the -BodyAsHtml argument.
Here's an example:
$html = "<body><h1>Heading</h1><p>paragraph.</p></body>"
Send-MailMessage -To "bob#fake.com" -From "me#fake.com" -Subject "Test" -Body $html -BodyAsHtml

Adding a variable to a -Body when sending an email

I'm creating a PowerShell script to make our starters and leavers process smoother. We have a separate team who needs to add certain accounts.
What I'd like to do is take the variable that is declared at the start of the script, the new users name, and put it in an email asking for this other department to set them up.
$username = "joe"
Send-MailMessage -SmtpServer smtp.office365.com -From "it#support.com" -To "other#department.com" -Subject 'Starter/Leaver ' -Body "Hi department, `n `nPlease can you add/remove" $username "from the necessary account please `n `nThanks"
I get an error saying:
Send-MailMessage : A positional parameter cannot be found that accepts argument "joe"
The issue here is that the string object sent to -Body is broken because of the quoting. You can just surround the entire body with one set of quotes to achieve the desired result.
$username = "joe"
Send-MailMessage -SmtpServer smtp.office365.com -From "it#support.com" -To "other#department.com" -Subject 'Starter/Leaver ' -Body "Hi department, `n`nPlease can you add/remove $username from the necessary account please `n`nThanks"
Neater Alternative:
I know this answer is not as concise, but it is more readable and adds some flexibility. It uses a here-string to create the body, which doesn't require having to add all of the line feed characters. It also uses splatting to execute the command. With splatting, you can just update the hash table when you need to change something.
$Body = #"
Hi department,
Please can you add/remove $username from the necessary account please
Thanks
"#
$Message = #{ SmtpServer = 'smtp.office365.com'
From = "it#support.com"
To = "other#department.com"
Subject = 'Starter/Leaver'
Body = $Body
}
Send-MailMessage #Message
When running a PowerShell command, parameters are space-delimited. In the case of Send-MailMessage positional parameters are also allowed, which means you don't have to provide the parameter name when passing in a value. In your attempt, your first quote pair was passed to the -Body parameter. After the first closing quote, a space followed by $username is interpreted. Because positional parameters are enabled for the command, PowerShell attempts to assign $username to a parameter and fails. Of course this also means that if you intend to include a space in your string, it must be surrounded by quotes.
Additional Reading:
See About Parameters for an overview of how parameters work.
See About Splatting for information on splatting.

Sent email converts unicode characters into mojibake

I have a mail script sending automated messages to agents about tickets, but Swedish extended characters are being garbled in the script. The text is garbled even when I send it to console instead of emailing.
My research indicates that strings in PowerShell are in UTF16, so I expected things to be preserved... alas, mojibake.
I started with Net.Mail.SmtpClient and that didn't work. I switched to Send-MailMessage because of the -Encoding parameter, but that doesn't change anything for me. I've messed around with the $OutputEncoding variable in case that had something to do with something, but no luck.
So, for example (assuming this doesn't get mangled here either):
The extended characters from the Sweedish alphabet are ÅÄÖåäö
And they get rendered as ÅÄÖåäö
#$encod = ([System.Text.Encoding]::UTF8);
$encod = ([System.Text.Encoding]::Unicode);
$OutputEncoding = $encod;
[string]$message = 'ÅÄÖåäö';
$emailFrom = "Example <EXAMPLE#SAMPLE.COM>";
$emailTo = "Test <TEST#SAMPLE.COM)";
$subject="Långtidsspara";
$smtpserver="smtp.SAMPLE.COM";
#$smtp=New-Object Net.Mail.SmtpClient($smtpServer);
#$smtp.Send($emailFrom, $emailTo, $subject, $message) ;
Send-MailMessage -Body $message -Encoding $encod -From $emailFrom -SmtpServer $smtpserver -Subject $subject -To $emailTo
Edited to add: Previously when I was trying the Net.Mail.SmtpClient() I was doing the following:
$smtp=New-Object Net.Mail.SmtpClient($smtpServer);
$smtp.Send($emailFrom, $emailTo, $subject, $message);
but I couldn't find a way to adjust the encoding.
EDIT 2: thanks to #RemyLebeau I have tried setting the message up as a MailMessage object and using SmtpClient to send that, but no change in behavior.
$smtp=New-Object Net.Mail.SmtpClient($smtpServer);
$mail=New-Object Net.Mail.MailMessage($emailFrom, $emailTo, $subject, $message);
$mail.BodyEncoding = $encod;
$mail.HeadersEncoding = $encod;
$mail.SubjectEncoding = $encod;
$mail.BodyTransferEncoding = [System.Net.Mime.TransferEncoding]::EightBit;
$smtp.SendMailAsync($mail);
EDIT 3: After correcting from UTF16 to UTF8, my email headers say the following
Subject: =?utf-8?B?SW5zcGVsbmluZ3NkYXRhIChMw4PCpW5ndGlkc3NwYXJhKQ==?=
Content-Type: text/plain; charset="utf-8"
Content-Transfer-Encoding: 8bit
But it's all still garbled. I've got Outlook 365 here, but I get emails from Europe all the time, including previous emails from a customer with Å in their name, and Outlook seems to cope?

How to attach files to a Powershell function and send it through MS Outlook?

I've got this code:
Function Mailer ($MSubject, $MBody, $File){
$Outlook = New-Object -ComObject Outlook.Application
$Mail = $Outlook.CreateItem(0)
$Mail.To = "abc#contoso.com"
$Mail.Subject = $MSubject
$Mail.Body = $MBody
$Mail.Attachments.Add($File)
$Mail.Send()
}
I will work if I provide the exact path in the function by assigning it to the $File variable. However, I wish to make this universal for different subjects, bodies and paths. Shall I set the file path as global? What are your thoughts?
Thanks in advance :)
Piotr
This is the code I use to send emails out,
$from="ServerAdmin#Contoso.com"
$to="worker#contoso.com"
$cc=#("John.Doe#Contoso.com", "Jane.Doe#Contoso.com")
$subject="Weekly reports"
$attach="c:\SchTsk\Reports\Server_Inventory_$((Get-Date).ToString('MM-dd-yyyy')).csv","C:\SchTsk\Reports\VMPlatform_$((Get-Date).ToString('MM-dd-yyyy')).csv"
$body="This email contains weekly reports ran on the domain.<br>In an effort to reduce inbox spam, reports that generate separate files are now being attached to one weekly email."
Send-MailMessage -from $from -To $to -cc $cc -subject $subject -SmtpServer snmp.relay.contoso.com -Body $body -BodyAsHtml -Attachments $attach
Actually the function works fine. The problem was with the variable for the file path I was calling to.

How important is parameter order when calling powershell cmdlets?

In PowerShell (PS), is it important to use cmdlet parameters in the order in which they're defined in the official syntax?
I'm adding the -cc parameter to send-mailMessage in an existing script. I added -cc immediately after -To and it works just fine, so I'm inclined to leave well enough alone. But the cmdlet's only parameter set is defined as follows in the help text:
Send-MailMessage [-To] <String[]> [-Subject] <String> [[-Body] <String> ] [[-SmtpServer] <String> ] -From <String> [-Attachments <String[]> ] [-Bcc <String[]> ] [-BodyAsHtml] [-Cc <String[]> ] [-Credential <PSCredential> ] [-DeliveryNotificationOption <DeliveryNotificationOptions> ] [-Encoding <Encoding> ] [-Port <Int32> ] [-Priority <MailPriority> ] [-UseSsl] [ <CommonParameters>]
So I assume best practice would be to run a command like this (cc after subject, body, smtpserver, and from, following the help text):
send-mailmessage -to $mailTo -subject $mailSubj -body $msgbody -smtpserver smtp.domain.tld -from $mailFrom -cc $mailCC
...instead of like this (cc before many of those other parameters):
send-mailmessage -to $mailTo -cc $mailCC -subject $mailSubj -body $msgbody -smtpserver smtp.domain.tld -from $mailFrom
In general I haven't been super careful about this, and stuff works. So surely it'd be overkill (not to mention error-prone) to go back and adjust functional existing scripts along these lines. But maybe it's worth respecting the parameter order going forward, in future scripts? Or not worth the trouble? What say you?
Of course you don't want to make a bad assumption about which parameter is the default and then omit the parameter name; I can also imagine this sort of thing getting messy with custom functions or etc. But my question is about the simpler case, when the parameters of an in-the-box cmdlet are explicitly named, as with the send-mailMessage examples above.
If you are naming your parameters when invoking a cmdlet (e.g.Get-ChildItem -Path *.txt) then it doesn't matter what order you specify them in. Everything is exactly specified by name, so the order in which params were provided is not needed to resolve the arguments.
If you are NOT naming your parameters (e.g. Get-ChildItem *.txt) then it does matter. The cmdlet author can specify that certain parameters can/should be expected, without names, in a certain order. The Powershell engine will try its best to honor that, and in general it will try to pair un-named arguments to any parameters which have not yet been assigned.
Check out this page on parameter types for some more technical info.