How to send mail using system.net.mail

using System.Net.Mail;
using System.Net.Mime;


    protected bool SendMail()
    {
        string objFrom, objSubject, objTo;
        objFrom = "username@domai.com"; //sender mail id
        objSubject = "subject"; //subject of mail
        objTo = objEmail;
        SmtpClient smtpClient = new SmtpClient();
        MailMessage message = new MailMessage();
        MailAddress fromAddress = new MailAddress(objFrom, objSubject);
        smtpClient.Host = ConfigurationManager.AppSettings["HostName"].ToString(); ;
        smtpClient.Port = System.Convert.ToInt32(ConfigurationManager.AppSettings["Port"].ToString());
        message.From = fromAddress;
        message.IsBodyHtml = true;
        message.Subject = objSubject;
       
        // Mail Template(Use this code for send html file as mail)
        System.IO.StreamReader fs = new System.IO.StreamReader(Server.MapPath("~/folder/Mailer.htm"));
        StringBuilder sbMailerTemplate = new StringBuilder();
        sbMailerTemplate.Append(fs.ReadToEnd());
        fs.Dispose();
        //template end

        AlternateView av1 = AlternateView.CreateAlternateViewFromString(sbMailerTemplate, null, MediaTypeNames.Text.Html);
        message.AlternateViews.Add(av1);

        smtpClient.UseDefaultCredentials = false;
        smtpClient.Credentials = new System.Net.NetworkCredential(ConfigurationManager.AppSettings["Username"].ToString(), ConfigurationManager.AppSettings["UserPass"].ToString());
        //user Email to be send
        message.To.Add(objTo);
        try
        {
            smtpClient.Send(message);
            return true;
        }
        catch (Exception ex)
        {
            this.lblMessage.Visible = true;
            this.lblMessage.Text = ex.Message;
            return false;
        }



    }


    //web config settings

   
  <appSettings>
    <add key="HostName" value="mail.servername.com"/>
    <add key="Port" value="25"/>
    <add key="EmailFrom" value="username@domain.com"/>
    <add key="Username" value="username@domain.com"/>
    <add key="UserPass" value="password"/>
  </appSettings>
    <system.net>
    <mailSettings>
      <smtp>
        <network host="mail.servername.com" port="25" userName="username" password="password"/>
      </smtp>
    </mailSettings>
  </system.net>

Previous
Next Post »
Thanks for your comment