C system.net.mail example
Here is an example of using the System.Net.Mail
namespace in C# to send an email:
using System;
using System.Net.Mail;
using System.Net;
class Program
{
static void Main()
{
// Create a new MailMessage object.
MailMessage mail = new MailMessage();
// Set the sender's email address, name, and email client.
mail.From = new MailAddress("[email protected]", "Sender Name");
// Set the recipient's email address and name.
mail.To.Add(new MailAddress("[email protected]", "Recipient Name"));
// Set the subject line.
mail.Subject = "Test email from C#";
// Set the email body.
mail.Body = "This is a test email sent from C#.";
// Set the email body format.
mail.IsBodyHtml = true;
// 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 credentials.
client.Credentials = new NetworkCredential("username", "password");
// Send the email.
client.Send(mail);
}
}
In this example, we create a new MailMessage
object and set its properties such as the sender's email address, recipient's email address, subject line, and email body. We also set the email body format to HTML.
Next, we create a new SmtpClient
object and set its properties such as the SMTP server's address, port, and credentials. Finally, we use the Send
method of the SmtpClient
object to send the email.
Note that you need to replace the placeholders ("[email protected]"
, "[email protected]"
, "smtp.example.com"
, "username"
, and "password"
) with your actual email address, recipient's email address, SMTP server's address, and credentials.
Also, make sure to handle any exceptions that may occur during the email sending process.