Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

Recently, the server kept restarting automatically because of insufficient resources or some other reasons. After the restart, some services did not automatically run, leading to some abnormal system data. In order to ensure normal monitoring, boss asked him to send an email to the data of the day before leaving work every day. Up to now, you need to add mail to the data computing service. Without saying a word, I started to do it. As an old programmer, I wrote SmtpClient directly before and this time was no exception. However, I never expected that When I opened this, I found that Microsoft had abandoned SmtpClient.

Fortunately, Microsoft recommended MailKit as its successor. Now that Microsoft recommends it, it’s time to update it.

Mailkit is an open source project and the author’s goal is to make it the best email framework for.NET. It supports SMTP, POP3, and IMAP protocols. Github.com/jstedfast/M…

Configure your email

Since SMTP needs to be enabled to send emails, I will directly use my QQ mailbox. The qq email Settings – account – POP3 / IMAP/SMTP/Exchange/CardDAV/CalDAV service under open an SMTP server and the IMAP/POP3 / SMTP service, I have opened here don’t open, the method of the open it step by step, according to the prompt.

Install Mailkit

1, directly install with Nuget command

Install-Package MailKit

2. You can also search in the Nuget solution and select the corresponding installation

Code implementation

The code implementation is simple

public void SendEmail() { MimeMessage message = new MimeMessage(); Message.from.add (new MailboxAddress(" BC Xiaoping ", "[email protected]")); Message.to. Add(new MailboxAddress("boss", "[email protected]")); // header message.Subject = "test header "; TextPart body = new TextPart(textFormat.html) {Text = "<h1> Test content </h1>"}; // Create Multipart add attachment Multipart Multipart = new Multipart("mixed"); multipart.Add(body); // message.Body = multipart; Using (SmtpClient client = new SmtpClient()) {//Smtp server client.connect ("smtp.qq.com", 587, false); Authenticate("[email protected]", "XXX "); // Login client.authenticate ("[email protected]"," XXX "); / / Send the client. The Send (message); / / Disconnect client. Disconnect (true); Console.WriteLine(" Email sent successfully "); }}Copy the code

Local test ok.

After deploying the server, the server works normally. Please open port 587.