Monday, June 16, 2014

Code for sending mail in asp.net using c#

  I write following function in my asp.net application to send E-Mail

namespace used for this


using System.Net.Mail;

function that sends the mail
This function requires receivers mail Id,message body of the mail.

 public bool SendMail(string To, string MessageBody)
    {
        // System.Web.Mail.SmtpMail.SmtpServer is obsolete in 2.0
        // System.Net.Mail.SmtpClient is the alternate class for this in 2.0

        try
        {
            SmtpClient smtpClient = new SmtpClient();
            MailMessage message = new MailMessage();
            string From = "sender mail Id";
            MailAddress fromAddress = new MailAddress(From);

            // You can specify the host name or ipaddress of your server
            // Default in IIS will be localhost 
            smtpClient.Host = "relay-hosting.secureserver.net";

            //Default port will be 25
            smtpClient.Port = 25;

            //From address will be given as a MailAddress Object
            message.From = fromAddress;

            // To address collection of MailAddress
            message.To.Add(To);
            message.Subject = "Welcome to world of fresh flowers and gifts";

            message.CC.Add(new MailAddress("Cc Mail Id"));
            message.Bcc.Add(new MailAddress("another Bcc mail Id"));
            message.Bcc.Add(new MailAddress("Another Bcc mail Id"));
        
            message.IsBodyHtml = false;

            // Message body content
            message.Body = MessageBody;

            // Send SMTP mail
            smtpClient.Send(message);
            return true;
            
        }
        catch
        {
            return false;
        }

    }

hope this code will help you in sending Email from your asp.net Application.

Enjoy Coding..........................

No comments:

Post a Comment