I have an email that works from PS. What I have been trying to do is include images embedded in the email (not attachments). Below is what I have so far:
function Email
{
$smtpServer = {smtp server}
$smtpFrom = {email from}
$smtpTo = {email to}
$messageSubject = "test"
$message = New-Object System.Net.Mail.MailMessage $smtpfrom, $smtpto
$message.Subject = $messageSubject
$message.IsBodyHTML = $true
$credentials=new-object system.net.networkcredential({smtpUsername},{smtpPassword})
# $message.Body = Get-Content "D:\Program Files\CymbaTech_FBNC_AM\CTDataLoader\data\TestBody.html"
# The line below will add any attachments you have such as log files.
$message.Attachments.Add("{path}\Image1.png")
$message.Body = '<img src="cid:xyz">'
$smtp = New-Object Net.Mail.SmtpClient($smtpServer)
$smtp.credentials=$credentials.getcredential($smtpserver,"25","basic")
$smtp.Send($message)
}
In the above, I have added image tags to the Body.html file. If I open the html directly, it looks as expected with images showing correctly.
When I send the mail however, the images are just displayed as white boxes with a border. Seems that the script is not loading the images in the file.
Has anyone done similar before and have any suggestions?
You must add images as regular attachments. The HTML body must then reference these attachments though the cid attribute: <img src="cid:xyz"> where "xyz" is the value of the Content-ID MIME attribute on the attachment MIME part.
Related
I'm looking for a method to import a template HTML file in PowerShell and being able to populate it with variables, which in turn sends an e-mail in HTML format containing user data.
I already know how to send the HTML e-mail. And, currently have HTML in a 'here' string embedded in the code. I want to take it a step further, by being able to grab an HTML template based on country code. So, if the user is in the US, it'll get a English HTML data filled e-mail, if they're dutch, they'll get it in Dutch, etc.
function SendMessage {
Param(
[Parameter(Position=0,Mandatory=$true)]
[string]$Identity,
[Parameter(Position=1,Mandatory=$true)]
[string]$Body
)
$Subject = "Important information - Do not delete this email. Welcome to Voicemail"
$SmtpClient = New-object system.net.mail.smtpClient
$MailMessage = New-Object system.net.mail.mailmessage
$CredentialFile = ".\UMcloud-creds.txt"
$password = Get-Content $CredentialFile| ConvertTo-SecureString -Force
$UMCloudAdmin = ""
$SmtpClient.Credentials = New-Object System.Net.NetworkCredential($UMCloudAdmin, $Password)
$smtpclient.Host = "smtp-in.net"
$MailMessage.From = "Voicemail <P#domain.net>"
$MailMessage.To.clear()
$MailMessage.To.Add($Identity)
$MailMessage.Subject = $Subject
$Mailmessage.Body = $body
$MailMessage.IsBodyHtml = 1
$Logofilepath = ((Resolve-Path .\).Path) + "\logo.jpg"
$attachment = New-Object System.Net.Mail.Attachment -ArgumentList $LogoFilePath
$attachment.ContentDisposition.Inline = $True
$attachment.ContentDisposition.DispositionType = "Inline"
$attachment.ContentType.MediaType = "image/jpg"
$attachment.ContentId = "logo.jpg"
$MailMessage.Attachments.Add($attachment)
do {
$Continue = $false
try {
$smtpclient.Send($MailMessage)
Write-LogFile $OutputLogFile ("[SUCCESS] {0} {1}" -f $identity, $UMExtension)
Write-LogFile $customemaillog ("[SUCCESS] {0} {1}" -f $identity, $UMExtension) | out-null
$Continue = $true
} catch {
sleep -s 10
Write-LogFile $OutputLogFile "[ERROR] $Identity $_.Exception.Message"
Write-LogFile $CustomEmailLog "[ERROR] $Identity $UMExtension"
Write-Error $_.Exception.Message
}
} until($Continue -eq $true)
} # End send message
$WelcomeText = Get-Content -Path ".\$CountryID.txt"
$Body = #"
<html>
...
</html>
"#
The here string is part of the script, I'd like to be able to import it from TXT file as not to clutter the script.
Instead of using a text file, create a powershell file (ps1) for each html language format you want. Within those files, you can set a single variable as the html text (file EN_US.ps1):
$bodyENUS = #"Dear <b><font color=red>user</b></font> <br>
This is a test <b>HTML</b> email for your language preference<br>
Sincerely,<br> PdeRover<br>"
You can then pass the variable into the main ps file using two ways: Dot Sourcing or using a Global Variable.
Dot Sourcing: calling the variable by providing the file name.
In the main file:
..\EN_US.ps1
..\PT_PT.ps1
$smtp = "Exchange-Server"
$to = $Identity
$from = "Voicemail <P#domain.net>"
$subject = "This is a Test of HTML Email"
if (user is English speaking){
$bodyByLang = $bodyENUS}
elseif (user is Portuguese speaking) {
$bodyByLang = $bodyPTPT}
send-MailMessage -SmtpServer $smtp -To $to -From $from -Subject $subject -Body $bodyByLang -BodyAsHtml -Priority high
Global Variable: prefixing a variable with $Global:and calling the file during runtime. $Global: bodyENUS Then calling it using $bodyENUS
I asked my own SO question about the difference/best practice of using them. May be worth a read.
This should be enough to point you in the right direction.
I have a powershell script that embedds (not attaches) a picture and sends an email. The picture has increased now to 1500x5000 pixels and now I'm seeing that the pictures lenth gets compressed and it distorts the picture. How ever, when I manually insert the picture via outlook and send an email, it looks fine.
If i save the picture and then open it via paint or something, the picture opens fine. It just looks compressed in the email. Anyone know what may be going on there?
{
$Application = "C:\Autobatch\Spotfire.Dxp.Automation.ClientJobSender.exe"
$Arguments = "http://s.net:8070/spotfireautomation/JobExecutor.asmx C:\Autobatch\HourlyStats.xml"
$CommandLine = "{0} {1}" -f $Application,$Arguments
invoke-expression $CommandLine
$file = "C:\Autobatch\HourlyStats.png"
$smtpServer = "smtp.staom.sec.s.net"
$att = new-object Net.Mail.Attachment($file)
$att.ContentType.MediaType = “image/png”
$att.ContentId = “pict”
$att.TransferEncoding = [System.Net.Mime.TransferEncoding]::Base64
$msg = new-object Net.Mail.MailMessage
$smtp = new-object Net.Mail.SmtpClient($smtpServer)
$msg.Attachments.Add($att)
$msg.From = "d.k#s.com"
$msg.To.Add("r.p#p.com")
$msg.Subject = "Voice and Data Hourly Stats"
$msg.Body = "<p style=’font-family: Calibri, sans-serif’>
Voice and data hourly stats details<br />
</p>
<img src='cid:pict'/>"
$msg.IsBodyHTML = $true
$smtp.Send($msg)
$att.Dispose()
invoke-expression "DEL $file"
}
here is what the picture looks like in the email.
Try adding
$att.ContentDisposition.Inline = $true
I suspect some default behavior is happening under the covers and it's just not consistent between the script and Outlook.
More info here
It seems like your email client shrinks content to a certain maximum size. Try putting <img src='cid:pict'/> in a <div> environment:
<div style="overflow: scroll">
<img src='cid:pict'/>
</div>
Also, if you have any way to retrieve the actual pixel width of the image, you can try to set the CSS of the <img> tag accordingly.
By asking this I may sound like a noob, but Just out of Curiosity, if you have a manual way to send an email via Outlook, why not to make a script to send an automated email with desired screenshot?
IDK, if this might help you or not, but I had made this script long back, for my daily reporting purposes. Well, it fits the bill. Sharing it here, for your views on it.
#In this segment, I navigate IE to my specific destination, screen which I want to capture.
$ie = New-Object -ComObject InternetExplorer.Application
$ie.Visible = $true;
$Website = $ie.navigate('https://put.your.URL.here')
while($Website.Busy){Start-Sleep -Seconds 5}
#In this class, script captures the screen, once, all the data loading is over.
$file = "C:\Users\Desktop\$(Get-Date -Format dd-MM-yyyy-hhmm).bmp"
#P.S. I made it to save that screenshot with current date and time format. Also, default screenshot will be captured in .BMP format.
Add-Type -AssemblyName System.Windows.Forms
Add-type -AssemblyName System.Drawing
$Screen = [System.Windows.Forms.SystemInformation]::VirtualScreen
$width = $Screen.width
$Height = $Screen.Height
$Left = $Screen.Left
$Right = $Screen.Right
$Top = $Screen.Top
$Bottom = $Screen.Bottom
$bitmap = New-Object System.Drawing.Bitmap $width, $Height
$Graphics = [System.Drawing.Graphics]::FromImage($bitmap)
$Graphics.CopyFromScreen($Left, $Top, 0, 0, $bitmap.Size)
$bitmap.Save($File)
Write-Output "Screenshot saved to:"
Write-Output $File
sleep -Seconds 5
#Sending an Email
$Outlook = New-Object -ComObject Outlook.Application
$mail = $Outlook.CreateItem(0)
$mail.To = "your.designated#emailid.com"
$mail.Subject = "Outstanding data as on $(Get-Date -Format dd-MM-yyyy)"
$mail.Body = "PFA screenshot, of all outstanding formation as on $(Get-Date -Format dd-MM-yyyy-hhmm)"
$mail.Attachments.Add($file)
$mail.Send()
I am just answering this, since, I tried commenting above, but I guess, my reputation score is way too less to do that.
Hope this might be helpful for you to find a workaround.
Happy coding. :)
HTML code: is <img src='cid:pict'/> supposed to be <img src='cid:pict'> -just remove the forward slash?
Added: This link might help talking about embedding pic in email. base64 encoded images in email signatures. You can try generation base64 code and put it in email body HTML.
I already posted a question related to this (HTML embedded image in the email not displayed ) and updated my script to include cid, but now my images are attached rather than coming inline. I am not sure how I can use inline images in outlook object.
$Text --> "<br /><font face='Arial'><b><i>For Full Interactive Viewing <a href=http://www.google.com>Click Here</a></i></b></font><br/>"
$MessageImages --> <br/><img src='cid:Volume.png'/><br/><br/><hr><br/><img src='C:\MyImages\Value.png'/><br/><br/><hr><br/><hr>
$FinalText = $Text+$MessageImages
Then I am creating an outlook object and sending it with attachments in it.
$o = New-Object -com Outlook.Application
$mail = $o.CreateItem(0)
$mail.importance = 2
$mail.subject = “Reports - Automated Email from user list “
$mail.HTMLBody = $FinalText
$mail.SentOnBehalfOfName ="*********"
$mail.To = "*******"
$mail.Attachments.Add($file.ToString())
$mail.Send()
It is attached without any issue, but not embedded inline. Can anyone help on this.
I dont have smtp server details and so I cannot use smtp client. So I tried to use this class System.Net.Mail.Attachment as below, but when I tried to add the attachment as below,
PS H:\> $file
Directory: C:\Users\Images
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a--- 23/09/2015 4:04 p.m. 132361 Volume.png
$attachment = New-Object System.Net.Mail.Attachment –ArgumentList ($file.FullName).ToString()
$attachment.ContentDisposition.Inline = $True
$attachment.ContentDisposition.DispositionType = "Inline"
$attachment.ContentType.MediaType = "image/png"
$attachment.ContentId = $file.Name.ToString()
$mail.Attachments.Add($attachment)
I am getting this error -
Exception calling "Add" with "1" argument(s): "Value does not fall within the expected range."
At C:\work\Automated.ps1:130 char:23
+ $mail.Attachments.Add <<<< ($attachment)
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : ComMethodTargetInvocation
Can someone assist me on how to use inline images in outlook object.?
You will need to set the PR_ATTACH_CONTENT_ID property to the matching value of the cid attribute (Volume.png in your case):
$attach = $mail.Attachments.Add($attachment)
$attach.PropertyAccessor.SetProperty("http://schemas.microsoft.com/mapi/proptag/0x3712001F", "Volume.png")
Updated and Complete Answer incase if anyone needs :
$Text = "<br /><font face='Arial'><b><i>For Full Interactive Viewing <a
href=http://www.google.com>Click Here</a></i></b></font><br/>"
$MessageImages = "<br/><img src='C:\Users\E5559405\Desktop\IT\Image.jpg'/><br/>"
$FinalText = $Text+$MessageImages
$o = New-Object -ComObject Outlook.Application
$mail = $o.CreateItem(0)
$mail.importance = 2
$mail.subject = “Reports - Automated Email from user list “
$mail.HTMLBody = $FinalText
$mail.To = "xyz#gmail.com"
$mail.Send()
I'm using powershell to notify a high number of users about an expiration date of a document.
I have my script prepared
$smtpServer = "xxxxx.contoso.com"
$msg = new-object Net.Mail.MailMessage
$smtp = new-object Net.Mail.SmtpClient($smtpServer)
$msg.From = New-Object Net.Mail.mailaddress "xxxx#contoso.es", "xxx yyy zzz"
$msg.ReplyTo = "no-reply#contoso.es"
$msg.To.Add("xxx#contoso.es")
$msg.bcc.add($bcc)
$msg.subject = "Expiration notification"
$msg.body = I need to include HTML content, or MHT or bin as outlook message format.
$smtp.Send($msg)
But the email body was preformatted using outlook, so it contains images, preformated text etc. Which would be the best way to include that kind of content in the message body??
Thank you!
It should work if you add the Body as an html string and also add the line:
$msg.IsBodyHTML = true
I have a powershell script that embedds (not attaches) a picture and sends an email. The picture has increased now to 1500x5000 pixels and now I'm seeing that the pictures lenth gets compressed and it distorts the picture. How ever, when I manually insert the picture via outlook and send an email, it looks fine.
If i save the picture and then open it via paint or something, the picture opens fine. It just looks compressed in the email. Anyone know what may be going on there?
{
$Application = "C:\Autobatch\Spotfire.Dxp.Automation.ClientJobSender.exe"
$Arguments = "http://s.net:8070/spotfireautomation/JobExecutor.asmx C:\Autobatch\HourlyStats.xml"
$CommandLine = "{0} {1}" -f $Application,$Arguments
invoke-expression $CommandLine
$file = "C:\Autobatch\HourlyStats.png"
$smtpServer = "smtp.staom.sec.s.net"
$att = new-object Net.Mail.Attachment($file)
$att.ContentType.MediaType = “image/png”
$att.ContentId = “pict”
$att.TransferEncoding = [System.Net.Mime.TransferEncoding]::Base64
$msg = new-object Net.Mail.MailMessage
$smtp = new-object Net.Mail.SmtpClient($smtpServer)
$msg.Attachments.Add($att)
$msg.From = "d.k#s.com"
$msg.To.Add("r.p#p.com")
$msg.Subject = "Voice and Data Hourly Stats"
$msg.Body = "<p style=’font-family: Calibri, sans-serif’>
Voice and data hourly stats details<br />
</p>
<img src='cid:pict'/>"
$msg.IsBodyHTML = $true
$smtp.Send($msg)
$att.Dispose()
invoke-expression "DEL $file"
}
here is what the picture looks like in the email.
Try adding
$att.ContentDisposition.Inline = $true
I suspect some default behavior is happening under the covers and it's just not consistent between the script and Outlook.
More info here
It seems like your email client shrinks content to a certain maximum size. Try putting <img src='cid:pict'/> in a <div> environment:
<div style="overflow: scroll">
<img src='cid:pict'/>
</div>
Also, if you have any way to retrieve the actual pixel width of the image, you can try to set the CSS of the <img> tag accordingly.
By asking this I may sound like a noob, but Just out of Curiosity, if you have a manual way to send an email via Outlook, why not to make a script to send an automated email with desired screenshot?
IDK, if this might help you or not, but I had made this script long back, for my daily reporting purposes. Well, it fits the bill. Sharing it here, for your views on it.
#In this segment, I navigate IE to my specific destination, screen which I want to capture.
$ie = New-Object -ComObject InternetExplorer.Application
$ie.Visible = $true;
$Website = $ie.navigate('https://put.your.URL.here')
while($Website.Busy){Start-Sleep -Seconds 5}
#In this class, script captures the screen, once, all the data loading is over.
$file = "C:\Users\Desktop\$(Get-Date -Format dd-MM-yyyy-hhmm).bmp"
#P.S. I made it to save that screenshot with current date and time format. Also, default screenshot will be captured in .BMP format.
Add-Type -AssemblyName System.Windows.Forms
Add-type -AssemblyName System.Drawing
$Screen = [System.Windows.Forms.SystemInformation]::VirtualScreen
$width = $Screen.width
$Height = $Screen.Height
$Left = $Screen.Left
$Right = $Screen.Right
$Top = $Screen.Top
$Bottom = $Screen.Bottom
$bitmap = New-Object System.Drawing.Bitmap $width, $Height
$Graphics = [System.Drawing.Graphics]::FromImage($bitmap)
$Graphics.CopyFromScreen($Left, $Top, 0, 0, $bitmap.Size)
$bitmap.Save($File)
Write-Output "Screenshot saved to:"
Write-Output $File
sleep -Seconds 5
#Sending an Email
$Outlook = New-Object -ComObject Outlook.Application
$mail = $Outlook.CreateItem(0)
$mail.To = "your.designated#emailid.com"
$mail.Subject = "Outstanding data as on $(Get-Date -Format dd-MM-yyyy)"
$mail.Body = "PFA screenshot, of all outstanding formation as on $(Get-Date -Format dd-MM-yyyy-hhmm)"
$mail.Attachments.Add($file)
$mail.Send()
I am just answering this, since, I tried commenting above, but I guess, my reputation score is way too less to do that.
Hope this might be helpful for you to find a workaround.
Happy coding. :)
HTML code: is <img src='cid:pict'/> supposed to be <img src='cid:pict'> -just remove the forward slash?
Added: This link might help talking about embedding pic in email. base64 encoded images in email signatures. You can try generation base64 code and put it in email body HTML.