Sending email in ASP.NET
Many times I tried to send an email through .net. Although there are many posts still contains to send an email through .net. But in this article I have created a class which have differenet methods like getSMTPInfo() and MailConfiguration(string to, string from, string cc, string bcc) and SendMail(string subject, string emailBody)
Let me explains you what these methods does.
/// <summary>
/// This Method gets the all SMTP Information
/// </summary>
GetSMTPInfo()
{
System.Collections.Hashtable section;
System.Collections.IDictionaryEnumerator
enumerator;
try
{
section = (System.Collections.Hashtable)
ConfigurationManager.GetSection("ReportsEmail/SMTP");
enumerator = section.GetEnumerator();
while (enumerator.MoveNext())
{
if (enumerator.Entry.Key.ToString() ==
"Host")
{
SMTPHost = enumerator.Entry.Value.ToString();
}
else if (enumerator.Entry.Key.ToString()
== "Port")
{
if (enumerator.Entry.Value.ToString() !=
"")
{
int.TryParse(enumerator.Entry.Value.ToString(),
out port);
}
}
else if (enumerator.Entry.Key.ToString()
== "UserName")
{
smtpuser = enumerator.Entry.Value.ToString();
}
else if (enumerator.Entry.Key.ToString()
== "Password")
{
smtppass = enumerator.Entry.Value.ToString();
}
else
if (enumerator.Entry.Key.ToString() ==
"EnableSSL") {
int value = 0;
int.TryParse(enumerator.Entry.Value.ToString(),
out value);
if (value == 1)
enablessl
= true;
else
enablessl = false;
}
}
if (message.To.Count < 1)
{
return;
}
message.From =
new MailAddress(this.from);
if (this.cc !=
"")
{
string[] multipleMailArraycc =
this.cc.Split(',');
if (multipleMailArraycc !=
null && multipleMailArraycc.Length > 0)
{
for (int z = 0; z <
multipleMailArraycc.Length; z++)
{
if (multipleMailArraycc[z].Trim() !=
"")Z
{
message.CC.Add(multipleMailArraycc[z].Trim());
}
}
}
if (this.bcc !=
"")
{
string[] multiplebcc =
this.bcc.Split(',');
if
(multiplebcc != null && multiplebcc.Length > 0)
{
for (int z = 0; z <
multiplebcc.Length; z++)
{
if (multiplebcc[z].Trim() !=
"")
{
message.Bcc.Add(multiplebcc[z].Trim());
}
}
}
}
//message.To.Add(this.to);
//message.From = new MailAddress(this.from);
//if (this.cc != "") message.CC.Add(this.cc);
//if (this.bcc != "") message.Bcc.Add(this.bcc);
message.Subject = subject;
message.IsBodyHtml = true;
message.Body =
emailBody;
SmtpClient mailClient =
new SmtpClient(this.SMTPHost);
if (this.port >
0)
{
mailClient.Port = this.port;
}
if (this.isDefaultCredential
== false)
{
mailClient.UseDefaultCredentials = false;
mailClient.Credentials = basicAuthenticationInfo;
}
else
{
mailClient.UseDefaultCredentials = true;
}
}
catch (Exception
ex)
{
throw ex;
}
}

Join the conversation! Your thoughts help the community grow.