Loading...

Simple C# Code to Send an Email with Source Code

How To Send Email using C# Code

The Microsoft .NET framework provides two namespaces, System.Net and System.Net.Sockets for handled implementation of Internet protocols that programs can employ to send or receive data on the internet. SMTP protocol is used for sending e-mail. SMTP stands for Simple Mail Transfer Protocol . C# using System.Net.Mail namespace for sending e-mail . We assign the Host and Port and can instantiate SmtpClient class. The default port using SMTP may vary distinct Mail Servers, although it is 25.

The following C# source code reveals the best way to send an e-mail from SMTP server being used by a Gmail address. The Gmail SMTP server name is smtp.gmail.com along with the interface using send mail is 587 and Yahoo server name is smtp.mail.yahoo.com with same port 587 and also using NetworkCredential for password based authentication.

We are sending email from yahoo, you have to change server name if your are trying to email through gmail or hotmail your have to change the server name.
                 
Provider
SMTP Server
Gmail
Smtp.gmail.com
Hotmail
smtp.live.com
Yahoo
Smtp.mail.yahoo.com

Code:

 using System.Net.Mail;
 using System.Net;

      private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                MailMessage mail = new MailMessage();
                SmtpClient SmtpServer = new SmtpClient("smtp.mail.yahoo.com");//smtp server name

                mail.From = new MailAddress("abc@yahoo.com");// sending email
                mail.To.Add("recieve@gmail.com");//recieving email
                mail.Subject = "Test Mail"; //subject
                mail.Body = "This is for testing SMTP mail from GMAIL";//content
                //mail.IsBodyHtml = true;
                //// Can set to false, if you are sending pure text.

                //mail.Attachments.Add(new Attachment("C:\\text.txt"));

                SmtpServer.Port = 587; // port
                SmtpServer.Credentials = new System.Net.NetworkCredential("sending@yahoo.com", "password");// password and email
                SmtpServer.EnableSsl = true;

                SmtpServer.Send(mail);
                MessageBox.Show("mail Send");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString()); // Exception information
            }
        }   

You have to provide the information correct like email and password

Learn how to make a Windows Service using C# here.

Hit Like Button if you understood, It helps a lot to keep us Motivated.

0 comments:

Post a Comment

Google+

 
TOP