Powershell – Send Mail Message with Multiple Attachments

I have a server where I create a certain type of files that I have to send by email on a daily basis to the same email receiver. Sending an email with Powershell is not complicated, just use Send-MailMessage. But since I had to do this a lot, I decided to create a function to do this job including a search window to find and attach the file.

I added the following function to my PowerShell profile:

#Send email with Attachment(s)
Function Send-CustomMailMessage
{
[System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms") | Out-Null
$FileLocation = New-Object System.Windows.Forms.OpenFileDialog
$FileLocation.initialDirectory = 'd:\' #Or any other location
$FileLocation.Multiselect = $true
$Dialog = $FileLocation.ShowDialog()
If ($Dialog -eq 'Cancel')
{
	Return #End Function
}
Else
{
$fileNames = $FileLocation.filename
$email = New-Object System.Net.Mail.MailMessage
$email.From = 'from_email_address'
$email.To.Add('to_email_address')
$email.Subject = 'Subject Text'
$email.Body = 'Body Text'
Foreach ($fileName in $fileNames)
{
$emailAttach = New-Object System.Net.Mail.Attachment $fileName
$email.Attachments.Add($emailAttach)
}
$smtp = new-object Net.Mail.SmtpClient
$smtp.host = 'smtp_host'
$smtp.Send($email)
}
}

Now I just have to type “Send-CustomMailMessage”, browse to the file(s) and press <<OK>> to send the file to it’s destination.

Leave a Reply

  

  

  


(Required)