Refer the below sample code for your reference.
SQL
CREATE TABLE OpenedEmails(EmailID UNIQUEIDENTIFIER NOT NULL)
HTML
CS.Aspx
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="btnSentEmail" runat="server" Text="Sent Email" OnClick="SentEmail" />
</div>
</form>
</body>
</html>
C#
protected void SentEmail(object sender, EventArgs e)
{
MailMessage Mymessage = new MailMessage();
Mymessage.From = new MailAddress("fromEmailAddress@gmail.com");
Mymessage.To.Add(new MailAddress("recepientEmail@gmail.com"));
Mymessage.Headers.Add("Disposition-Notification-To", "notificationemail@gmail.com");
Mymessage.DeliveryNotificationOptions = DeliveryNotificationOptions.OnSuccess;
Mymessage.Subject = "This is test email";
Mymessage.Body = "Hi,<br/>I love ASPSnippets.<br/>Thanks";
// Your handler url which will log the email read entry
Mymessage.Body += "<img src ='" + "http://localhost:49231/198453_EmailTracing_SentEmail/TrackEmail.ashx?emailId=" + Guid.NewGuid() + "'" + " height='1px' width='1px' />";
// Your Page url which will log the email read entry
// Uncomment the below line to check for log by Page code
//Mymessage.Body += "<img src ='" + "http://localhost:49231/198453_EmailTracing_SentEmail/LogPage.aspx?emailId=" + Guid.NewGuid() + "'" + " height='1px' width='1px' />";
Mymessage.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.EnableSsl = true;
System.Net.NetworkCredential networkCred = new System.Net.NetworkCredential();
networkCred.UserName = "<UserName>";
networkCred.Password = "<Password>";
smtp.UseDefaultCredentials = true;
smtp.Credentials = networkCred;
smtp.Port = 587;
smtp.Send(Mymessage);
}
TrackEmail.ashx
<%@ WebHandler Language="C#" Class="TrackEmail" %>
using System;
using System.Web;
public class TrackEmail : IHttpHandler {
public void ProcessRequest (HttpContext context) {
if (checkIfRequested(context.Request))
{
context.Response.StatusCode = 304;
context.Response.SuppressContent = true;
}
else
{
if (!string.IsNullOrEmpty(context.Request.QueryString["emailId"]) )
{
string emailId = context.Request.QueryString["emailId"].ToString();
InsertEmailOpenDetails(emailId);
}
byte[] imgbytes = System.IO.File.ReadAllBytes(context.Server.MapPath("~/Images/imgEmail.png"));
context.Response.ContentType = "image/png";
context.Response.AppendHeader("Content-Length", imgbytes.Length.ToString());
context.Response.Cache.SetLastModified(DateTime.Now);
context.Response.Cache.SetCacheability(HttpCacheability.Public);
context.Response.BinaryWrite(imgbytes);
}
}
public bool IsReusable
{
get
{
return false;
}
}
private bool checkIfRequested(HttpRequest req)
{
return req.Headers["If-Modified-Since"] == null ? false : DateTime.Parse(req.Headers["If-Modified-Since"]).AddHours(24) >= DateTime.Now;
}
private void InsertEmailOpenDetails(string emailId)
{
string constring = System.Configuration.ConfigurationManager.ConnectionStrings["ConStr"].ConnectionString;
System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection(constring);
string query = "INSERT INTO OpenedEmails(EmailID) VALUES(@EmailID)";
System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(query, con);
cmd.CommandType = System.Data.CommandType.Text;
con.Open();
cmd.Parameters.AddWithValue("@EmailID", System.Data.SqlDbType.VarChar).Value = emailId;
cmd.ExecuteNonQuery();
con.Close();
}
}
If you want to log by page then refer the below code for page.
LogPage.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
if (checkIfRequested(Request))
{
Response.StatusCode = 304;
Response.SuppressContent = true;
}
else
{
if (!string.IsNullOrEmpty(Request.QueryString["emailId"]))
{
string emailId = Request.QueryString["emailId"].ToString();
InsertEmailOpenDetails(emailId);
}
byte[] imgbytes = File.ReadAllBytes(Server.MapPath("~/Images/imgEmail.png"));
Response.ContentType = "image/png";
Response.AppendHeader("Content-Length", imgbytes.Length.ToString());
Response.Cache.SetLastModified(DateTime.Now);
Response.Cache.SetCacheability(HttpCacheability.Public);
Response.BinaryWrite(imgbytes);
}
}
private bool checkIfRequested(HttpRequest req)
{
return req.Headers["If-Modified-Since"] == null ? false : DateTime.Parse(req.Headers["If-Modified-Since"]).AddHours(24) >= DateTime.Now;
}
private void InsertEmailOpenDetails(string emailId)
{
string constring = ConfigurationManager.ConnectionStrings["ConStr"].ConnectionString;
SqlConnection con = new SqlConnection(constring);
string query = "INSERT INTO OpenedEmails(EmailID) VALUES(@EmailID)";
SqlCommand cmd = new SqlCommand(query, con);
cmd.CommandType = CommandType.Text;
con.Open();
cmd.Parameters.AddWithValue("@EmailID", SqlDbType.VarChar).Value = emailId;
cmd.ExecuteNonQuery();
con.Close();
}