C# send email

C# send email


  Many times while developing application you come across the requirement, where you need to send emails to users using your application.
Here I will use Gmail account for sending emails. First you need to open Gmail account and configure it's settings to allow
third party clients send emails or receive emails. You can refer how to configure Gmail account by visiting here: Gmail configuration
send email using asp.net and gmail smtp

 
using System.Net.Mail;
using System.Net;
   It uses above namespace. System.Net will be used for network credentials and System.Net.Mail
   will be used for Sending and creating mail message object.
private void SendEmail(string fromEmailAddress, string toEmailAddress)
{
private void SendEmail(UserProfileInfo u)
{
NetworkCredential loginInfo = new NetworkCredential(fromEmailAddress, "Password_of_gmail");
MailMessage msg = new MailMessage();
msg.From = new MailAddress(fromEmailAddress);
msg.To.Add(new MailAddress(toEmailAddress));
msg.Subject = "Your email subject";
msg.Body = "Hi, <br/> This is test email <br/><br/> please ignore this email.";
msg.IsBodyHtml = true;
SmtpClient client = new SmtpClient("smtp.gmail.com");
client.EnableSsl = true;
client.UseDefaultCredentials = false;
client.Credentials = loginInfo;
client.Send(msg);        
}

Description:


Network Credentilas:


Network credential instance accepts username and password. Pass your Gmail credentials to constructor of Network credential.
		NetworkCredential loginInfo = new NetworkCredential(fromEmailAddress, "Password_of_gmail");
	

Mail Message Object:

Create instance of mail message and configure is From Email address, To Email address, Subject and body of email.

		MailMessage msg = new MailMessage();
	msg.From = new MailAddress(fromEmailAddress);
	msg.To.Add(new MailAddress(toEmailAddress));
	msg.Subject = "Your email subject";
	msg.Body = "Hi, <br/> This is test email <br/><br/> please ignore this email.";
	msg.IsBodyHtml = true;	
	

HTML body:
You can send email as HTML body or plain text. To send email as HTML body set mailmessage object ISBodyHtml = true.

		msg.IsBodyHtml = true;
	
SMTP Client setup:

Create instance of SMTP client and use Smtp.gmail.comas SMTP address


			SmtpClient client = new SmtpClient("smtp.gmail.com");
	client.EnableSsl = true;
	client.UseDefaultCredentials = false;
	client.Credentials = loginInfo;
	client.Send(msg); 	
	

EnableSSL to use secure connection with Gmail SMTP.

				client.Credentials = loginInfo;		
		

Tell SMTP client about your network credentials.

				client.Send(msg); 	
		
Pass mail message object to send method of SMtp client instance.

It will send email to destination.

Note:

You may requre to temporarily disbale the forewall. As it may block your application request to SMTP of gmail server.

Currently rated 3.7 by 3 people

  • Currently 3.666667/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:

Author

code tutorial