项目中需要使用邮件功能,使用内置的System.Net.Mail.SmtpClient模块发送邮件时,无论使用126邮箱还是QQ邮箱,均报以下错误System.IO.IOException: Unable to read data from the transport connection: The connection was closed.
。参考相关资料,可能的原因是相关邮箱的加密协议已经更新,但是.net内置库不支持,为了解决这一问题,可以使用第三方库例如MailKit
等。以下以MailKit为例。
首先,在目前国内的邮箱中,要使用客户端,均需要申请授权码,而不应该使用邮箱密码,详见常用邮箱客户端设置指南。
使用VS Code时,使用dotnet new console -n EmailSenderApp
在命令行创建一个新项目,并cd EmaiSenderApp
。使用code .
打开VS code。
使用dotnet add package MailKit
安装MailKit包。
在Program.cs文件中,添加引用,分别创建Email,EmailSender类,并调用进行测试。
using System;
using MailKit.Net.Smtp;
using MimeKit;
public class Email
{
public string RecipientEmail { get; set; }
public string Subject { get; set; }
public string Body { get; set; }
public Email(string recipientEmail, string subject, string body)
{
RecipientEmail = recipientEmail;
Subject = subject;
Body = body;
}
}
public class EmailSender
{
private readonly string _smtpServer;
private readonly int _smtpPort;
private readonly string _senderEmail;
private readonly string _senderPassword;
public EmailSender(string smtpServer, int smtpPort, string senderEmail, string senderPassword)
{
_smtpServer = smtpServer;
_smtpPort = smtpPort;
_senderEmail = senderEmail;
_senderPassword = senderPassword;
}
public void SendEmail(Email email)
{
var message = new MimeMessage();
message.From.Add(new MailboxAddress("John",_senderEmail));
message.To.Add(new MailboxAddress("",email.RecipientEmail));
message.Subject = email.Subject;
message.Body = new TextPart("plain") { Text = email.Body };
using (var client = new SmtpClient())
{
client.Connect(_smtpServer, _smtpPort, true);
client.Authenticate(_senderEmail, _senderPassword);
client.Send(message);
client.Disconnect(true);
}
}
}
public class Program
{
public static void Main()
{
var email = new Email("target email", "Test Subject", "Test Email Body");
var sender = new EmailSender("smtp.qq.com", 465, "email account", "password");
sender.SendEmail(email);
Console.WriteLine("Email sent using MailKit!");
}
}
修改以上代码中收发邮件相关内容,运行dotnet run
。可以测试邮件已成功发送。