Send e-mail with attachment from database image column (sql server 2k5)

Soooo...I needed to get files out of my SQL Server table (which has the files in an image column) and attach them to an email to send out.  I honestly thought this would be a no-brainer but turned out it was pretty finicky.  Anyway...the code to so is below just in case anyone is wondering.


     Partial Class _Default

         Inherits System.Web.UI.Page

     

         Function SendEmail()

     

             'Get your data (filename, content type, image column) from the db

     

             Dim dt As DataTable = GetYourStuff()

            If dt.Rows.Count <= 0 Then Return Nothing

    

            Dim msg As System.Net.Mail.MailMessage = New System.Net.Mail.MailMessage()

            msg.Subject = "Sample Message"

            msg.To.Add(New System.Net.Mail.MailAddress("Receiver@yourDomain.com"))

    

           Dim fromadx As New System.Net.Mail.MailAddress("Sender@yourDomain.com", "Sender Name")
           msg.From = fromadx

            msg.IsBodyHtml = False

            msg.Body = "Sample body..."

    

            Dim strMem As System.IO.MemoryStream = New System.IO.MemoryStream(CType(dt.Rows(0)("ImageColumn"), Byte()))

            Dim strWriter As System.IO.StreamWriter = New System.IO.StreamWriter(strMem)

    

            strWriter.Flush()

            'this is very important..wont work without it

            strMem.Position = 0

            'Filename and content type are hardcoded here, but I assume you get them from GetYourStuff() above

    

            Dim attachment As System.Net.Mail.Attachment = New System.Net.Mail.Attachment(strMem, "myFile.txt", "text/plain")

            msg.Attachments.Add(attachment)

    

            Dim smtpClient As System.Net.Mail.SmtpClient = New System.Net.Mail.SmtpClient(ConfigurationManager.AppSettings.Item("smtpserver"), 25)

            smtpClient.Send(msg)

   

        End Function

    End Class

 

kick it on DotNetKicks.com
  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Print | posted @ Thursday, January 31, 2008 4:44 PM

Twitter