Sunday, July 5, 2009

How to Send mail through C# using SMTP

If you need to send mails through your code here is the simple Example in
C#

1) Add the System.Net.Mail; namespace to your code.

2) Wirte this code or modify it according to your need.

SmtpClient smtpClient = new SmtpClient();
MailMessage message = new MailMessage();
try
{
string sHostName = "mail.test.com";
string strEmailFrom = "Manoj@mailtest.com";
string sFromName = "Manoj";
string strToEmail = "manojjoshi@gmail.com";
string strSubject = "Test Mail From Manoj";
string strBody = "< table >< tr >< td >This is just a test mail< /td >
< /tr >< /table >"; // Format your massage body here

MailAddress fromAddress = new MailAddress(strEmailFrom, sFromName);

// You can specify the host name or ipaddress of your server
// Default in IIS will be localhost in this case it is mail.test.com
smtpClient.Host = sHostName;
//Default port will be 25
smtpClient.Port = 25;
//From address will be given as a MailAddress Object
message.From = fromAddress;
// To address collection of MailAddress
message.To.Add(strToEmail);
message.Subject = strSubject;
string ccMailIDs = "MyCC1@gmail.com";

///this line of code is for adding more Recipients in cc of your mail

message.CC.Add(new MailAddress(ccMailIDs));
ccMailIDs = "MyCC2@gmail.com";
message.CC.Add(new MailAddress(ccMailIDs));
ccMailIDs = "MyCC3@gmail.com";
message.CC.Add(new MailAddress(ccMailIDs));
//Body can be Html or text format
//Specify true if it is html message
message.IsBodyHtml = true;
// Message body content
message.Body = strBody;

// Send SMTP mail
smtpClient.Send(message);

}
catch (Exception ex)
{
string s = ex.Message;
}


And you are done. Cheers

No comments:

Post a Comment