Asp.net send mail function using smtp authemtication
Here is an example of how to send an email using ASP.NET and SMTP authentication:
using System.Net.Mail;
using System.Net;
// Create a new MailMessage object
MailMessage mail = new MailMessage();
// Set the sender's email address
mail.From = new MailAddress("[email protected]");
// Set the recipient's email address
mail.To.Add("[email protected]");
// Set the subject of the email
mail.Subject = "Test Email";
// Set the body of the email
mail.Body = "This is a test email sent using ASP.NET and SMTP authentication.";
// Create a new SmtpClient object
SmtpClient client = new SmtpClient();
// Set the SMTP server and port
client.Host = "your_smtp_server";
client.Port = 587; // or 25, depending on your SMTP server
// Set the SMTP username and password
client.Credentials = new NetworkCredential("your_smtp_username", "your_smtp_password");
// Send the email
client.Send(mail);
Make sure to replace the placeholders with your actual email addresses, SMTP server, and credentials.
You can also use the MailMessage
class to send HTML emails by setting the IsBodyHtml
property to true
and the Body
property to an HTML string:
mail.IsBodyHtml = true;
mail.Body = "<html><body>This is an HTML email sent using ASP.NET and SMTP authentication.</body></html>";
You can also use the MailMessage
class to send attachments by adding a Attachment
object to the Attachments
collection:
Attachment attachment = new Attachment("path/to/attachment.txt");
mail.Attachments.Add(attachment);
It's also important to note that you should handle any exceptions that may occur when sending the email, such as network errors or authentication failures. You can do this by wrapping the client.Send(mail)
call in a try-catch block:
try
{
client.Send(mail);
}
catch (SmtpException ex)
{
// Handle the exception
Console.WriteLine("Error sending email: " + ex.Message);
}