Email via ASP.NET

HOW TO SEND EMAIL VIA ASP.NET:
Step 1:
Use the following namespaces:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Mail;

Step 2:
This following function will help you to send emails in asp.net
(pass appropriate parameters to this function)

        public void SendMailMessage(string @from, string recepient, string bcc, string cc, string subject, string body)
        {
            try
            {
                // Instantiate a new instance of MailMessage
                System.Net.Mail.MailMessage mMailMessage = new System.Net.Mail.MailMessage();
                // Set the sender address of the mail message
                mMailMessage.From = new MailAddress(@from);
                // Set the recepient address of the mail message
                mMailMessage.To.Add(new MailAddress(recepient));
                // Check if the bcc value is nothing or an empty string
                if ((bcc != null) & bcc != string.Empty)
                {
                    // Set the Bcc address of the mail message
                    mMailMessage.Bcc.Add(new MailAddress(bcc));
                }
                // Check if the cc value is nothing or an empty value
                if ((cc != null) & cc != string.Empty)
                {
                    // Set the CC address of the mail message
                    mMailMessage.CC.Add(new MailAddress(cc));
                }
                // Set the subject of the mail message
                mMailMessage.Subject = subject;
                // Set the body of the mail message
                mMailMessage.Body = body;
                // Set the format of the mail message body as HTML
                mMailMessage.IsBodyHtml = true;
                // Set the priority of the mail message to normal
                mMailMessage.Priority = System.Net.Mail.MailPriority.Normal;
                // Instantiate a new instance of SmtpClient
                SmtpClient mSmtpClient = new SmtpClient();
                // Send the mail message
                mSmtpClient.Send(mMailMessage);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
[Note:for sending emails from your system,your antivirus software will be disabled]

Step 3:
In the Web.Config file,

   <system.net>
    <mailSettings>
      <smtp deliveryMethod="Network" from="your gmail username">
        <network host="smtp.gmail.com" port="587" userName="your gmail username" password="your gmail password"/>
      </smtp>
    </mailSettings>
  </system.net>

Thats it...!!!!

No comments:

Post a Comment