Thursday 16 August 2012

Sending e-mails with attachments using ASP.NET

Public Shared Sub SendEmail
(ByVal recipientToCsv As String, 
ByVal subject As String, 
ByVal body As String,
Optional ByVal isHtml As Boolean = True, 
Optional ByVal recipientCCCsv As String = "", 
Optional ByVal recipientBCCCsv As String = "", 
Optional ByVal Attachment1_Stream As Stream = Nothing, 
Optional ByVal Attachment1_filename As String = "")

'Create the email object
Dim newEmail As New MailMessage()

' From
newEmail.From = New MailAddress(System.Configuration.ConfigurationManager.AppSettings.Item("AppMailboxAddress"), System.Configuration.ConfigurationManager.AppSettings.Item("AppMailboxAddressName"))

' To
If String.IsNullOrEmpty(recipientToCsv) Then
recipientToCsv = System.Configuration.ConfigurationManager.AppSettings.Item("AppMailboxAddress")
End If
newEmail.To.Add(recipientToCsv)

' CC
If Trim(recipientCCCsv) <> "" Then newEmail.CC.Add(recipientCCCsv)
If Trim(System.Configuration.ConfigurationManager.AppSettings.Item("CCMailboxAddress")) <> "" Then newEmail.CC.Add(System.Configuration.ConfigurationManager.AppSettings.Item("CCMailboxAddress"))

' BCC
If Trim(recipientBCCCsv) <> "" Then newEmail.Bcc.Add(recipientBCCCsv)
If Trim(System.Configuration.ConfigurationManager.AppSettings.Item("BCCMailboxAddress")) <> "" Then newEmail.Bcc.Add(System.Configuration.ConfigurationManager.AppSettings.Item("BCCMailboxAddress"))

' Subject
newEmail.Subject = subject

' Body
newEmail.IsBodyHtml = isHtml
newEmail.Body = body

' Attachment
If Not IsNothing(Attachment1_Stream) Then
   Dim Attachment1 As Attachment = New Attachment(Attachment1_Stream, Attachment1_filename)
   newEmail.Attachments.Add(Attachment1)
End If

'Send the email
Dim smtp As New SmtpClient
smtp.Send(newEmail)

End Sub

No comments:

Post a Comment