today i was wondering for some well written SMTP mail sender code in ASP.NET 2.0. i found so many but then i liked to write one for myself. here it goes...
public void SendMailNow()
{
// System.Web.Mail.SmtpMail.SmtpServer is obsolete in 2.0
// System.Net.Mail.SmtpClient is the alternate class for this in 2.0
SmtpClient smtpClient = new SmtpClient(); System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
try
{
MailAddress fromAddress = new MailAddress(FromEmail, FromDisplayName);
// You can specify the host name or ipaddress of your server
// Default in IIS will be localhost
smtpClient.Host = SmtpServer;
//Default port will be 25
int prt=0;Int32.TryParse(Port, out prt);
smtpClient.Port = prt ;
//From address will be given as a MailAddress Object
message.From = fromAddress;
// To address collection of MailAddress
foreach(string t in To)
{
message.To.Add(t);
}
message.Subject = Subject;
// CC and BCC optional
foreach (string c in Cc)
{
message.CC.Add(c);
}
foreach (string b in Bcc)
{
message.Bcc.Add(b);
}
// MailAddressCollection class is used to send the email to various users
// You can specify Address as new MailAddress("admin1@yoursite.com")
message.CC.Add(new MailAddress("sajid.nazeer@gmail.com", "Sajid"));
// You can specify Address directly as string
//message.Bcc.Add(new MailAddress("admin3@yoursite.com"));
//message.Bcc.Add(new MailAddress("admin4@yoursite.com"));
//Body can be Html or text format
//Specify true if it is html message
message.IsBodyHtml = IsHtml;
// Message body content
message.Body = Message.Trim();
// Send SMTP mail
smtpClient.Send(message);
}
catch (Exception)
{
throw;
}
}
Download the Code in C#
EmailSender.cs (6.09 kb)