Code Simplified – Viral Sarvaiya

Code Simplified – Viral Sarvaiya, Web Developer Friends, dot net Developer, Sql Server Developer

Send Email Attachment Using A Memory Stream

Posted by Viral Sarvaiya on December 12, 2011

mainly we send attachment as a file which is already in the server, but from memory stream we can also send as a attachment in email, below is code for that,

Dim strMailServer As String = "SMTPServerName"

Dim fs As New FileStream("FilePath\FileName.txt", FileMode.Open, FileAccess.Read, FileShare.ReadWrite)

Dim sReader As New StreamReader(fs)

Dim objMemoryStream As New MemoryStream()

Dim sb As New System.Text.StringBuilder("")
Dim str As String

'--read through template form, replace variables and add lines to string builder

Do While sReader.Peek() >= 0

str = sReader.ReadLine()

'--replace [Date_Time]
'Replace string here



Dim Encoding As New UTF8Encoding

Dim arrByt() As Byte = Encoding.GetBytes(sb.ToString())

objMemoryStream.Write(arrByt, 0, arrByt.Length)

objMemoryStream.Position = 0

'--release file system resources





Dim objMailMessage As New MailMessage

Dim objSMTP As New SmtpClient

Dim toAddress As New MailAddress("ToEmailAddress", "ToEmailName")


Dim fromAddress As New MailAddress("FromEmailAddress", "FromEmailName")

objMailMessage.From = fromAddress

objMailMessage.IsBodyHtml = False
objMailMessage.Priority = MailPriority.Normal

objMailMessage.Subject = "EmailSubject"

objMailMessage.Body = "Email Body"

' add fax cover page as first file attachment

objMailMessage.Attachments.Add(New Attachment(objMemoryStream, "FileName.txt"))


objSMTP.Host = strMailServer


Catch ex As Exception

Throw ex

End Try



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: