Windows Form project, sending e-mail error in C#

Gennady Gurin 166 Reputation points
2025-06-24T02:32:54.5733333+00:00

Hi, I tried several things sending email pragmatically, but get an error:

enter image description here

code here:

using System.Net;

using System.Net.Mail;

private void SendEmailOutlook(string toAddress, string fromAddress, string subject, string messageText, bool isHtmlMessage, string username, string password)

{

MailAddress from = new MailAddress(fromAddress);

using (SmtpClient client = new SmtpClient("smtp.gmail.com",465) { DeliveryMethod = SmtpDeliveryMethod.Network, EnableSsl = true, UseDefaultCredentials = false })

{

    client.Credentials = new System.Net.NetworkCredential(username, password);

    MailAddress to = new MailAddress(toAddress);

    using (MailMessage message = new MailMessage(from, to) { IsBodyHtml = isHtmlMessage })

    {

        message.Subject = subject;

        message.Body = messageText;

        try { client.Send(message); } catch (Exception ex) { MessageBox.Show(ex.ToString()); }

    }

}

}

and then I call it:

SendEmailOutlook(target-email,"******@gmail.com", "subject text", " message text", false, "my-email-gmail.com", "My-Password");

Anyone can help me to figure this out.

Thanks.

Developer technologies C#
0 comments No comments
{count} votes

Accepted answer
  1. Castorix31 90,521 Reputation points
    2025-06-25T12:01:56.2966667+00:00

    I had done a test app in WinUI 3 C# to test various methods to send mails : https://github.com/castorix/WinUI3_SendMail/tree/master

    (same code as in WinForms, except for GUI)

    I just re-tested with a gmail account and it worked with Net.Mail method, but by using an App Password (https://myaccount.google.com/apppasswords) instead of account password and 587 port

    1 person found this answer helpful.

2 additional answers

Sort by: Most helpful
  1. mudinaman143 0 Reputation points
    2025-06-24T02:38:15.3966667+00:00

    ✅ Solution:

    1. Ensure your SMTP client is configured correctly:
      
         using System.Net.Mail;
      
         var client = new SmtpClient("smtp.yourserver.com");
      
         client.Port = 587; // Or 25/465 depending on your server
      
         client.Credentials = new NetworkCredential("username", "password");
      
         client.EnableSsl = true;
      

  2. Bruce (SqlWork.com) 77,686 Reputation points Volunteer Moderator
    2025-06-24T15:23:12.7066667+00:00

    It appears you may be trying to use office 365 to send mail. The SmtpClient does not support modern authentication required office or google mail. You will need to pick a different email library.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.