【发布时间】:2025-12-12 23:25:01
【问题描述】:
我正在尝试通过 .net 核心中的 SmtpClient 发送邮件。基本上我只是将一些旧的 .net 框架代码迁移到 .net 核心。在旧系统中,它是通过以下方式完成的:
using (var smtpClient = new SmtpClient("smtp.xyz.de", 587))
{
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = new System.Net.NetworkCredential("user", "password", "domain");
smtpClient.EnableSsl = true;
smtpClient.Send(mailMessage);
}
此代码运行良好。
现在我将此代码迁移到 .net 核心,如下所示:
using (var smtpClient = new SmtpClient("smtp.xyz.de", 587))
{
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = new NetworkCredential("user", "password", "domain");
smtpClient.EnableSsl = true;
smtpClient.Send(mailMessage);
}
第一个问题是现在我收到一条错误消息:
输入不是有效的 Base-64 字符串,因为它包含非 base 64 字符、两个以上的填充字符或填充字符中的非法字符。
堆栈跟踪:
at System.Convert.FromBase64CharPtr(Char* inputPtr, Int32 inputLength)
at System.Convert.FromBase64String(String s)
at System.Net.Mail.SmtpNegotiateAuthenticationModule.GetSecurityLayerOutgoingBlob(String challenge, NTAuthentication clientContext)
at System.Net.Mail.SmtpNegotiateAuthenticationModule.Authenticate(String challenge, NetworkCredential credential, Object sessionCookie, String spn, ChannelBinding channelBindingToken)
at System.Net.Mail.SmtpConnection.GetConnection(String host, Int32 port)
at System.Net.Mail.SmtpTransport.GetConnection(String host, Int32 port)
at System.Net.Mail.SmtpClient.GetConnection()
at System.Net.Mail.SmtpClient.Send(MailMessage message)
由于该错误,我尝试将用户和密码字符串转换为 Base64,如下所示:
using (var smtpClient = new SmtpClient("smtp.xyz.de", 587))
{
var userEncoded = Convert.ToBase64String(Encoding.UTF8.GetBytes("user"));
var passwordEncoded = convert.ToBase64String(Encoding.UTF8.GetBytes("password"));
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = new NetworkCredential(userEncoded, passwordEncoded, "domain");
smtpClient.EnableSsl = true;
smtpClient.Send(mailMessage);
}
这样做我得到另一个错误:
SMTP 服务器需要安全连接或客户端未通过身份验证。服务器响应为:5.7.1 客户端未通过身份验证
堆栈跟踪:
at System.Net.Mail.MailCommand.CheckResponse(SmtpStatusCode statusCode, String response)
at System.Net.Mail.MailCommand.Send(SmtpConnection conn, Byte[] command, MailAddress from, Boolean allowUnicode)
at System.Net.Mail.SmtpTransport.SendMail(MailAddress sender, MailAddressCollection recipients, String deliveryNotify, Boolean allowUnicode, SmtpFailedRecipientException& exception)
at System.Net.Mail.SmtpClient.Send(MailMessage message)
at MailTest.Program.ProgramStart() in C:\Repos\MailTest\MailTest\Program.cs:line 67
MailMessage 对象的创建:
mailMessage = new MailMessage("sender@xyz.com", "recipient@xyz.com", "subject", "body");
谁能弄清楚我做错了什么?对我来说,除了转换为 Base64 之外,代码看起来完全一样。
【问题讨论】:
-
第一个错误的堆栈跟踪是什么?
-
您没有转换用户名和密码。它们会使用 NetworkCredentials 自动安全发送。
-
我在帖子中添加了堆栈跟踪
-
@jdweng 但后来我收到有关 Base64 字符串的错误
-
先发个简单的短信看看能不能用。该错误表明 MailMessage 对象有问题。需要看代码。您是在发送 HTML 消息还是文本消息。你有附件吗?消息的 mrom 地址和 SMTP 凭据必须匹配(从 3.5 更改为 4.0)。 HTML 有特殊字符。 Base64 字符串表示您将文本添加到具有 html 特殊字符的消息中。见维基:en.wikipedia.org/wiki/…
标签: c# .net .net-core smtp smtpclient