Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I attach varbinary(max) data from SQL to my SMTPMessage in powershell?

I have a varbinary(max) column in my SQL server containing binary that looks like the following:

  0x255044462D312E340D0A25E2E3CFD30D...

I want to retrieve this value in a powershell so that I can run logic that sends out an email.

#Get the attachment binary into a variable from sql server
$Query = "SELECT AttachmentBinary FROM [dbo].MyFiles"
$e= Invoke-Sqlcmd -Query $Query -ServerInstance $server (etc.etc.)

Running $e.Attachmentbinary in powershell gives me a list of decimal numbers, which I assume is how powershell displays the binary:

37
80
68
70
45
(and so on)

The problem now is that when I prepare the file and send the email..

$contentStream = New-Object System.IO.MemoryStream(,$e.Attachmentbinary)
$MailAttachment = New-Object System.Net.Mail.Attachment($contentStream, "application/pdf")
$SMTPMessage.Attachments.Add($MailAttachment)

.. It leaves sends me a 1kb file. That is to say,

$e.AttachmentBinary.Length #Returns 1024 for some reason..

I know for sure the binary data in the database is correct. The problem seems to be in the second part when adding the attachment.

How can this be corrected?

like image 622
Erechtheus Avatar asked Mar 17 '26 04:03

Erechtheus


1 Answers

The Invoke-Sqlcmd needs a -MaxBinaryLength value, as the default size of 1024 (1KB) may be to small for the varbinary.

The resulting array $e.Attachmentbinary needs to be cast to binary explicitly, as @Theo suggested.

[Byte[]]$e.Attachmentbinary
like image 146
Erechtheus Avatar answered Mar 22 '26 15:03

Erechtheus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!