Home > database >  Modify PowerShell script to attach not only .docx but also .html files
Modify PowerShell script to attach not only .docx but also .html files

Time:11-02

The script below uses Outlook to send emails with .docx attachments.

I would like to change the PowerShell script below to also add any .html files it finds, in addition to .docx files.

Any assistance in modifying this script is appreciated.

I would like to modify this PowerShell email script which uses Outlook so send an email with an attachment.

I want to include any .html files it also sees, in addition to the .docx file.

Thanks in advance to who may be able to assist me modify this.

 #SendEMail $SendTo $MailSubject $htmlOutput 
 # Check to see we have all the arguments
 If (Test-Path -Path "C:\Users\User1\Report\Report.html") {
 $FullPath=$args[0] 
 #Get an Outlook application object
 $o = New-Object -com Outlook.Application
 $mail = $o.CreateItem(0)
 #2 = High importance message
 $mail.importance = 1
 $mail.subject = "Report: $(get-date)"
 $mail.HTMLBody = "Report $(get-date)`n$(Get-Content 'C:\Users\User1\Report\Report.html' 
 | Out-String)"
 $mail.To = "[email protected]"
 # Iterate over all files and only add the ones that have an .docx extension
 $files = Get-ChildItem $FullPath
 for ($i=0; $i -lt $files.Count; $i  ) {
 $outfileName = $files[$i].FullName
 $outfileNameExtension = $files[$i].Extension
 # if the extension is the one we want, add to attachments
 if($outfileNameExtension -eq '.docx')
 {
 $mail.Attachments.Add($outfileName);
 }
 }
 $mail.Send()
 # give time to send the email
 Start-Sleep 5
 # quit Outlook
 $o.Quit()
 #end the script
 #exit
 }

CodePudding user response:

It is not clear if also files from any subdirectories should be attached or not, but here's code for both scenarios:

Scenario 1: Only files from $FullPath, not from any subdirectories

# Iterate over all files and only add the ones that have a .docx or .html extension
$files = Get-ChildItem -Path $FullPath -File | Where-Object { '.docx', '.html' -contains $_.Extension }
foreach ($file in $files) {
    $mail.Attachments.Add($file.FullName);
}

Scenario 2: All .docx and .html files from $FullPath AND its subdirectories

# Iterate over all files and only add the ones that have a .docx or .html extension
$files = Get-ChildItem -Path $FullPath -File -Recurse -Include '*.docx', '*.html'
foreach ($file in $files) {
    $mail.Attachments.Add($file.FullName);
}

After this, you can send the email.

Note To stop consuming memory, you should release the COM objects:

$o.Quit()
$null = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($mail)
$null = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($o)
$null = [System.GC]::Collect()
$null = [System.GC]::WaitForPendingFinalizers()
  • Related