Created
September 27, 2025 11:13
-
-
Save obar1/f8a27596609562c8e9ee3e5f7def6679 to your computer and use it in GitHub Desktop.
send pdf via mail
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 = '[email protected]' | |
$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() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
thanks chagpt5