Tuesday, June 24, 2014

Sending Mail from Asp.Net c#

Introduction

This post will explain you how to sending the mail from the asp.net

Note:- You can send even though you company having Gmail access 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;






namespace SampleTestingCodes
{
    public partial class SendingMailFromAsp : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
           
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            SendMail();
        }
        protected void SendMail()
        {
            // Gmail Address from where you send the mail
            var fromAddress = "gmail@gmail.com";
            // any address where the email will be sending
            var toAddress = txtemailid.Text.ToString();
            //Password of your gmail address
            const string fromPassword = "*****************************";
            // Passing the values and make a email formate to display
            string subject = txtsubject.Text.ToString();
            string body = "From: " + txtyourname.Text + "\n";
            body += "Email: " + txtemailid.Text + "\n";
            body += "Subject: " + txtsubject.Text + "\n";
            body += "Question: \n" + txtbody.Text + "\n";
            // smtp settings
            var smtp = new System.Net.Mail.SmtpClient();
            {
                smtp.Host = "smtp.gmail.com";
                smtp.Port = 587;
                smtp.EnableSsl = true;
                smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
                smtp.Credentials = new NetworkCredential(fromAddress, fromPassword);
                smtp.Timeout = 20000;
            }
                  using (var message = new MailMessage(fromAddress, toAddress)
                {
                    Subject = subject,
                    IsBodyHtml = true,
                    Body = body


                })
                {
                    smtp.Send(message);
                }
                // Passing values to smtp object
                //smtp.Send(fromAddress, toAddress, subject, body);
        }
    }
}



Out put will look like
From: lokehs
Email: lannam@technobrainltd.com
Subject: hi
Question:
gg



No comments:

Post a Comment