How to send email in ASP.Net

less than 1 minute read

You have to configure SMTP server before sending email from your server. Hope you already know how to configure smtp server. Here is the simple code segment for sending email against a button click.

protected void btnSendMail_Click(object sender, EventArgs e)
      SmtpClient smtpClient = new SmtpClient();
      MailAddress fromAddress = new MailAddress(""); //Sender email address
      MailMessage _mail = new MailMessage();
     _mail.Attachments.Add(new Attachment(@"E:\Temp\attachment.pdf")); //Add dirctory of attachment
     //bool IsSuccess = false;
      _mail.From = fromAddress;
      _mail.To.Add(""); //Receiver email address
      _mail.CC.Add(""); //Email address for cc
      _mail.Bcc.Add(""); //Email address for bcc
      _mail.Subject = "Test Message"; //Email subject
      _mail.Body = "Dear concern, This is the test message from Mahedee"; //Email body
      _mail.IsBodyHtml = true; //Email body is in html format
       smtpClient.Host = ""; //Name or IP address of the host used for SMTP transaction
       smtpClient.EnableSsl = false;
       //smtpClient.Port = 25; //25 is default port for smtp. You have to change port no if it is not used defualt         port
      smtpClient.Send(_mail); //Send mail
      //IsSuccess = true;
    catch (Exception ex)
       //IsSuccess = false;