Send email in c#

Here is an example of how to send an email using C#:

using System.Net.Mail;

// 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 C#";

// Create a new SmtpClient object
SmtpClient client = new SmtpClient();

// Set the SMTP server's address and port
client.Host = "smtp.example.com";
client.Port = 587;

// Set the SMTP server's username and password
client.Credentials = new NetworkCredential("your_smtp_username", "your_smtp_password");

// Send the email
client.Send(mail);

This code uses the System.Net.Mail namespace to create a new MailMessage object, which represents the email to be sent. The MailMessage object has properties for the sender's email address, the recipient's email address, the subject of the email, and the body of the email.

The code then creates a new SmtpClient object, which is used to send the email. The SmtpClient object has properties for the SMTP server's address and port, as well as the username and password for the SMTP server.

Finally, the code calls the Send method of the SmtpClient object to send the email.

You can also use the MailMessage class to attach files to the email, set the priority of the email, and specify the format of the email.

Here is an example of how to attach a file to the email:

// Create a new attachment
Attachment attachment = new Attachment("path/to/file.txt");

// Add the attachment to the email
mail.Attachments.Add(attachment);

And here is an example of how to set the priority of the email:

// Set the priority of the email
mail.Priority = MailPriority.High;

And here is an example of how to specify the format of the email:

// Set the format of the email
mail.IsBodyHtml = true;

You can also use the SmtpClient class to send emails asynchronously, by using the SendAsync method:

// Send the email asynchronously
client.SendAsync(mail, null);

This method returns a Task object that represents the asynchronous operation. You can use the Wait method to wait for the operation to complete:

// Wait for the email to be sent
client.SendAsync(mail, null).Wait();

Note that the SmtpClient class is not thread-safe, so you should not use it in a multi-threaded environment without taking proper synchronization measures.