Wednesday, August 12, 2009

Sending an email with asp

Sending email is a very common task in any web application

Sending email is a very common task in any
web application. In almost every web application (web site), their will at
least be an occasion to send email in any fashion. In classic ASP, we worked
with the CDONTS object to send emails from an ASP page. The SMTP Mail class in
ASP .NET provides properties and methods for sending messages using the
Collaboration Data Objects for Windows 2000 (CDOSYS) message component In this
article, we will see, how can we send email from an ASP .NET page. In a nut
shell, today, we will be looking into the following:




  • What we need to send Email
    from an ASP .NET?

  • How to send an email from
    an ASP .NET page?

  • What is new in sending
    email? (SmtpMail.SmtpServer)



What we need to send Email
from an ASP .NET?


The first thing that you need is the SMTP
service. SMTP service should be up and running. And you also need to import the
namespace, System.Web.Mail. To create a mail object, you need to create
an instance of MailMessage. MailMessage has all required properties such
as To, Subject, BCC, CC etc. For a complete list of method and properties, that
you can make use of, please visit



How to send an email from an
ASP .NET page?








<%@ Import Namespace="System.Web.Mail" %>



<html>



<script language="VB" runat="server">

Sub Page_Load(Sender As Object, E As EventArgs)



Dim msg as New MailMessage()



msg.To = "saurav@vb-tek.com"

msg.From = "abhi@vb-tek.com"

msg.Subject = "test"

'msg.BodyFormat = MailFormat.Html

msg.BodyFormat = MailFormat.Text

msg.Body = "hi"



SmtpMail.SmtpServer = "localhost"



SmtpMail.Send(msg)

msg = Nothing

lblMsg.Text = "An Email has been send to
" & "das@silicomm.com"



End Sub

</script>



<body style="font: 10pt verdana">

<form runat=server>

<asp:Label id=lblMsg runat=Server /> </form>

</body>

</html>






In the above example, we
start the coding by importing the namespace, "System.Web.Mail". Then,
in the Page_Load event, we create an instance of MailMessage object. It is
through the MailMessage object, we set all the properties such as To, From,
Subject, Body etc. We can either send a text message or a html message. We need
to specify the bodyformat in the BodyFormat property. One we set all the
properties, it is ready to send the email. Before sending the email, you have
to set another important property, ie; SmtpServer. You have to set this
property. You should assign the name of your SMTP server to this property. In
most cases you can assign this as "localhost". If you do not set this
property, then you will not be able to send email from an ASP .NET page.
Finally we send the email using SmtpMail.Send. This method expects the
MailMessage as an argument. Actually the method Send is overloaded. You can
also send an email by specifiying, SmtpMail.Send (From, To, subject, body).



0 comments:

Post a Comment