VB.net code send attachment(.csv file) in email where the attachement is done as an in-memory operation

Posted by Rajnilari2015 under VB.NET category on | Points: 40 | Views : 110
The below code will do so

Public Shared Sub SendEmailWithAttachment(sb As StringBuilder, smptTuple As Tuple(Of String, Integer, String, String), emailInfoTuple As Tuple(Of String, String, String, String, String, String))
Dim smptHost As String = smptTuple.Item1
Dim smptPort As Integer = smptTuple.Item2
Dim smptUser As String = smptTuple.Item3
Dim smptPassword As String = smptTuple.Item4
Dim fromEmailAddress As String = emailInfoTuple.Item1
Dim toEmailAddress As String = emailInfoTuple.Item2
Dim ccEmailAddress As String = emailInfoTuple.Item3
Dim subject As String = emailInfoTuple.Item4
Dim body As String = emailInfoTuple.Item5
Dim attachmentName As String = emailInfoTuple.Item6

Using stream As New MemoryStream(Encoding.ASCII.GetBytes(sb.ToString()))
Dim mailMsg As New MailMessage()
Dim emailAddress As New MailAddress(toEmailAddress)

For Each address As var In ccEmailAddress.Split(New () {","}, StringSplitOptions.RemoveEmptyEntries)

mailMsg.From = New MailAddress(fromEmailAddress)

'Add a new attachment to the E-mail message, using the correct MIME type
Dim attachment As New Attachment(stream, New ContentType("text/csv"))
attachment.Name = attachmentName

mailMsg.Subject = subject
mailMsg.Body = body
mailMsg.IsBodyHtml = True

' Init SmtpClient
Dim smtpClient As New SmtpClient(smptHost, smptPort)
smtpClient.EnableSsl = False
Dim credentials As New System.Net.NetworkCredential(smptUser, smptPassword)
smtpClient.Credentials = credentials

'send email
End Using
Catch ex As Exception
Throw ex
End Try
End Sub

Comments or Responses

Login to post response