Skip to content

Instantly share code, notes, and snippets.

@nickadam
Created April 25, 2022 13:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nickadam/67b6851425b86d049f981552dd598a05 to your computer and use it in GitHub Desktop.
Save nickadam/67b6851425b86d049f981552dd598a05 to your computer and use it in GitHub Desktop.
Format raw data email message for sending attachments with AWS Send-SES2Email
function ConvertTo-RawDataEmail {
<#
.SYNOPSIS
Format an email message for AWS Send-SES2Email -Raw_Data
.DESCRIPTION
Accepts From, To, Cc, Bcc, Subject, Body, and Attachments, uses
System.Net.Mail to format the message into a byte array that
Send-SES2Email -Raw_Data can accept.
.PARAMETER From
[String] Sender's email address
.PARAMETER To
[String[]] Recipients' email addresses
.PARAMETER Cc
[String[]] Carbon copy addresses
.PARAMETER Bcc
[String[]] Blind carbon copy addresses
.PARAMETER Subject
[String] The subject line of the email
.PARAMETER Body
[String] The plain text body of the email
.PARAMETER Attachments
[String[]] The full paths to the attachments
.OUTPUTS
[Byte[]] A byte array of the formatted message
.NOTES
Author: Nick Vissari
.EXAMPLE
$RawData = ConvertTo-RawDataEmail -From "sender@example.com" -To "bob@example.com", "mary@example.com" -Subject "The files you wanted" -Body "Attached" -Attachments "C:\File1.txt", "C:\File2.txt"
Send-SES2Email -Raw_Data $RawData
#>
param(
[String]$From,
[String[]]$To,
[String[]]$Cc,
[String[]]$Bcc,
[String]$Subject,
[String]$Body,
[String[]]$Attachments
)
$Message = New-Object Net.Mail.MailMessage
$Message.From = $From
$Message.Subject = $Subject
$Message.Body = $Body
ForEach($Address in $To){
$Message.To.Add($Address)
}
ForEach($Address in $Cc){
$Message.Cc.Add($Address)
}
ForEach($Address in $Bcc){
$Message.Bcc.Add($Address)
}
ForEach($FilePath in $Attachments){
$Attachemnt = New-Object Net.Mail.Attachment($FilePath)
$Message.Attachments.Add($Attachemnt)
}
$Client = New-Object Net.Mail.SmtpClient
$Client.DeliveryMethod = "SpecifiedPickupDirectory"
$TempDir = [String](New-TemporaryFile)
Remove-Item $TempDir -Force
New-Item $TempDir -ItemType Directory | Out-Null
$Client.PickupDirectoryLocation = $TempDir
$Client.Send($Message)
ForEach($Item in (Get-ChildItem $TempDir)){
Get-Content $Item -AsByteStream
Remove-Item $Item -Force
}
Remove-Item $TempDir -Force
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment