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 sb.Append(str) Loop 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 sReader.Close() sReader.Dispose() fs.Close() fs.Dispose() Dim objMailMessage As New MailMessage Dim objSMTP As New SmtpClient Dim toAddress As New MailAddress("ToEmailAddress", "ToEmailName") objMailMessage.To.Add(toAddress) 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")) Try objSMTP.Host = strMailServer objSMTP.Send(objMailMessage) Catch ex As Exception Throw ex End Try <pre>
This entry was posted on December 12, 2011 at 9:32 PM and is filed under ASP.NET, asp.net feature. Tagged: Attachment, Attachment Using A Memory Stream, Memory Stream, Send Email, Send Email Attachment Using A Memory Stream, Send Email using C#. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.