Here I have described how to send email in Asp.Net C#.

For sending email, required two namespaces “System.Net;”,” System.Net.Mail;”. These namespaces have some classes (“MailMessage”,” Attachment”,” SmtpClient”,” NetworkCredential”) that help to sending mail. Demo is given in few steps.

Step 1: create table with some values.

CREATE DATABASE Email 

USE Email 
CREATE TABLE tblEmailDetails
(
Id INT IDENTITY PRIMARY KEY,
EmailId VARCHAR(200) UNIQUE,
UserName VARCHAR(200)

INSERT INTO tblEmailDetails([EmailId],UserName)
VALUES('memtechlodhi@gmail.com','Manish'),
('praveshsinghfaq@gmail.com','Pravesh Singh')

 Step 2: Create UI part of demo


<fieldset style="width:200px; height:100px">
    <legend>Send bulk emails</legend>
    <asp:Button ID="btnSend" Text="Send" runat="server" onclick="btnSend_Click"/>
</fieldset>

 Step 3: coding part (.cs file)

using System;

using System.Net.Mail;
using System.Data.SqlClient;
using System.Net;
using System.Configuration;
 
public partial class index : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    { 
    }
    protected void btnSend_Click(object sender, EventArgs e)
    {
        string conString = ConfigurationManager.ConnectionStrings["dbconnection"].ConnectionString;
        SqlConnection con = new SqlConnection(conString);
        try
        {
            MailMessage msg = new MailMessage(); 
            SqlCommand cmd = new SqlCommand("select EmailId from tblEmailDetails", con);
            con.Open();
            SqlDataReader dr = cmd.ExecuteReader();
            while (dr.Read())
            {
                msg.Bcc.Add(dr["EmailId"].ToString());
            }
            msg.From = new MailAddress("your email id ");
            msg.Subject = "Testing email delivery";
            msg.Body = "Hello";
            msg.IsBodyHtml = true;
            Attachment imgAtt = new Attachment(Server.MapPath("~/images/issue.png"));
            imgAtt.ContentId = "issue.png";
            msg.Attachments.Add(imgAtt);
            SmtpClient client = new SmtpClient("smtp.gmail.com", 587);
            client.EnableSsl = true;
            NetworkCredential credentials = new NetworkCredential("your email id", "your email password");
            client.Credentials = credentials;
            client.Send(msg);
            Response.Write("We Will Contact you as soon as Possible!!! "); 
        }
        catch { Response.Write("please try again letter!!! "); }
        finally { con.Close(); }
    }
}

 Note: For sending email, sender (From) required email id and regarding password. That checks network credential for sending emails to receiver (To).

  Modified On Nov-30-2017 06:03:33 AM

Leave Comment