Skip to content

Instantly share code, notes, and snippets.

@obar1
Created September 27, 2025 11:13
Show Gist options
  • Select an option

  • Save obar1/f8a27596609562c8e9ee3e5f7def6679 to your computer and use it in GitHub Desktop.

Select an option

Save obar1/f8a27596609562c8e9ee3e5f7def6679 to your computer and use it in GitHub Desktop.
send pdf via mail
# Send all PDFs in the current folder via Outlook
# Save as: Send-PDFs.ps1, then run it from the folder containing the PDFs.
Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'
$recipient = 'mamatucci@gmail.com'
$subject = "PDFs $(Get-Date -Format 'yyyy-MM-dd HH:mm')"
$body = "Hi,`r`n`r`nPlease find attached all PDF files from: $(Get-Location).`r`n`r`nSent automatically via PowerShell.`r`n"
# 1) Collect PDFs in current folder (force array even for 0 or 1 item)
$pdfs = @(Get-ChildItem -Path (Get-Location) -Filter *.pdf -File)
if ($pdfs.Count -eq 0) {
Write-Host "No PDF files found in $(Get-Location). Nothing to send." -ForegroundColor Yellow
exit 0
}
# 2) Start or attach to Outlook
try {
$outlook = [Runtime.InteropServices.Marshal]::GetActiveObject('Outlook.Application')
} catch {
$outlook = New-Object -ComObject Outlook.Application
}
# 3) Ensure a MAPI session (uses default Outlook profile)
$namespace = $outlook.GetNamespace('MAPI')
$namespace.Logon()
# 4) Create the email
$mail = $outlook.CreateItem(0) # 0 = olMailItem
$mail.To = $recipient
$mail.Subject = $subject
$mail.Body = $body
# 5) Attach all PDFs
foreach ($pdf in $pdfs) {
$null = $mail.Attachments.Add($pdf.FullName)
}
# 6) Send (or use .Display() if you want to review first)
$mail.Send()
Write-Host "Email sent to $recipient with $($pdfs.Count) PDF attachment(s)." -ForegroundColor Green
# 7) Cleanup COM objects
try { [void][System.Runtime.InteropServices.Marshal]::ReleaseComObject($mail) } catch {}
try { [void][System.Runtime.InteropServices.Marshal]::ReleaseComObject($namespace) } catch {}
try { [void][System.Runtime.InteropServices.Marshal]::ReleaseComObject($outlook) } catch {}
[GC]::Collect()
[GC]::WaitForPendingFinalizers()
@obar1
Copy link
Copy Markdown
Author

obar1 commented Sep 27, 2025

thanks chagpt5

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment