ASP.NET C# How to send mail with SMTP Authetication.

To send email from ASP.NET hosting account it is necessary to use credentials for smtp authentication.
Here is a way to do this with help function for sending mail.

private void sendEmail(string strTo, string strFrom,
string strSubject, string strBody, Attachment item, bool isHTML)
{

MailAddress maFrom = new MailAddress(strFrom, "sender");
MailAddress maTo = new MailAddress(strTo);
MailMessage mail = new MailMessage(maFrom, maTo);
mail.Attachments.Add(item);
mail.IsBodyHtml = isHTML;
mail.Subject = strSubject;
mail.Body = strBody;
SmtpClient sc = new SmtpClient();
System.Net.NetworkCredential basicAuthenticationInfo = new System.Net.NetworkCredential("email account", "password");

sc.Credentials = basicAuthenticationInfo;
sc.Host = "mail.xxxx.xxx";
sc.Port = 25;
sc.Send(mail);
}

Email account you can register with the hosting control panel (if you don't have already). The host is usually mail.+ domain name.

2 comments:


  1. Problem with that code is, it will wait until the receiver's sever will pick up the mail when your server is calling - since this may take 2 - 3 seconds your app seems to hang, if its a desktop app; if its a webapp, your page rendering/loading will seem to hang.
    Only solution is to make this an asynchron task:
    Either by sending the mail in a background thread (by encapsulating the smtp-mail-setup stuff in a class), or use some of the fancy MVC features to accomplish it.
    Regards

    ReplyDelete
  2. I basically agree.
    The advantage of the way above is the on time error handling. If the regular case includes only one recipient the delay should be pretty low.
    Having these facts in place the developer has to carefully consider the best way to handle that.

    ReplyDelete