Thursday, October 17, 2019

Email files via PowerShell

# Email files
# Requires Powershell Version 5.1 or higher check with $PSVersionTable

$FolderTarget = '\\SomeFolder'
$FolderMove = "\\SomeFolder\Move"
$emailFrom = "from@domain.com"
$emailTo = "tosomeone@domain.com"
$emailSubjectPrefex = "Prefex note: "
$emailBodyPrefex = "Prefex Body: "
$smtpServerName = "smtp.domain.com"
$smtpServerPort = "25"

# Get files in Target Folder
$files = (get-childitem $FolderTarget)

# Loop through the list of files and send email
$files|ForEach-Object {
    # Select only PDF files
    if ($_.Extension -eq '.pdf') {
        $MessageHash = @{
                from        = $emailFrom
                to          = $emailTo
                subject     = $emailSubjectPrefex + $_.BaseName
                smtpserver  = $smtpServerName
                port        = $smtpServerPort
                attachments = $_.fullname
                body        = $emailBodyPrefex + $_.BaseName
            }
            Send-MailMessage $MessageHash
            # Move file to folder and add timestamp
            $ToFolder = $FolderMove + "\" + $_.BaseName + "-" `
                + $($(Get-Date -Format yymmddhhmmss-fff)) + ".pdf"
            Move-Item $_.FullName $ToFolder
    }
}

No comments:

Post a Comment