sarpay
11/28/2013 - 8:17 AM

[.net] [vb] Send email with attachment from memory stream

[.net] [vb] Send email with attachment from memory stream

Dim photoBase64 As String
Dim photoImgType As String 

' Prep photo attachment
Dim isImgJpeg As Integer = InStr(photoBase64, photoImgType)
Dim imgBytes As Byte() = Nothing
If isImgJpeg > 0 Then ' Attach this image
    ' Crop out section: "data:image/jpeg;base64,"
    ' Convert base64 to byte() to be placed in memory stream and attached to email
    imgBytes = Convert.FromBase64String(Mid(photoBase64, InStr(photoBase64, ",") + 1))
End If

' Send email
emailSent = MyEmailProvider.SendSupportEmail(toAddresses, "Product Support Inquiry", bodyText, imgBytes, "photo.jpg", photoImgType)



==============



Public Function SendSupportEmail( _
        ByVal toAddresses() As String, _
        ByVal subjectLine As String, _
        ByVal bodyText As StringBuilder, _
        ByVal attachedFileData As Byte(), _
        ByVal attachedFileName As String, _
        ByVal attachedMediaType As String _
    ) As Boolean

    SendSupportEmail = True
    Dim errorStr As String = "None"

    Try
        Dim mail As MailMessage = New MailMessage()

        Dim toAddressesStr As String = String.Empty
        For i As Integer = 0 To toAddresses.GetUpperBound(0)
            If toAddresses(i) IsNot String.Empty Then
                toAddressesStr &= toAddresses(i) & ","
            End If
        Next
        toAddressesStr = Mid(toAddressesStr, 1, toAddressesStr.Length - 1)
        mail.To.Add(toAddressesStr)

        mail.From = New MailAddress(ConfigurationManager.AppSettings("FROMNAME") & " <" & ConfigurationManager.AppSettings("FROMEMAIL") & ">")
        'Mail.From = New MailAddress(ConfigurationManager.AppSettings("FROMEMAIL"), ConfigurationManager.AppSettings("FROMNAME"))
        mail.Subject = subjectLine

        mail.Body = bodyText.ToString()
        mail.IsBodyHtml = True

        If attachedFileData IsNot Nothing And attachedFileName IsNot Nothing And attachedMediaType IsNot Nothing Then
            Dim ms As MemoryStream = New MemoryStream(attachedFileData)
            mail.Attachments.Add(New Attachment(ms, attachedFileName, attachedMediaType))
        End If

        Dim smtp As SmtpClient = New SmtpClient()
        smtp.Host = ConfigurationManager.AppSettings("SMTP").ToString()
        smtp.Port = CInt(ConfigurationManager.AppSettings("SMTPPORT"))
        smtp.Credentials = New NetworkCredential(ConfigurationManager.AppSettings("FROMEMAIL"), ConfigurationManager.AppSettings("FROMPWD"))
        'smtp.EnableSsl = True

        smtp.Send(mail)

    Catch ex As Exception
        SendSupportEmail = False
        errorStr = ex.ToString()

    End Try

    Return SendSupportEmail

End Function