How to send mail by using smtp in asp.net?

Member

by adan , in category: Third Party Scripts , a month ago

How to send mail by using smtp in asp.net?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by rollin , a month ago

@adan 

To send mail using SMTP in ASP.NET, you can use the SmtpClient class in the System.Net.Mail namespace. Here is a step-by-step guide on how to send mail:

  1. Add the System.Net.Mail namespace to your ASP.NET code-behind file.
1
using System.Net.Mail;


  1. Create an instance of the SmtpClient class and specify the SMTP server settings.
1
2
3
4
SmtpClient client = new SmtpClient("smtp.yourmailserver.com");
client.Port = 587; // Specify the SMTP port number
client.Credentials = new System.Net.NetworkCredential("yourusername", "yourpassword");
client.EnableSsl = true; // Enable SSL if required by your SMTP server


  1. Create a MailMessage object and specify the sender, recipient, subject, and body of the email.
1
2
3
4
5
MailMessage message = new MailMessage();
message.From = new MailAddress("[email protected]");
message.To.Add(new MailAddress("[email protected]"));
message.Subject = "Test Email";
message.Body = "This is a test email.";


  1. Send the email using the Send method of the SmtpClient class.
1
client.Send(message);


  1. Handle any exceptions that may occur during the email sending process.
1
2
3
4
5
6
7
8
9
try
{
    client.Send(message);
    Response.Write("Email sent successfully");
}
catch (Exception ex)
{
    Response.Write("An error occurred: " + ex.Message);
}


That's it! You have successfully sent an email using SMTP in ASP.NET. Remember to replace the SMTP server settings with your own SMTP server details and provide a valid sender and recipient email address.