DeveloperBarn Forums

DeveloperBarn

Programming & IT forum

Sending Emails Using ASP.NET

This is a discussion on Sending Emails Using ASP.NET within the .Net Code Samples forums, part of the .Net Development category; This code sample is to show how to send emails in ASP.NET. Obviously there's lots more you can do, such ...

Go Back   DeveloperBarn Forums > Programming & Scripting > .Net Development > .Net Code Samples

  1 links from elsewhere to this Post. Click to view. #1  
Old March 23rd, 2008, 07:20 AM
richyrich's Avatar
Administrator
 
Join Date: Mar 2008
Real name: Rich
Location: Somewhere only we know...
Posts: 1,347
Blog Entries: 6
Rep Power: 8
richyrich is a name known to allrichyrich is a name known to allrichyrich is a name known to allrichyrich is a name known to allrichyrich is a name known to allrichyrich is a name known to all
Default Sending Emails Using ASP.NET

This code sample is to show how to send emails in ASP.NET. Obviously there's lots more you can do, such as add attachments, read receipts etc. I'll add different code samples for these type of events.

Main Page
Code:
<%@ Page Language="VB" AutoEventWireup="true" CodeFile="Default.aspx.vb" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN""http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="XHTML namespace">
<head runat="server">
<title>Sending Email using ASP.Net</title>
</head>
<body>
<form id="form1" runat="server">
<asp:Label ID="lbl_response" runat="server"/><br/>
<br/>
To:
<asp:TextBox ID="txt_to" runat="server"/><br/>
cc:
<asp:TextBox ID="txt_cc" runat="server"/><br/>
bcc:
<asp:TextBox ID="txt_bcc" runat="server"/><br/>
Subject:
<asp:TextBox ID="txt_subject" runat="server"/><br/>
<br/>
Message:<br/>
<asp:TextBox ID="txt_mess" runat="server" TextMode="MultiLine"/><br/>
<br/>
<asp:Button ID="but_send" runat="server" Text="Send"/>
</form>
</body>
</html>
Code Behind
Code:
'import the net.mail namespace
Imports System.Net.Mail
 
Partial Class _Default
Inherits System.Web.UI.Page
Protected Sub but_send_Click(ByVal sender AsObject, ByVal e As System.EventArgs) Handles but_send.Click
 
'create smtp instance
Dim smtp As New SmtpClient
 
'set the delivery method. We're using an external smtp server
smtp.DeliveryMethod = SmtpDeliveryMethod.Network
 
'set the port the smtp server allows access on
smtp.Port = 25
 
'set the name of the smtp server to use
smtp.Host = "smtp.domain.com"
 
'create mail message instance
Dim myMail As New MailMessage()
 
'stringbuilder for building message body
Dim mail_body As New StringBuilder
 
'create html email body
mail_body.Append("<!DOCTYPE HTML PUBLIC ""-//W3C//DTD HTML 4.0 Transitional//EN"">")
mail_body.Append("<html>")
mail_body.Append("<head>")
mail_body.Append("<title>Send Email</title>")
mail_body.Append("<style type=""text/css"">")
mail_body.Append(".dblue8 { font-family:arial; color: #000066; font-size: 8pt }")
mail_body.Append("</style>")
mail_body.Append("</head>")
mail_body.Append("<body class=""dblue8"">")
'add in text from message box as the body
mail_body.Append(txt_mess.Text)
mail_body.Append("</body>")
mail_body.Append("</html>")
 
'create a variable to hold any error message
Dim err_mess As String = String.Empty
 
'create a try...catch area for creating the email and catching any errors
 Try
 
    'create instance of a mail address for the To address
    Dim mail_to As MailAddress
 
    'for multiple email addresses, split the email address by ;
    Dim arr_email As Array = Split(txt_to.Text, ";")
    'create a temp string to hold each email address in the to box
    Dim email_to As String
 
    'iterate through all the email addresses in the email array
         For Each email_to In arr_email
 
             'convert txt_to email to a mail address and set to variable
             mail_to = New MailAddress(Trim(email_to))
             'add the mail address to the .to property of the mail message
             myMail.To.Add(mail_to)
 
         Next
 
     'check if cc text box is empty
         If Not txt_cc.Text = String.Empty Then
             'txt_cc is not empty so need to add cc email addresses to cc property
             'create instance of a mail address for the cc address
             Dim mail_cc As MailAddress
             'for multiple email addresses, split the cc email addresses by ;
             'can use the same array instance as we used for the to addresses
             arr_email = Split(txt_cc.Text, ";")
             'create a temp string to hold each email address in the cc box
             Dim email_cc As String
             'iterate through all the email addresses in the email array
                  For Each email_cc In arr_email
                        'convert txt_to email to a mail address and set to variable
                        mail_cc = New MailAddress(Trim(email_cc))
                        'add the mail address to the .cc property of the mail message
                        myMail.CC.Add(mail_cc)
                  Next
         End If
 
     'check if bcc text box is empty
         If Not txt_bcc.Text = String.Empty Then
             'txt_bcc is not empty so need to add bcc email addresses to bcc property
             'create instance of a mail address for the bcc address
             Dim mail_bcc As MailAddress
             'for multiple email addresses, split the bcc email addresses by ;
             'can use the same array instance as we used for the to addresses
             arr_email = Split(txt_bcc.Text, ";")
             'create a temp string to hold each email address in the bcc box
             Dim email_bcc As String
             'iterate through all the email addresses in the email array
                 For Each email_bcc In arr_email
                     'convert txt_to email to a mail address and set to variable
                     mail_bcc = New MailAddress(Trim(email_bcc))
                     'add the mail address to the .bcc property of the mail message
                     myMail.Bcc.Add(mail_bcc)
                 Next
          End If
 
    'add your email as the .from property of the mail message
    myMail.From = New MailAddress("youremail@domain.com")
 
    'set the .subject property of the mail message to the value in the txt_subject box
    myMail.Subject = txt_subject.Text
 
    'set the body of the email to HTML. Set to False if you want Plain Text
    myMail.IsBodyHtml = True
 
    'set the .body property of the mail message to the email we created above
    myMail.Body = mail_body.ToString
 
    'send the email
    smtp.Send(myMail)
 
 Catch ex As Exception
         err_mess = ex.Message.ToString
 
 Finally
         myMail.Dispose()
 
 End Try
 
 If err_mess = String.Empty Then
          lbl_response.Text = "Your email has been sent"
 Else
          lbl_response.Text = err_mess
 End If
 
End Sub
 
End Class

Last edited by richyrich; April 2nd, 2008 at 09:19 AM.
Reply With Quote
  #2  
Old July 4th, 2009, 07:43 AM
micky's Avatar
Lazy Bum
 
Join Date: Jul 2008
Location: India
Posts: 566
Rep Power: 4
micky has a spectacular aura aboutmicky has a spectacular aura aboutmicky has a spectacular aura about
Default

Hey RR
Have you checked this code when you have more than 1 email address in TO field?

I did and it shows all email addresses in TO field.
I thought it happened with Async method only.

Any pointers??
__________________
Get the Mantra!
Reply With Quote
  #3  
Old July 4th, 2009, 09:08 AM
richyrich's Avatar
Administrator
 
Join Date: Mar 2008
Real name: Rich
Location: Somewhere only we know...
Posts: 1,347
Blog Entries: 6
Rep Power: 8
richyrich is a name known to allrichyrich is a name known to allrichyrich is a name known to allrichyrich is a name known to allrichyrich is a name known to allrichyrich is a name known to all
Default

Quote:
Originally Posted by micky View Post
Hey RR
Have you checked this code when you have more than 1 email address in TO field?

I did and it shows all email addresses in TO field.
I thought it happened with Async method only.

Any pointers??
This particular code sample adds them all to the To: field...
Reply With Quote
  #4  
Old July 6th, 2009, 03:21 AM
micky's Avatar
Lazy Bum
 
Join Date: Jul 2008
Location: India
Posts: 566
Rep Power: 4
micky has a spectacular aura aboutmicky has a spectacular aura aboutmicky has a spectacular aura about
Default

Quote:
Originally Posted by richyrich View Post
This particular code sample adds them all to the To: field...
ok, let me see if i can send them separately!
Reply With Quote
  #5  
Old July 6th, 2009, 04:07 AM
richyrich's Avatar
Administrator
 
Join Date: Mar 2008
Real name: Rich
Location: Somewhere only we know...
Posts: 1,347
Blog Entries: 6
Rep Power: 8
richyrich is a name known to allrichyrich is a name known to allrichyrich is a name known to allrichyrich is a name known to allrichyrich is a name known to allrichyrich is a name known to all
Default

I think it was my own confusion micky....I think some original code I had in classic ASP sent an email to each person, but when I wrote the .NET code, I sent the same email to everyone...
Reply With Quote
  #6  
Old July 6th, 2009, 04:21 AM
micky's Avatar
Lazy Bum
 
Join Date: Jul 2008
Location: India
Posts: 566
Rep Power: 4
micky has a spectacular aura aboutmicky has a spectacular aura aboutmicky has a spectacular aura about
Default

Actually RR, i think this system.net.mail component behaves nonsensely
If i use such code
Code:
        Dim arr_email_to As Array = Split(emails, ";")
        Dim SmtpMail As New SmtpClient(ConfigurationManager.AppSettings("SmtpServer"), 25)
        Dim myMail As New MailMessage()

        myMail.From = New MailAddress(ConfigurationManager.AppSettings("NoReply"))
        myMail.Body = "Update"
        myMail.Subject = "Update"

        For Each email_to As String In arr_email_to

            myMail.To.Add(New MailAddress(email_to))
            SmtpMail.Send(myMail)
        Next
It sends different number of mails and with different number of emails in TO field.

When i do this, then it sends correct mails.
But i wonder if its a good way, as i have to define everything every time in loop.
Code:
        Dim arr_email_to As Array = Split(emails, ";")

        For Each email_to As String In arr_email_to
            Dim SmtpMail As New SmtpClient(ConfigurationManager.AppSettings("SmtpServer"), 25)
            Dim myMail As New MailMessage()

            myMail.From = New MailAddress(ConfigurationManager.AppSettings("NoReply"))
            myMail.Body = "Update for your match"
            myMail.Subject = "Match Update"

            myMail.To.Add(New MailAddress(email_to))
            SmtpMail.Send(myMail)
        Next
Reply With Quote
Reply

  DeveloperBarn Forums > Programming & Scripting > .Net Development > .Net Code Samples

Bookmarks

Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On


LinkBacks (?)

LinkBack to this Thread: http://www.developerbarn.com/net-code-samples/57-sending-emails-using-asp-net.html

Posted By For Type Date
PolicyCheck - | Pensions | Investments | Savings | Advice This thread Refback April 2nd, 2008 09:31 AM

Similar Threads

Thread Thread Starter Forum Replies Last Post
Sending Email with ASP and CDOSYS jmurrayhead ASP Code Samples 1 November 13th, 2008 09:26 AM
windows service send emails every 10 days peebman2000 .Net Development 8 May 20th, 2008 04:00 PM
Sending Email using CDOSYS & Classic ASP richyrich ASP Code Samples 0 March 17th, 2008 09:52 AM


All times are GMT -4. The time now is 06:45 PM.


Copyright ©2008-2010, DeveloperBarn

Content Relevant URLs by vBSEO 3.3.2