Saturday 31 December 2011

ASP.NET - Send Email in C#.NET


Sending Email in ASP.NET
using System.Net.Mail;
protected void imgbtnSendEmail_Click(object sender, EventArgs e)
        {
            MailMessage Msg = new MailMessage();
            Msg.To = txtTo.Text;
            Msg.From = txtFrom.Text;
            Msg.Cc = txtCc.Text;
            Msg.Subject = "SyntaxHelp Welcomes You";
            Msg.objEmail.Body = txtBody.Text;
            Msg.Priority = MailPriority.High;
            Msg.BodyFormat = MailFormat.Html;
            Msg.Attachments.Add(Server.MapPath("SyntaxHelp.doc"));
            //Notifies if delivery of e-mail is success
            DeliveryNotificationOptions= DeliveryNotificationOptions.OnSuccess
            SmtpClient client = new SmtpClient("localhost");

            client.Timeout = 500;
            try
            {
                client.Send(Msg);
                Response.Write("Your Email has been sent sucessfully");
            }
            catch (Exception exc)
            {
                Response.Write(" Send Email fails: " + exc.ToString());
            }
        }

Change web.config settings to Configure SMTP
     <system.net>
   <mailsettings>
     <smtp from="syntaxhelp@syntaxhelpdomain.com">
       <network host="somesmtpserver" port="25" username="name" password="pass" defaultcredentials="true">
     </network></smtp>
   </mailsettings>
</system.net>

No comments:

Post a Comment