Mainly we send attachment as a file which is already in the server and take that physical file, 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 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
Like this we are not storing any file in server and send mail as a txt file as a attachment. like this we are also saving server space also...
Tags: attachment, Attachment using Memory Stream, Memory Stream, Send Email, Send Email Attachment using a Memory Stream, Send Email using C#, .Net