Thursday, July 19, 2007

Sending email using C# -- CodeResource.net

Code for sending email:
Lets see the code to send an email. This code is executed on the button click control. First of all don't forget to add the
using System.Web.Mail;
namespace which provides the methods and properties for sending an email.
private void Button1_Click(object sender, System.EventArgs e)
{
MailMessage mail = new MailMessage();
mail.To = txtTo.Text;
mail.From = txtFrom.Text;
mail.Subject = txtSubject.Text;
mail.Body = txtBody.Text;
SmtpMail.SmtpServer = "localhost";
SmtpMail.Send(mail);
}
The code you see above is very simple to understand. In the button click event we made the object/instance of the MailMessage class. MailMessage is responsible for sending emails. It also provides several properties and methods. later we assigned several properties.
The line SmtpMail.SmtpServer = "localhost" sets the server for the mail. If you are running the application on your own pc using IIS than your server will be "localhost". If your website is running on the production server you can have different SmtpServer name.
The final line SmtpMail.Send(mail) sends the email to the email address provided.

For complete article: http://www.codersource.net/csharp_sending_emails.aspx

No comments: