Send an Email through C# 5.0


The .Net Framework has fantastic support for web applications. The System.Net.Mail can be used to send Emails very easily. All you require is a valid Username & Password that you use to log into your email account. Attachments of various file types like PNG and JPEG can be very easily attached with the body of the mail.  Below is a function shown to send an email if you are sending through a gmail account. The default port number is 587 & is checked to work well in all conditions.

The  MailMessage class contains everything you'll need to send an email. The information related to an email like From, To, Subject, CC, BCC etc. These parameters can be set to the Object created from the MailMessage Class. Also note that the attachment object has a text parameter. This text parameter is actually the file path of the file that is to be sent as the attachment. When you click the attach button, a file path dialog box appears which allows us to choose the file path(of an existing file) on your Hard Disk.

public void SendEmail()
        {
            try
            {
                MailMessage mailObject = new MailMessage();
                SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
                mailObject.From = new MailAddress(txtFrom.Text);
                mailObject.To.Add(txtTo.Text);
                mailObject.Subject = txtSubject.Text;
                mailObject.Body = txtBody.Text;

                if (txtAttach.Text != "") // Check if Attachment Exists
                {
                    System.Net.Mail.Attachment attachmentObject;
                    attachmentObject = new System.Net.Mail.Attachment(txtAttach.Text);
                    mailObject.Attachments.Add(attachmentObject);
                }

                SmtpServer.Port = 587;
                SmtpServer.Credentials = new System.Net.NetworkCredential(txtFrom.Text, txtPassKey.Text);
                SmtpServer.EnableSsl = true;

                SmtpServer.Send(mailObject);
                MessageBox.Show("Mail Sent Successfully");
            }
            catch (Exception ex)
            {
                MessageBox.Show("Some Error Plz Try Again", "http://www.code-kings.blogspot.com");
            }
        }

Please Note :
** Do not Copy & Paste code written here ; instead type it in your Development Environment
** Testing done in .Net Framework 4.5 but code should be very similar for previous versions of .Net
** All Program Codes written here are 100%  tested & running.