Welcome to deBUG.to Community where you can ask questions and receive answers from Microsoft MVPs and other experts in our community.
0 like 0 dislike
1.3k views
in Programming by 66 69 85
I am using C# .NET 5 and would like to send an email to some address with a subject, a body and an attachment. Also, the body needs to be in HTML format.

I tried sending an email using the `System.Net.Mail` namespace, so any help here would be appreciated.

1 Answer

0 like 0 dislike
by 66 69 85
edited by

How To Send Email using SMTP in Csharp

Prerequisites:

  1. having an SMTP server.
  2. Get the hostname and port of the SMTP server.
  3. make sure the port is open to your server or computer.
  4. Finally email address to send the masse from it.

Check if the port is open

You can check the port from CMD by writing the following command.

Syntax:

telnet SMTPserver port

Example:

telnet mail.outlook 25

if a new window opened then you can connect.

Send Email in Csharp

You can send an email by using C#l in the code below.

         MailMessage message = new MailMessage();
        SmtpClient smtpClient = new SmtpClient();

       // Emaill details 
        message.From = new MailAddress("info@yourDomain");
        message.To.Add(new MailAddress("mohammed@yourDomain"));
        message.Subject = "SEND EMAIL FROM Csharp";
        message.IsBodyHtml = true;
        message.Body = "<b>Hello</b>";

        // setup smtp
        smtpClient.Port = 578;
        smtpClient.Host = "SMTPserver";
        smtpClient.EnableSsl = false;
        smtpClient.UseDefaultCredentials = true;  // if you need to use credentials set to false then write below line
        //smtpClient.Credentials = new NetworkCredential("username", "password");
        smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
        smtpClient.Send(message); // send Email

See also The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.1 Client was not authenticated

If you don’t ask, the answer is always NO!
...