Thursday, February 9, 2012

sending emails through c# asp.net

web.config entry

<system.net>
<mailSettings>
<smtp from="yoursenderemail@corporate.com">
<network host="hostname" port="25" password="Password"
userName="PASSPORT2" defaultCredentials="false" /> </smtp>
</mailSettings>
</system.net>

Note: 1) Make sure from address domain name
2) IP address, port number should be valid

c# code

SmtpSection mailSettings = ConfigurationManager.GetSection("system.net/mailSettings/smtp") as SmtpSection;
MailMessage MyMessage = new MailMessage();

string sendTo = this.txtEmailHard.Text;
string sendFrom = mailSettings.From;
string sendMessage = "hello now the time is : " + DateTime.Now.ToLongDateString();
MyMessage.To.Add(sendTo);
MyMessage.From = new MailAddress(sendFrom);
MyMessage.Subject = "Hi Welcome to eProfile";
MyMessage.Body = sendMessage;
MyMessage.IsBodyHtml = true;

this.lblComment.Text = mailSettings.Network.Host + " " + mailSettings.Network.Port;

SmtpClient emailClient = new SmtpClient(mailSettings.Network.Host, mailSettings.Network.Port);
if (mailSettings.Network.DefaultCredentials)
{
emailClient.UseDefaultCredentials = true;
}
else
{
emailClient.Credentials = new System.Net.NetworkCredential(mailSettings.Network.UserName, mailSettings.Network.Password);
}

emailClient.DeliveryMethod = SmtpDeliveryMethod.Network;
try
{
emailClient.Send(MyMessage);
return;
}
catch (SmtpException smtpx)
{
throw smtpx;
}
catch (Exception ex)
{
throw ex;
}

4 comments:

  1. The given program coding very very good and it is more helpful in my studies.
    Thanks for sharing that post.
    html5 training in chennai

    ReplyDelete
  2. Thank you for taking time to provide us this useful coding. This is really helpful for me in gaining my knowledge in a right way.
    Informatica Training in Chennai

    ReplyDelete
  3. Thank you for sharing such a nice and interesting blog with us. Hope it might be much useful for us. keep on updating...!!
    seo company in india
    digital marketing company in india

    ReplyDelete