Thursday, July 9, 2009

SendingMails

Protected Sub btnSend_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSend.Click

    'Create instance of main mail message class.
    Dim mailMessage As System.Net.Mail.MailMessage = New System.Net.Mail.MailMessage()

    'Configure mail mesage
    'Set the From address with user input
    '    mailMessage.From = New System.Net.Mail.MailAddress(txtFromAddress.Text.Trim())
    'Get From address in web.config
    mailMessage.From = New System.Net.Mail.MailAddress(System.Configuration.ConfigurationManager.AppSettings("fromEmailAddress"))
    'Another option is the "from" attirbute in the <smtp> element in the web.config.

    'Set additinal addresses
    mailMessage.To.Add(New System.Net.Mail.MailAddress(txtToAddress.Text.Trim()))
    'mailMessage.CC
    'mailMessage.Bcc
    'mailMessage.ReplyTo

    'Set additional options
    mailMessage.Priority = Net.Mail.MailPriority.High
    'Text/HTML
    mailMessage.IsBodyHtml = False

    'Set the subjet and body text
    mailMessage.Subject = txtSubject.Text.Trim()
    mailMessage.Body = txtBody.Text.Trim()

    'Add one to many attachments
    'mailMessage.Attachments.Add(New System.Net.Mail.Attachment("c:\temp.txt")

    'Create an instance of the SmtpClient class for sending the email
    Dim smtpClient As System.Net.Mail.SmtpClient = New System.Net.Mail.SmtpClient()

    'Use a Try/Catch block to trap sending errors
    'Especially useful when looping through multiple sends
    Try
      smtpClient.Send(mailMessage)
    Catch smtpExc As System.Net.Mail.SmtpException
      'Log error information on which email failed.
    Catch ex As Exception
      'Log general errors
    End Try

  End Sub


and in Web.Config

<appSettings>
    <add key="fromEmailAddress" value="YOUR EMAIL ADDRESS HERE"/>
  </appSettings>


<!--Mail settings-->
  <system.net>
    <mailSettings>
      <smtp>
        <network host="YOUR HOST HERE"/>
      </smtp>
    </mailSettings>
  </system.net>
  <!--Mail settings-->


Source ASP.NET Videos

No comments:

Post a Comment