Submitted By: Edmond Deuser

Email an attachment in VB.NET, using settings found in the Web.config file.

Visual Basic
Edit|Remove
'Author: Edmond Deuser
'Date: 01/11/2006
'desc:   Desc: script emails a text file or other attachment to a specified 
'        email.  All settings are set in the web.config file.
'
'**You must use the following imports to use this script.**
Imports System.IO
Imports System.Configuration
Imports System.Web.Mail
Public Sub EmailErrorLog(ByVal strMessage As String, Optional ByVal isReport As Boolean = False)
   Dim mail As New MailMessage  'set up a new mail message
   Dim attach As MailAttachment 'create a holder for a mail attachment
   Dim oFile As File            'File object to check our attachment
   'smtp server to use ex: can be dns or ip
   SmtpMail.SmtpServer = ConfigurationSettings.AppSettings("MailServer")
   mail.From = ConfigurationSettings.AppSettings("FromEmail")
   If (ConfigurationSettings.AppSettings("Test") = "true") Then
      'Send all email to Technical Contact if test
      mail.To = ConfigurationSettings.AppSettings("TechnicalContact")
      If isReport Then
         If oFile.Exists(ConfigurationSettings.AppSettings("Attachment")) Then
            attach = New MailAttachment(ConfigurationSettings.AppSettings("Attachment"))
            mail.Attachments.Add(attach)
         End If
         mail.Subject = "Email Subject"
         mail.BodyFormat = MailFormat.Text
         mail.Body = strMessage
         SmtpMail.Send(mail)
         attach = Nothing
         mail = Nothing
      Else
         mail.Subject = "Email Subject"
         mail.BodyFormat = MailFormat.Text
         mail.Body = strMessage
         SmtpMail.Send(mail)
         mail = Nothing
      End If
   Else
      If isReport Then
         mail.To = ConfigurationSettings.AppSettings("ToList")
         If oFile.Exists(ConfigurationSettings.AppSettings("Attachment")) Then
            attach = New MailAttachment(ConfigurationSettings.AppSettings("Attachment"))
            mail.Attachments.Add(attach)
         End If
         mail.Subject = "Email Subject"
         mail.BodyFormat = MailFormat.Text
         mail.Body = strMessage
         SmtpMail.Send(mail)
         attach = Nothing
         mail = Nothing
      Else
         mail.To = ConfigurationSettings.AppSettings("Helpdesk")
         mail.Subject = "Email Subject"
         mail.BodyFormat = MailFormat.Text
         mail.Body = strMessage
         SmtpMail.Send(mail)
         mail = Nothing
      End If
   End If
End Sub