Send mail c#
Here is an example of how to send an email using C#:
Using the System.Net.Mail
namespace
You can use the System.Net.Mail
namespace to send an email. Here is an example:
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";
// 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 username and password for the SMTP server
client.Credentials = new NetworkCredential("username", "password");
// Send the email
client.Send(mail);
Using the System.Net.Mail.SmtpClient
class
You can also use the SmtpClient
class to send an email. Here is an example:
using System.Net.Mail;
// 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 username and password for the SMTP server
client.Credentials = new NetworkCredential("username", "password");
// 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";
// Send the email
client.Send(mail);
Using a third-party library
There are also third-party libraries available that can help you send emails in C#. For example, you can use the MailKit
library, which provides a more modern and flexible way of sending emails.
Here is an example of how to send an email using MailKit
:
using MailKit.Net.Smtp;
using MailKit.Security;
using MailKit.Net.Smtp;
// Create a new SmtpClient object
SmtpClient client = new SmtpClient();
// Set the SMTP server's address and port
client.Connect("smtp.example.com", 587, SecureSocketOptions.StartTls);
// Set the username and password for the SMTP server
client.Authenticate("username", "password");
// 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";
// Send the email
client.Send(mail);
Note that you will need to install the MailKit
NuGet package in your project in order to use this library.