在 Powershell 中,我試圖從一個大文本字串創建一個 zip 檔案,將其附加到電子郵件中,然后發送。訣竅是我需要在不使用本地存盤或磁盤資源的情況下執行此操作,而是在記憶體中創建結構。
我有兩塊卡住了。
- 我在下面采取的步驟不會將任何內容寫入 zip 變數或其條目。
- 完成后如何將 zip 附加到電子郵件中?
因為我無法通過創建 zip 的第一個問題,所以我無法嘗試將 zip 附加到電子郵件中。
$strTextToZip = '<html><head><title>Log report</title></head><body><p>Paragraph</p><ul><li>first</li><li>second</li></ul></body></html>'
Add-Type -Assembly 'System.IO.Compression'
Add-Type -Assembly 'System.IO.Compression.FileSystem'
# step 1 - create the memorystream for the zip archive
$memoryStream = New-Object System.IO.Memorystream
$zipArchive = New-Object System.IO.Compression.ZipArchive($memoryStream, [System.IO.Compression.ZipArchiveMode]::Create, $true)
# step 2 - create the zip archive's entry for the log file and open it for writing
$htmlFile = $zipArchive.CreateEntry("log.html", 0)
$entryStream = $htmlFile.Open()
# step 3 - write the HTML file to the zip archive entry
$fileStream = [System.IO.StreamWriter]::new( $entryStream )
$fileStream.Write( $strTextToZip )
$fileStream.close()
# step 4 - create mail message
$msg = New-Object Net.Mail.MailMessage($smtp['from'], $smtp['to'], $smtp['subject'], $smtp['body'])
$msg.IsBodyHTML = $true
# step 5 - add attachment
$attachment = New-Object Net.Mail.Attachment $memoryStream, "application/zip"
$msg.Attachments.Add($attachment)
# step 6 - send email
$smtpClient = New-Object Net.Mail.SmtpClient($smtp['server'])
$smtpClient.Send($msg)
條目的步驟 3 中的流式傳輸不會填充該變數。此外,一旦成功填充,我不確定如何關閉流并保持內容可用于電子郵件附件。最后,我認為Add第Net.Mail.Attachment5 步中的 zip 應該成功地將 zip 復制到訊息中,但這里也歡迎任何指標。
uj5u.com熱心網友回復:
為了至少對第一項提供適當的指導,如何在沒有檔案的情況下在記憶體中創建 Zip。你已經很接近了,這就是它的完成方式,舊版本
現在試圖回答第二個問題,這是基于一種預感,我認為你的邏輯已經很合理了,Attachment類有一個.ctor支持流的類,Attachment(Stream, ContentType)所以我覺得這應該可以正常作業,盡管我不能親自測驗它:
$msg = [MailMessage]::new($smtp['from'], $smtp['to'], $smtp['subject'], $smtp['body'])
$msg.IsBodyHTML = $true
# EDIT:
# Based on OP's comments, this is the correct order to follow
# first Flush()
$memStream.Flush()
# then
$memStream.Position = 0
# now we can attach the memstream
# Use `Attachment(Stream, String, String)` ctor instead
# so you can give it a name
$msg.Attachments.Add([Attachment]::new(
$memStream,
'nameyourziphere.zip',
[ContentType]::new('application/zip')
))
$memStream.Close() # I think you can close here then send
$smtpClient = [SmtpClient]::new($smtp['server'])
$smtpClient.EnableSsl = $true
$smtpClient.Send($msg)
$msg, $smtpClient | ForEach-Object Dispose
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/529127.html
