send an email in csharp

To send an email in C#, we need to use the SmtpClient class provided by the System.Net.Mail namespace. We can create an instance of the MailMessage class to create our email message and populate it with the necessary information.

Here's an example code snippet that demonstrates how to send an email using C#:

main.cs
using System.Net;
using System.Net.Mail;

public void SendEmail(string toEmail, string subject, string body)
{
    string fromEmail = "sender@example.com"; // Replace with your own email address
    string password = "yourpassword"; // Replace with your own email password

    MailMessage mail = new MailMessage(fromEmail, toEmail, subject, body);

    SmtpClient client = new SmtpClient("smtp.gmail.com", 587);
    client.EnableSsl = true;
    client.UseDefaultCredentials = false;
    client.Credentials = new NetworkCredential(fromEmail, password);

    try
    {
        client.Send(mail);
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
}
679 chars
25 lines

In the above code, we create a new MailMessage object with the toEmail, subject, and body parameters. We then create a new SmtpClient object with the smtp.gmail.com server and port 587. We set the EnableSsl property to true to enable secure SSL connections and provide our login credentials using the NetworkCredential class. Finally, we call the Send() method of the SmtpClient object to send the email.

You can replace the 'smtp.gmail.com' with your email service provider's SMTP server details. Note that some email service providers may require additional configuration or authentication.

related categories

gistlibby LogSnag