Description:-
In this
example we explain that how to send email with read notification and
delivery receipt or sending mail using read notification and delivery receipt
in asp.net using c#.
What is Read
Notification in email:-
Read notification means when you
send the mail anyone one and then it received but we cannot judge that our sent
mail is read by receiver or not so when you send mail with mail Read
Notification checked then it will direct ally resend mail to you that user is
reading your mail.
What is Delivery Receipt
in email:-
Delivery receipt are used to know
that our mail is send to the user successfully or not.
Code.aspx:-
<div class="popup" style="width: 650px !important;">
<div id="rounder_box">
<div class="mid" style="height: auto !important; background: none !important;">
<div class="mid_poopup" style="margin-left: 10px; margin-bottom: 10px;">
<table id="pnldrag1" style="cursor: move; width: 550px;">
<tr>
<td>
<h1>Send Email</h1>
<div style="float: right; cursor: pointer;">
<asp:Image ID="imgimportclose" runat="server" ImageAlign="AbsMiddle" ImageUrl="~/ImageLibrary/SiteAssets/Close.png" />
</div>
</td>
</tr>
</table>
<div class="clear">
<br />
</div>
<div class="clear">
</div>
<div class="sin gsasin">
<label
class="label1">
From :</label>
<asp:TextBox ID="txtFromEmail" runat="server" Width="400px"></asp:TextBox>
<asp:RequiredFieldValidator ID="rfFromEmail" runat="server" ControlToValidate="txtFromEmail" Display="Dynamic"
ValidationGroup="sendemail" ErrorMessage="*" ForeColor="Red" ToolTip="Enter From email
address">
</asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="revEmail" runat="server" ValidationGroup="sendemail"
ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*" ForeColor="Red"
Display="Dynamic" ControlToValidate="txtFromEmail" ErrorMessage="*" ToolTip="Enter valid email
address."
SetFocusOnError="true"></asp:RegularExpressionValidator>
</div>
<div class="clear">
</div>
<div class="sin gsasin">
<label
class="label1">
To :</label>
<asp:TextBox ID="txtToAddess" runat="server" Width="400px"></asp:TextBox>
<asp:RequiredFieldValidator ID="regemail" EnableClientScript="true" runat="server" ControlToValidate="txtToAddess" Display="Dynamic"
ValidationGroup="sendemail" ErrorMessage="*" ForeColor="Red" ToolTip="Enter To email
address">
</asp:RequiredFieldValidator>
<asp:CustomValidator ID="custvValidateEmail" EnableClientScript="true" runat="server" ControlToValidate="txtToAddess" Display="Dynamic"
ValidationGroup="sendemail" ClientValidationFunction="validateEmails" ErrorMessage="*" ForeColor="Red" ToolTip="Invalid Email
Address(es)">
</asp:CustomValidator>
</div>
<div class="clear">
</div>
<div class="sin gsasin">
<label
class="label1">
</label>
<i>(Multiple email addresses are allowed
separate by (;) .)</i>
</div>
<div class="clear">
</div>
<div class="sin gsasin">
<label
class="label1">
Subject :</label>
<asp:TextBox ID="txtEmailSubject" runat="server" MaxLength="250" Width="400px"></asp:TextBox>
<asp:RequiredFieldValidator ID="redSubject" EnableClientScript="true" runat="server" ControlToValidate="txtEmailSubject" Display="Dynamic"
ValidationGroup="sendemail" ErrorMessage="*" ForeColor="Red" ToolTip="Enter email
subject">
</asp:RequiredFieldValidator>
</div>
<div class="clear">
</div>
<div class="sin gsasin" style="width: 400px;">
<div>
<asp:Label ID="lblAtttitle" runat="server" CssClass="label1">
Attachments
:</asp:Label>
<asp:LinkButton ID="lnkviepdfattach" OnClick="lnkviepdfattach_Click" runat="server">
<asp:Label ID="lblAttachment" runat="server" ForeColor="Blue"></asp:Label>
</asp:LinkButton><br />
<div id="dvFile1" runat="server">
<asp:Label ID="Label2" runat="server" CssClass="label1" Style="visibility: hidden">
Attachments
:</asp:Label>
<asp:CheckBox ID="chkFile1" runat="server" /><asp:LinkButton ID="lnkFile1" runat="server" Text="File 1" OnClick="lnkFile1_Click"></asp:LinkButton>
</div>
<br />
<div id="dvFile2" runat="server">
<asp:Label ID="Label1" runat="server" CssClass="label1" Style="visibility: hidden">
Attachments
:</asp:Label>
<asp:CheckBox ID="chkFile2" runat="server" /><asp:LinkButton ID="lnkFile2" runat="server" Text="File 2" OnClick="lnkFile2_Click"></asp:LinkButton>
</div>
<br />
<div id="dvMoreAttach" runat="server" style="float: left; width: 100%; margin-left: 113px;" visible="false">
<asp:DataList ID="dlAttachs" runat="server" RepeatDirection="Horizontal" CellPadding="3" CellSpacing="3" RepeatColumns="1" OnItemDataBound="dlAttachs_ItemDataBound">
<ItemTemplate>
<asp:CheckBox ID="chkAttcah" runat="server" />
<asp:LinkButton ID="lnkMoreFile" runat="server" OnClick="lnkMoreFile_Click"></asp:LinkButton>
<asp:HiddenField ID="hdnFile" runat="server" Value='<% #Eval("amdfile")%>'></asp:HiddenField>
</ItemTemplate>
<ItemStyle VerticalAlign="Middle" />
</asp:DataList>
</div>
</div>
</div>
<div class="clear">
</div>
<div class="sin gsasin" id="fileuploaddiv" runat="server">
<label
class="label1" style="width: 125px !important;">
Attach More File :</label>
<asp:FileUpload ID="flUFile" runat="server" AllowMultiple="true" class="multi" />
<asp:Button runat="server" ID="uploadedFile" Text="Upload" OnClick="uploadFile_Click" />
<ul id="ulfl" runat="server">
</ul>
<asp:Repeater ID="menu_ul_1" runat="server" OnItemCommand="menu_ul_1_ItemCommand" >
<HeaderTemplate>
<ul class="my-menu" Style="height:100px;overflow:auto">
</HeaderTemplate>
<ItemTemplate>
<li>
<asp:ImageButton ID="ImageButton1" runat="server" ImageUrl="~/App_Themes/Default/Images/remove.png" CommandName="Delete" />
<asp:HiddenField ID="hdnid" runat="server" Value='<%# Eval("id")%>' />
<asp:HiddenField ID="path" runat="server" Value='<%# Eval("DisplayText")%>' />
<asp:HyperLink ID="LinkButton1" Target="_blank" NavigateUrl='<%# Eval("href_li")%>' CommandName="Open" runat="server"><%# Eval("DisplayText")%></asp:HyperLink>
<%-- <a href='<%# Eval("href_li")%>'>
<%# Eval("DisplayText")%></a>--%>
</li>
</ItemTemplate>
<FooterTemplate>
</ul>
</FooterTemplate>
</asp:Repeater>
<%--<asp:BulletedList ID="BulletedList1"
runat="server" OnClick="BulletedList1_Click"
DisplayMode="HyperLink"></asp:BulletedList>--%>
</div>
<div class="clear">
</div><br />
<div>
<asp:Label ID="Label3" runat="server" CssClass="label1" Style="visibility: hidden">
Attachmentssssss :</asp:Label>
<b> <asp:CheckBox ID="chkDeliveryNotification" runat="server" Text=" Delivery
Notification" /></b><br /><br />
<asp:Label ID="Label4" runat="server" CssClass="label1" Style="visibility: hidden">
Attachmentssssss :</asp:Label>
<b> <asp:CheckBox ID="chkReadNotification" runat="server" Text=" Read
Notification" /></b>
</div>
<div class="clear">
</div><br />
<div class="sin gsasin">
<label
class="label1" style="visibility: hidden">
Body :</label>
<asp:TextBox ID="txtEmailBody" runat="server" Style="width:600px" CssClass="txtLongDescr"
Height="300px"></asp:TextBox>
<ajax:HtmlEditorExtender ID="htmleditor" runat="server" EnableSanitization="false"
TargetControlID="txtEmailBody">
<Toolbar>
<ajax:Undo />
<ajax:Redo />
<ajax:Bold />
<ajax:Italic />
<ajax:Underline />
<ajax:StrikeThrough />
<ajax:Subscript />
<ajax:Superscript />
<ajax:CreateLink />
<ajax:UnLink />
<ajax:JustifyLeft />
<ajax:JustifyCenter />
<ajax:JustifyRight />
<ajax:JustifyFull />
<ajax:RemoveFormat />
<ajax:SelectAll />
<ajax:UnSelect />
<ajax:Delete />
<ajax:Cut />
<ajax:Copy />
<ajax:Paste />
<ajax:BackgroundColorSelector />
<ajax:ForeColorSelector />
<ajax:FontNameSelector />
<ajax:FontSizeSelector />
<ajax:InsertHorizontalRule />
<ajax:HorizontalSeparator />
</Toolbar>
</ajax:HtmlEditorExtender>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" EnableClientScript="true" runat="server" ControlToValidate="txtEmailBody" Display="Dynamic"
ValidationGroup="sendemail" ErrorMessage="*" ForeColor="Red" ToolTip="Enter Email
Body">
</asp:RequiredFieldValidator>
</div>
<div class="clear">
<br />
</div>
<div class="btn_rounded_syle" style="float: right;">
<asp:LinkButton ID="lnkSendEmail" runat="server" OnClientClick="return
checkhtmleditor();"
OnClick="imgEmail_Click" ValidationGroup="sendemail">Send Email</asp:LinkButton>
</div>
<div class="clear">
</div>
</div>
<div class="clear">
</div>
</div>
</div>
</div>
byte[] theData = theDoc.GetData();
MemoryStream ms = new MemoryStream(theData);
string ccname = string.Empty;
string ccaddress = string.Empty;
string BCC = string.Empty;
if (!string.IsNullOrEmpty(Convert.ToString(Session["userid"])))
{
DataTable dtUser = BLQuote.GetUserDetailsByUserName(Convert.ToString(Session["userid"]));
if (dtUser.Rows.Count > 0)
{
if (!string.IsNullOrEmpty(Convert.ToString(dtUser.Rows[0]["email"])))
{
// ccname = Convert.ToString(dtUser.Rows[0]["fname"])
+ " " + Convert.ToString(dtUser.Rows[0]["lname"]);
// ccaddress =
Convert.ToString(dtUser.Rows[0]["email"]);
}
}
}
BCC = ConfigurationManager.AppSettings["bcc"].ToString();
DataTable dtBid = BLGovBid.GetBidDetailsByID(BidID);
MemoryStream ms1 = null;
MemoryStream ms2 = null;
MemoryStream UploadFile = null;
//Files from amddoc.
Dictionary<string, MemoryStream> objAttachments = new Dictionary<string, MemoryStream>();
if (dlAttachs.Items.Count > 0)
{
for (int i = 0; i < dlAttachs.Items.Count;
i++)
{
CheckBox chkAttcah = (CheckBox)dlAttachs.Items[i].FindControl("chkAttcah");
LinkButton lnkMoreFile = (LinkButton)dlAttachs.Items[i].FindControl("lnkMoreFile");
if (chkAttcah.Checked)
{
string filenamepath =
lnkMoreFile.CommandArgument;
string filename = Path.GetFileName(lnkMoreFile.CommandArgument);
if (File.Exists(filenamepath))
{
MemoryStream msAttach = WebHelper.FileToByteArray(filenamepath) != null ? new MemoryStream(WebHelper.FileToByteArray(filenamepath)) : null;
objAttachments.Add(filename, msAttach);
}
}
}
}
string File1Name = string.Empty;
string File2Name = string.Empty;
List<FileUpload> lstFiles = new List<FileUpload>();
string UploadFileName = string.Empty;
if (dtBid.Rows.Count > 0)
{
string File1 = Convert.ToString(dtBid.Rows[0]["salesfile1"]);
string File2 = Convert.ToString(dtBid.Rows[0]["salesfile2"]);
if (ConfigurationManager.AppSettings["FilePath"] != null)
{
if (File1 != string.Empty)
File1 = Server.MapPath(Convert.ToString(ConfigurationManager.AppSettings["FilePath"]) + File1);
if (File2 != string.Empty)
File2 = Server.MapPath(Convert.ToString(ConfigurationManager.AppSettings["FilePath"]) + File2);
if (File.Exists(File1))
{
if (chkFile1.Checked)
{
ms1 = WebHelper.FileToByteArray(File1) != null ? new MemoryStream(WebHelper.FileToByteArray(File1)) : null;
File1Name = Path.GetFileName(File1);
lnkFile1.CommandArgument = File1;
}
}
if (File.Exists(File2))
{
if (chkFile2.Checked)
{
ms2 = WebHelper.FileToByteArray(File2) != null ? new MemoryStream(WebHelper.FileToByteArray(File2))
: null;
File2Name = Path.GetFileName(File2);
lnkFile2.CommandArgument = File2;
}
}
//File from File Uploader controls.
// List<MemoryStream>
lstmemorystram = new List<MemoryStream>();
// List<string> lstfiles = new
List<string>();
for (int item = 0; item < this.menu_ul_1.Items.Count; item++)
{
if (menu_ul_1.Items[item].Visible)
{
HyperLink link = this.menu_ul_1.Items[item].FindControl("LinkButton1") as HyperLink;
HiddenField hiddenField = this.menu_ul_1.Items[item].FindControl("path") as HiddenField;
string path = Server.MapPath(link.NavigateUrl);
byte[] data = File.ReadAllBytes(path);
MemoryStream stream = new MemoryStream(data);
UploadFileName = hiddenField.Value;
FileUpload file = new FileUpload();
file.fileName = UploadFileName;
file.fileUpload = stream;
lstFiles.Add(file);
}
}
}
}
// code for readNotification and
DeliveryNotification
bool DeliveryNotification = false, ReadNotification = false;
if (chkDeliveryNotification.Checked)
DeliveryNotification = true;
if (chkReadNotification.Checked)
ReadNotification = true;
if (lblNTSQuoteno.Text != "" && lblAttachment.Visible)
ob.SendEmail(txtFromEmail.Text, ccname, txtToAddess.Text, "", txtEmailSubject.Text, txtEmailBody.Text,
true, ms, "Quote_" + lblNTSQuoteno.Text + ".PDF", lstFiles, ccaddress, ccname, BCC, ms1,
ms2, File1Name, File2Name, objAttachments, DeliveryNotification,
ReadNotification);
// ob.SendEmail(txtFromEmail.Text,
ccname, txtToAddess.Text, "", txtEmailSubject.Text,
txtEmailBody.Text, true, ms, "Quote_" + lblNTSQuoteno.Text +
".PDF", lstFiles, ccaddress, ccname, ms1, ms2, File1Name, File2Name,
objAttachments);
else
ob.SendEmail(txtFromEmail.Text, ccname, txtToAddess.Text, "", txtEmailSubject.Text,
txtEmailBody.Text, true, ms, null, lstFiles, ccaddress,
ccname, BCC, ms1, ms2, File1Name, File2Name, objAttachments,
DeliveryNotification, ReadNotification);
// ob.SendEmail(txtFromEmail.Text,
ccname, txtToAddess.Text, "", txtEmailSubject.Text,
txtEmailBody.Text, true, ms, null, lstFiles, ccaddress, ccname, ms1, ms2,
File1Name, File2Name, objAttachments);
// txtEmailBody.Text = string.Empty;
menu_ul_1.DataSource = null;
menu_ul_1.DataBind();
//txtEmailSubject.Text = string.Empty;
//txtToAddess.Text = string.Empty;
ScriptManager.RegisterStartupScript(Page, this.GetType(), "alert", "alert('Email sent successfully.');", true);
SendMail.cs:-
public bool SendEmail(string _FromEmail, string _FromName, string _ToEmail, string
_ToName, string _Subject, string
_EmailBody, bool _IsBodyHtml, Stream _Attachments, string FileName, List<FileUpload> lstFiles, string _CCEmail = "", string _CCName = "", string _BCC = "", Stream
_File1 = null, Stream
_File2 = null, string _File1Name = "", string _File2Name = "", Dictionary<string, MemoryStream> objMoreAttachements = null, bool DeliveryNotification=false, bool ReadNotification=false)
{
try
{
string _EmailServer = ConfigurationManager.AppSettings["SMTPServer"].ToString();
int _Port = Convert.ToInt32(ConfigurationManager.AppSettings["SMTPPort"].ToString());
string _LoginName = ConfigurationManager.AppSettings["SMTPUser"].ToString();
string _LoginPassword = ConfigurationManager.AppSettings["SMTPPassword"].ToString();
bool _EnableSsl = Convert.ToBoolean(Convert.ToInt32(ConfigurationManager.AppSettings["SmtpUseSSL"]));
// setup email header
System.Net.Mail.MailMessage _MailMessage = new System.Net.Mail.MailMessage();
// Set the message sender
// sets the from address for this e-mail
message.
_MailMessage.From = new System.Net.Mail.MailAddress(_FromEmail, _FromName.Trim());
//Add code for request for receipt / Read
/ delivery acknowledge confirmation
if(DeliveryNotification)
_MailMessage.DeliveryNotificationOptions = System.Net.Mail.DeliveryNotificationOptions.OnSuccess;
if(ReadNotification)
_MailMessage.Headers.Add("Disposition-Notification-To", _FromEmail);
// Sets the address collection that
contains the recipients of this e-mail message.
string[] emails = _ToEmail.Split(';');
if (emails.Length > 1)
{
for (int i = 0; i < emails.Length; i++)
{
_MailMessage.To.Add(new System.Net.Mail.MailAddress(emails[i], _ToName.Trim()));
}
}
else
{
_MailMessage.To.Add(new System.Net.Mail.MailAddress(emails[0], _ToName.Trim()));
}
// sets the CC email address.
// if (_CCEmail != string.Empty)
//
_MailMessage.CC.Add(new System.Net.Mail.MailAddress(_CCEmail,
_CCName.Trim()));
if (_BCC != string.Empty)
_MailMessage.Bcc.Add(new System.Net.Mail.MailAddress(_BCC));
// sets the message subject.
_MailMessage.Subject = _Subject;
// sets the message body.
_MailMessage.Body = _EmailBody;
// sets a value indicating whether the
mail message body is in Html.
// if this is false then ContentType of
the Body content is "text/plain".
_MailMessage.IsBodyHtml = _IsBodyHtml;
// add all the file attachments if we
have any
if (_Attachments != null && _Attachments.Length > 0)
{
if(FileName != null)
_MailMessage.Attachments.Add(new System.Net.Mail.Attachment(_Attachments, FileName, "application/octet-stream"));
}
if (_File1 != null && _File1.Length > 0)
{
_MailMessage.Attachments.Add(new System.Net.Mail.Attachment(_File1, _File1Name, "application/octet-stream"));
}
if (_File2 != null && _File2.Length > 0)
{
_MailMessage.Attachments.Add(new System.Net.Mail.Attachment(_File2, _File2Name, "application/octet-stream"));
}
foreach (FileUpload file in lstFiles)
{
_MailMessage.Attachments.Add(new System.Net.Mail.Attachment(file.fileUpload, file.fileName, "application/octet-stream"));
}
if (objMoreAttachements != null)
{
foreach (var pair in objMoreAttachements)
{
_MailMessage.Attachments.Add(new System.Net.Mail.Attachment(pair.Value, pair.Key, "application/octet-stream"));
}
}
// SmtpClient Class Allows applications
to send e-mail by using the Simple Mail Transfer Protocol (SMTP).
System.Net.Mail.SmtpClient _SmtpClient = new System.Net.Mail.SmtpClient(_EmailServer);
//Specifies how email messages are
delivered. Here Email is sent through the network to an SMTP server.
_SmtpClient.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
_SmtpClient.Port = _Port;
// Provides credentials for
password-based authentication schemes such as basic, digest, NTLM, and Kerberos
authentication.
System.Net.NetworkCredential _NetworkCredential = new System.Net.NetworkCredential(_LoginName, _LoginPassword);
_SmtpClient.UseDefaultCredentials = false;
_SmtpClient.Credentials = _NetworkCredential;
_SmtpClient.EnableSsl = _EnableSsl;
//Let's send it
_SmtpClient.Send(_MailMessage);
// Do cleanup
_MailMessage.Dispose();
_SmtpClient = null;
//code for Deleting Atteched Files From
Folder
foreach (FileUpload file in lstFiles)
{
string path = HttpContext.Current.Server.MapPath("~/Quotes/MyFiles/" +file.fileName);
FileInfo files = new FileInfo(path);
if (files.Exists)//check file exsit or not
{
files.Delete();
}
}
}
catch (Exception _Exception)
{
// Error
throw _Exception;
}
return true;
}
0 comments:
Post a Comment