You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#使用MimeKit发邮件报错Invalid addr-spec token at offset 0解决方法

C# 用MimeKit发邮件报Invalid addr-spec token at offset 0的解决方法

我在C#中使用如下MimeKit代码发送邮件:

var message = new MimeMessage();
message.From.Add(new MailboxAddress(FromAddress, "Notification"));
            

foreach (var address in Toaddress.Split(','))
{
  message.To.Add(new MailboxAddress(address.Trim(), ""));
}
message.Subject = Subject;

message.Body = new TextPart("plain") { Text = "Test Message" };

using (var client = new SmtpClient())
{
   client.Connect(EmailHostName, Portnumber, SecureSocketOptions.StartTls);
   client.Authenticate(UserName, Password);

   client.Send(message);
   client.Disconnect(true);
}

运行时抛出如下异常:

MimeKit.ParseException: Invalid addr-spec token at offset 0
   at MimeKit.InternetAddress.TryParseAddrspec(Byte[] text, Int32& index, Int32 endIndex, Byte[] sentinels, Boolean throwOnError, String& addrspec, Int32& at)
   at MimeKit.MailboxAddress.set_Address(String value)
   at MimeKit.MailboxAddress..ctor(Encoding encoding, String name, String address)
   at MimeKit.MailboxAddress..ctor(String name, String address)

我已尝试多种网上公开的解决方案均未生效。

问题定位及解决方案

该报错是因为MailboxAddress构造函数的参数顺序填写错误,MailboxAddress的两个入参顺序是:第一个为邮箱显示名称,第二个为实际邮箱地址。
原代码中的写法message.From.Add(new MailboxAddress(FromAddress, "Notification"));把两个参数填反了,MimeKit尝试将字符串"Notification"解析为邮箱地址,自然会解析失败抛出异常。

修改为如下写法即可解决:

message.From.Add(new MailboxAddress("Notification", FromAddress));

另外注意收件人添加的逻辑同理,如果需要给收件人设置显示名称,第一个参数填显示名,第二个填实际邮箱地址即可,不要把顺序写反。


内容的提问来源于stack exchange,提问作者Rajesh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 20:06:04