Wednesday, June 4, 2008

Send Email using C#.NET (Visual Studio 2005)

Sending email is easy and simple by using the various classes in .NET Framework. But if you miss the right combinations, it will give you some headaches as well. Here I will just list the statements which will help you atleast test sending an email, then you can explore various option and combinations by yourself.

Here I will explan with sample code on how to send email using C# in Windows application (VS 2005).

If we are using the SMTP Server of Gmail for example, use the following code. But if you keep on sending emails continuously using smtp.gmail.com, chances are that your login will be restricted with some picture validation, which will result in failure of sending email using program. If you intent to use email feature of C# for commercial applications, it is always better to use a valid/paid email service.

The namespaces used

  • using System.Net;

  • using System.Net.Mail;

  • using System.Net.Mime;

The classes involved

SmtpClient - Allows applications to send email by using the Simple Mail Transfer Protocol (SMTP)
MailMessage- Represents an email message that can be sent using the System.Net.Mail.SmtpClient class
MailAddress- Represents the address of an electronic mail sender or recipient
NetworkCredential- Provides credentials for password-based authentication schemes

Example Code:
Case 1:
If you use gmail or similar kind of smtp servers
//Code Statements//replace xyz@xyz.com,zzz@xyz.com & xxxxx with actual values.

try
{
//The From address (Email ID)
string str_from_address = "xyz@xyz.com";

//The Display Name
string str_name= "Test Mail";

//The To address (Email ID)
string str_to_address = "zzz@xyz.com";

//Create MailMessage Object
MailMessage email_msg = new MailMessage();

//Specifying From,Sender & Reply to address
email_msg.From = new MailAddress(str_from_address, str_name);
email_msg.Sender = new MailAddress(str_from_address, str_name);
email_msg.ReplyTo = new MailAddress(str_from_address, str_name);

//The To Email id
email_msg.To.Add(str_to_address);

email_msg.Subject = "My Subject";//Subject of email

email_msg.Body = "This is the body of this message";

//Create an object for SmtpClient class
SmtpClient mail_client = new SmtpClient();

//Providing Credentials (Username & password)
NetworkCredential network_cdr = new NetworkCredential();
network_cdr.UserName = str_from_address;
network_cdr.Password = "xxxxx";

mail_client.Credentials = network_cdr;

//Specify the SMTP Port
mail_client.Port = 587;

//Specify the name/IP address of Host
mail_client.Host = "smtp.gmail.com";

//Uses Secure Sockets Layer(SSL) to encrypt the connection
mail_client.EnableSsl = true;

//Now Send the message
mail_client.Send(email_msg);

MessageBox.Show("Email Sent Successfully");
}
catch (Exception ex)
{
//Some error occured
MessageBox.Show(ex.Message.ToString());
}


Case 2
If we are using some business email/ paid emails, we need to use only basic authentication, providing the username and password will be enough to send the email. This block of statements will do the task.



//Code Statements
//replace xyz@xyz.com,zzz@xyz.com & xxxxx with actual values.
//smtp.yyyy.com should be replaced with smtp host of your email service
//UseDefaultCredentials is set to false
//Also EnableSsl property is skipped(If your smtp server supports, you can include it)

try
{
string str_from_address = "xyz@xyz.com"; //The From address (Email ID)
string str_name= "Test Mail"; //The Display Name
string str_to_address = "zzz@xyz.com"; //The To address (Email ID)

//Create MailMessage Object
MailMessage email_msg = new MailMessage();

//Specifying From,Sender & Reply to address
email_msg.From = new MailAddress(str_from_address, str_name);
email_msg.Sender = new MailAddress(str_from_address, str_name);
email_msg.ReplyTo = new MailAddress(str_from_address, str_name);

//The To Email id
email_msg.To.Add(str_to_address);

email_msg.Subject = "My Subject";//Subject of email
email_msg.Body = "This is the body of this message";
email_msg.Priority = MailPriority.Normal;

//Create an object for SmtpClient class
SmtpClient mail_client = new SmtpClient();

//Providing Credentials (Username & password)
NetworkCredential network_cdr = new NetworkCredential();
network_cdr.UserName = str_from_address;
network_cdr.Password = "xxxxx";

mail_client.Host = "smtp.yyyy.com"; //SMTP host
mail_client.UseDefaultCredentials = false;
mail_client.Credentials = network_cdr;

//Now Send the message
mail_client.Send(email_msg);

MessageBox.Show("Email Sent Successfully");

}
catch (Exception ex)
{
//Some error occured
MessageBox.Show(ex.Message.ToString());
}

//Happy Sending email :)

23 comments:

Anonymous said...

TQ for the code man, I have been looking the thing u post for 3 hours.

So many website I go, still no good result.

With your solution here, its just so easy...

super super TQ
(keep the link pls, I might promote your link at any forum )

Unknown said...

Hi last 10 days I tried for that, I referred lot of web sites and articles but i didn’t got the solution. But your post I simply finish that thank you.

Unknown said...

Thanx.. finally after tryin codin for last 2 days.. i found ur blog n it helped me a lot.. :)... happy writing lyk dis... :)
richa.j06@gmail.com

Anonymous said...

Who knows where to download XRumer 5.0 Palladium?
Help, please. All recommend this program to effectively advertise on the Internet, this is the best program!

Unknown said...

Thankyou. I search this code for two weeks. Now it is easy.

Unknown said...

thankyou. it is simple and it works good

Anonymous said...

thank you for the code it helps a lot....thank you thank you.

Rauf said...

Hi Mr.Sujith,

Thanks. Lot of thanks. I was searching for the same for long days.
I just used your code and executed it. I astonished, I got one new message in may gmail inbox. Thanks.

Anonymous said...

can i use that codes in Visual Studio 2008 as well?

Anonymous said...

i got an exception that says

"Command not implemented. The server response was: 5.5.1 Unrecognized command. 33sm6514805wfg.9"


can anyone help?

athira said...

thanks...................great yar.............

Unknown said...

Hi Thank you very good and easy step example for sening a mail using smtp mail server

sushma said...

Thank you very much... i have spent more than 8 hours on this code ... you did it so simple.. Yuppiii my work is done..

sushma said...

hello,
Please help me. i am coding foe contact page of my website. I have a id xxx@mycompany.com. if any one post me mail it should be delivered to this id. The problem is i am not getting mails when posted from other mailid like gmail or yaoo or any other i get mails only when submitted from my company domain only. like ccc@mycompany.com or jjj@mycompany.com. if possible mail me to sushmav2607@gmail.com

INP_Koes said...

networkcredential could not found error coming while compiling

sanjay said...

after waisting 2 days i found some relief thanks


thank you very much

NANDINAGOPALKRISHNA said...

I am getting ERROR MESSAGE "fails sending mail"


mail_client.Send(email_msg);

at this step i am getting this error sms plz help to solve this....

Unknown said...

I found Something Simple,
here is detailed Explanation
http://path4tech.blogspot.in/2012/02/simple-c-application-to-send-email.html

Anonymous said...

Worked flawless
Thank you

Anonymous said...

Thank you so much...!!! helped me a lot.. :)

Anonymous said...

Helped me a lot... thanks a lot.... :)

Anonymous said...

Helped me a lot... thanks a lot.... :)

Taa said...

thank you very much for this post,

i had a problem with "fails sending mail"

but was solved with my antivirus configuration