I have a snippet of Powershell code that allows me to specify a filename and path to attach a file into my email I want to send. The code works fine, but I do not wish to use $fileNameAndPath and want to provide raw binary data (in combination with mime type, if applicable).
# Attach file and send SMTPMessage
$attachment = New-Object System.Net.Mail.Attachment($filenameAndPath)
$SMTPMessage.Attachments.Add($attachment)
$SMTPClient.Send($SMTPMessage)
Suppose binary data is stored in $binary, and the mime type is stored in $mimetype. How can pass or convert them so that I can make a System.Net.Mail.Attachment object? Can anyone help me with a snippet ?
CodePudding user response:
The Attachment
type has a constructor that takes a Stream
object - and you can construct a stream object from a [byte[]]
buffer with the MemoryStream
class:
$contentStream = New-Object System.IO.MemoryStream(,$binary)
$attachment = New-Object System.Net.Mail.Attachment($contentStream, "application/octet-stream")
CodePudding user response:
You can use the same class itself. System.Net.Mail.Attachment
class have multiple overloads for the constructors.
New-Object System.Net.Mail.Attachment($binary, $mimetype)
I assume that you need Attachment(String, String) which Initializes a new instance of the Attachment class with the specified content string and MIME type information and it has the following signature.
public Attachment (string fileName, string? mediaType);
If the content is in bytes you can refer @Mathias R. Jessen answer to construct the Attachment object.