Saturday, January 14, 2012

How to Send E-Mail Through C# in asp.net.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.Net.Mail;
using System.Data.SqlClient;

public partial class Email : System.Web.UI.Page
{
    SqlConnection con;
    SqlCommand cmd;
    protected void Page_Load(object sender, EventArgs e)
    {
        con = new SqlConnection(@"data source=localhost;initial catalog=Email;integrated security=true");
    }
    protected void btnsave_Click(object sender, EventArgs e)
    {
        con.Open();
        cmd=new SqlCommand("insert into Gmail values('"+DropDownList1.Text+"','"+DropDownList2.Text+"','"+txtusername.Text+"','"+txtpassword.Text+"','"+txtmessage.Text+"')",con);
        cmd.ExecuteNonQuery();
        con.Close();
        Response.Write("Done Successfully");
        MailMessage message = new MailMessage();

        string s1;
        string s2;
        string s3;
        s1 = DropDownList2.SelectedItem.Text;
        s2 = "vibhutimishra58@gmail.com";
        MailAddress fromAddress = new MailAddress(s2);
        s3 = txtusername.Text;
        MailAddress toAddress = new MailAddress(s3);
        message.From = fromAddress;
        message.To.Add(toAddress);
        message.Subject = "Mail Send";
        message.Body = "Message:" + "</br>" + txtmessage.Text;
        if (DropDownList2.SelectedItem.Text == "smtp.gmail.com")
        {
            SmtpClient smtp = new SmtpClient();
            smtp.Port = 587;
            smtp.Host = s1;
            smtp.Credentials = new System.Net.NetworkCredential(s2, "confirm12m*");
            smtp.EnableSsl = true;
            smtp.Send(message);
            txtmessage.Text = "";
        }
        else if (DropDownList2.SelectedItem.Text == "smtp.mail.yahoo.com")
        {
            SmtpClient smtp = new SmtpClient();
            smtp.Port = 465;
            smtp.Host = s1;
            smtp.Credentials = new System.Net.NetworkCredential("Your Email Id","Your password");
            smtp.EnableSsl = true;
            smtp.Send(message);
            txtmessage.Text = "";
        }
    }
}

1 comment: