Send email in C#

  • 146 Views
  • Last Post 06 May 2020
sameh posted this 26 April 2020

hello every body i need to send a Email by C# windows forms

but the user type email in textbox and message <"without typeing email password ">

lucy posted this 06 May 2020

You can use this code

public Task SendEmailAsync(string email, string subject, string htmlMessage)
{
    var credentials = new NetworkCredential(_configuration.GetValue<string>("Smtp:UserName"), _configuration.GetValue<string>("Smtpassword"));
    var mail = new MailMessage()
    {
        From = new MailAddress(_configuration.GetValue<string>("Smtp:UserName")),
        Subject = subject,
        Body = htmlMessage,
    };
    mail.IsBodyHtml = true;
    mail.To.Add(new MailAddress(email));
    using var client = new SmtpClient()
    {
        Port = 587,
        DeliveryMethod = SmtpDeliveryMethod.Network,
        UseDefaultCredentials = false,
        Host = _configuration.GetValue<string>("Smtp:Server"),
        EnableSsl = true,
        Credentials = credentials
    };
    return client.SendMailAsync(mail);
}

You should create a configuration file, then add port, smtp server, email, password.

From your windows forms, only need email textbox, title textbox, message textbox.

Close