Use SmtpClient to send mail

  • 2020-05-09 19:09:03
  • OfStack

The procedure goes like this:


static void Main(string[] args)
{
    SmtpClient client = new SmtpClient();
    client.Host = "localhost";

    MailAddress from = new MailAddress("from@test.com");
    MailAddress to = new MailAddress("to@test.com");
    MailMessage message = new MailMessage(from, to);

    client.Send(message);

    Console.ReadLine();
}

When run, "unable to connect due to active rejection of target computer." The error. Check 1 and it is said that SMTP service is not started. So I found the setting method on the Internet, control panel - > program and function - > open or close Windows function - > Internet information service - b> application development function - >.NET extensibility, check this 1 item. The SMTP E-mail item will then appear in the IIS manager. After trying to make the relevant Settings in it, the result is still the same error.

After another study, IIS7 in Windows 7 has removed the SMTP service, so no matter how you set it up, it is useless. (there is a related discussion here.)

The solution is to install party 3's SMTP server. Like the free Free SMTP Server.

After the installation without any Settings, start SMTP server, and then run the above program, 1 cut normal.

If you want to use 3rd party SMTP servers such as netease to send mail, it's also easy. Slightly modified code:


static void Main(string[] args)
{
    SmtpClient client = new SmtpClient();
    client.Host = "smtp.163.com";
    client.Credentials = new NetworkCredential("usenme", "password");// You must set up 

    MailAddress from = new MailAddress("from@163.com");
    MailAddress to = new MailAddress("to@test.com");
    MailMessage message = new MailMessage(from, to);

    client.Send(message);

    Console.ReadLine();
}

This attempt took a long time and hopefully others will find this article helpful.


Related articles: