Sunday, September 03, 2006

How to send Email using C#

In order to send email in C# in ASP.NET 1.1., do the following:
using System.Web.Mail;

// create mail message object
MailMessage mail = new MailMessage();
mail.From = ""; // put the from address here
mail.To = ""; // put to address here
mail.Subject = ""; // put subject here
mail.Body = ""; // put body of email here
SmtpMail.SmtpServer = ""; // put smtp server you will use here
// and then send the mail
SmtpMail.Send(mail);


In ASP.NET 2.0, the MailMessage class and Smtp.Mail is obsoleted. Instead, you have to use the following code:

public static void CreateTestMessage4(string server)
{
MailAddress from = new MailAddress("ben@contoso.com");
MailAddress to = new MailAddress("Jane@contoso.com");
MailMessage message = new MailMessage(from, to);
message.Subject = "Using the SmtpClient class.";
message.Body = @"Using this feature, you can send an e-mail message from an application very easily.";
SmtpClient client = new SmtpClient(server);
Console.WriteLine("Sending an e-mail message to {0} by using SMTP host {1} port {2}.",
to.ToString(), client.Host, client.Port);
client.Send(message);
}




No comments:

Post a Comment