在电子邮件中嵌入图像并通过PowerShell发送

n8ghc7c1  于 2023-08-05  发布在  Shell
关注(0)|答案(3)|浏览(355)

我正在编辑我的一个旧脚本,以便向用户发送一封电子邮件,其中文本中嵌入了图像。我尝试使用Send-MailMessage函数来发送电子邮件,而不是使用旧的$smtp.send($msg)方法。但是,当尝试更新脚本时,图像不再被嵌入。
我知道如何将它们作为实际的附件附加到电子邮件中,但我不确定我做错了什么,让它们显示为实际的嵌入式图像。
注意:为了简洁,我删除了一些完整的电子邮件,因为它很大,只要我能得到一个或两个图像的工作,它将全部工作。

# force powershell to run as an x86 process
    Set-ExecutionPolicy -Scope CurrentUser Unrestricted
    if ($env:Processor_Architecture -ne "x86") {
        &"$env:windir\syswow64\windowspowershell\v1.0\powershell.exe" -file $myinvocation.Mycommand.path
        exit
    }

# initialize the script
    if ($startupvariables) { try {Remove-Variable -Name startupvariables  -Scope Global -ErrorAction SilentlyContinue } catch { } }
    New-Variable -force -name startupVariables -value ( Get-Variable | ForEach-Object { $_.Name } )
    [System.Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic') | Out-Null
    $Separator = ".", "@"

# advise what the script does
    Add-Type -AssemblyName PresentationCore,PresentationFramework
    $ButtonType = [System.Windows.MessageBoxButton]::OKCancel
    $MessageIcon = [System.Windows.MessageBoxImage]::Warning
    $MessageTitle = "Shared Drive Access Assistance"
    $MessageBody = "This script asks the user to provide more information regarding a network drive that they would like access to.`n`nTo use it, enter the below information:`n`n`n`tTicket Number`n`n`tUser's Email Address`n`n`tRequestor's Email Address`n`n`nIf this is the script you want to use, click OK.`nIf not, click Cancel."
    $Result = [System.Windows.MessageBox]::Show($MessageBody,$MessageTitle,$ButtonType,$MessageIcon)

    if ($Result -eq "Cancel")
    {
    Exit-PSSession
    }
    else
    {

# get the ticket number
    $Ticket = [Microsoft.VisualBasic.Interaction]::InputBox("Enter the SCTask ticket number" , "Ticket Number")

# get the user id via the email address
    $UserID = [Microsoft.VisualBasic.Interaction]::InputBox("Enter the user's email address" , "User Email Address")
    $User = $UserID.split($Separator)
    $Firstname = $User[0].substring(0,1).toupper()+$User[0].substring(1).tolower()
    $Lastname = $User[1].substring(0,1).toupper()+$User[1].substring(1).tolower()
    $User = $Firstname, $Lastname

# get local username
    $Username = [System.Environment]::UserName

# create email
    $subject = "Ticket $Ticket on Hold for User Response - Shared Drive Access for $User - Awaiting Additional Information"
    $body = @"
    <html>
    <body style="font-family:calibri"> 
    To $Requestor, $User,<br>
    <br>
    <br>
    In order to proceed with your request for shared drive access, we require the server name and full path to the folder you need access to. If you do not already know this information, you will need to provide these instructions to someone that already has access to the folder that you need access to.<br>
    <br>
    1)  Click the Start menu<br>
    <br>
    <img src="cid:image1.png"><br>
    <img src="cid:image2.png"><br>
    <img src="cid:image3.png"><br>
    <br>
    <br>
    2)  Navigate to "Computer"<br>
    <br>
    <img src="cid:image4.png"><br>
    <br>
    <br>

    <br>
    If you have any questions or need assistance with this process, please contact the Service Desk via one of the methods listed below. 
    <br>
    <br>
    Thank You,<br>
    <br>
    IT Service Desk<br>

    </body>
    </html>
"@

    $att1 = new-object Net.Mail.Attachment ("T:\PS Scripts\Images\shareddrive1.png")
    $att2 = new-object Net.Mail.Attachment ("T:\PS Scripts\Images\shareddrive2.png")
    $att3 = new-object Net.Mail.Attachment ("T:\PS Scripts\Images\shareddrive3.png")
    $att4 = new-object Net.Mail.Attachment ("T:\PS Scripts\Images\shareddrive4.png")
    $att1.ContentId = "image1.png"
    $att2.ContentId = "image2.png"
    $att3.ContentId = "image3.png"
    $att4.ContentId = "image4.png"
#    $msg.Attachments.Add($att1)
#    $msg.Attachments.Add($att2)
#    $msg.Attachments.Add($att3)
#    $msg.Attachments.Add($att4)

# create confirmation message
    $ButtonType = [System.Windows.MessageBoxButton]::YesNo
    $MessageIcon = [System.Windows.MessageBoxImage]::Warning
    $MessageTitle = "Shared Drive Access Assistance"
    $MessageBody = "The information you have entered is show below:`n`n`nTicket Number: $Ticket`n`nUser's Email Address: $UserID`n`nRequstor's Email Address: $RequestorID`n`n`nIf you would like to send the email, click Yes.`nOtherwise, click No."
    $Result = [System.Windows.MessageBox]::Show($MessageBody,$MessageTitle,$ButtonType,$MessageIcon)
    if ($Result -eq "No")
    {
    Exit-PSSession
    }
    else

# send email
    {
    Send-MailMessage -To "<$UserID>" -bcc "<$Username@dana.com>" -from "<itservicedesk@x.com>" -Subject $global:subject -SmtpServer "mailrelay.x.com" -BodyAsHtml -body $global:body
    }
    }

Function Clean-Memory {
    Get-Variable |
        Where-Object { $startupVariables -notcontains $_.Name } |
            ForEach-Object {
            try { Remove-Variable -Name "$($_.Name)" -Force -Scope "global" -ErrorAction SilentlyContinue -WarningAction SilentlyContinue}
                catch { }
 }
 }

字符串

polkgigr

polkgigr1#

因此,真实的的问题是如何将图像从附件嵌入到HTML文档中
CID又名内容ID将允许您附加图像,然后在文档中使用该附加图像。避免在内容ID名称中使用空格。

Send-MailMessage -To "Test@Test.com" -from "Test2@Test.com" -SmtpServer SMTP.TEST.NET -Subject "Hello" -BodyAsHtml -Body "<img src='cid:Test.png'>" -Port 25 -Attachments "C:\Users\Test\Test.png"

字符串
你在用

$att1 = new-object Net.Mail.Attachment ("T:\PS Scripts\Images\shareddrive1.png")
$att2 = new-object Net.Mail.Attachment ("T:\PS Scripts\Images\shareddrive2.png")
$att3 = new-object Net.Mail.Attachment ("T:\PS Scripts\Images\shareddrive3.png")
$att4 = new-object Net.Mail.Attachment ("T:\PS Scripts\Images\shareddrive4.png")
$att1.ContentId = "image1.png"
$att2.ContentId = "image2.png"
$att3.ContentId = "image3.png"
$att4.ContentId = "image4.png"


但是当你发送邮件时,你并没有附加那些附件

Send-MailMessage -To "<$UserID>" -bcc "<$Username@dana.com>" -from "<itservicedesk@x.com>" -Subject $global:subject -SmtpServer "mailrelay.x.com" -BodyAsHtml -body $global:body


您可以停止使用Net.Mail.Attachment,而是执行以下操作

$Body = @"
    <html>
        <body style="font-family:calibri"> 
            <b>This is image 1</b>
            <img src='cid:TEST1.png'>
            <b>This is image 2</b>
            <img src='cid:Test2.png'>
        </body>
    </html>
"@

Send-MailMessage -To "Test@Test.com" `
    -from "Test2@Test.com" `
    -SmtpServer Test.smtp.com `
    -Subject "Hello" `
    -BodyAsHtml -body $body `
    -Attachments "C:\Test\TEST1.png", "C:\Test\TEST2.png"

g6ll5ycj

g6ll5ycj2#

您可以将图像嵌入到HTML中,因此没有额外的文件。它正在取代

{img=file}

字符串
数据URL

{src="data:image/png;base64,[base64 encoded long string representing the image]}


有许多在线转换器可以将您的图像文件转换为所需的代码。
谷歌图像到数据URI转换器。

zkure5ic

zkure5ic3#

下面是一个使用MailKit的简单示例。我不得不从https://www.nuget.org/packages/MimeKithttps://www.nuget.org/packages/MailKit下载软件包,并使用7Zip解包,因为PowerShell正在努力从CLI安装。我从这里得到了一些想法,但想添加一个嵌入式图像https://adamtheautomator.com/powershell-email的示例。
你可以用MimeKit和MailKit做各种各样的事情,包括现代的Auth,这很棒。它也超级快,客户端甚至连接都可以在循环中使用,以发送大量消息。在不刷新的情况下使用连接的时间可能有一个上限?

$mailServer = "domain-com.mail.protection.outlook.com"

$SMTP = New-Object MailKit.Net.Smtp.SmtpClient

Add-Type -Path ".\mailkit.3.3.0\netstandard2.0\MailKit.dll"
Add-Type -Path ".\mimekit.3.3.0\netstandard2.0\MimeKit.dll"

$SMTP.Connect($mailServer, 25, [MailKit.Security.SecureSocketOptions]::StartTls, $False)

$Message  = New-Object MimeKit.MimeMessage
 
$message.From.Add("a.person@domain.com");
$message.To.Add("b.person@domain.com");
$message.Subject = "Some Subject";

$builder = [MimeKit.BodyBuilder]::new();

$image = $builder.LinkedResources.Add($path);
$image.ContentId = [MimeKit.Utils.MimeUtils]::GenerateMessageId();

$body = @"
    <html>
        <body style="font-family:calibri"> 
            <b>This is image 1</b>
            <img src='cid:$($image.ContentId)'>
        </body>
    </html>
"@

$builder.HtmlBody = $body

#Now we just need to set the message body and we're done
$message.Body = $builder.ToMessageBody();
$SMTP.Send($Message)

$SMTP.Disconnect($true)
$SMTP.Dispose()

字符串

相关问题