我正在使用 System.Net.Mail 库在 C# 中发送电子邮件。我想以某种方式检查消息未发送的情况,因为消息太大。这是我为说明问题而编写的示例代码:
internal class Program
{
private static void Main()
{
var client = new SmtpClient();
try
{
var mail = new MailMessage();
mail.From = new MailAddress("<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e093858e848592a08d81898cce838f8d" rel="noreferrer noopener nofollow">[email protected]</a>");
mail.To.Add(new MailAddress("<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d1a3b4b2b8a1b8b4bfa591bcb0b8bdffb2bebc" rel="noreferrer noopener nofollow">[email protected]</a>"));
mail.Subject = "Mail Subject";
mail.Body = "Mail Body";
mail.Attachments.Add(CreateAttachment());
var smtpClient = new SmtpClient("SomeHost", 25)
{
EnableSsl = false,
Credentials = new NetworkCredential("username", "password"),
};
smtpClient.Send(mail);
}
catch (SmtpException e)
{
// somehow verify that this exception happened because exceeding message size
Console.WriteLine("Message was not sent because it was to big"); ;
}
}
// This method generates an attachment that exceed maximum size allowed by the server
private static Attachment CreateAttachment()
{
var str = "Some message\n";
var superBigMessage = new System.Text.StringBuilder();
for (int i = 0; i < 10000000; i++)
{
superBigMessage.Append(str);
}
return Attachment.CreateAttachmentFromString(superBigMessage.ToString(), "Attachment.txt");
}
}
我想提一下,SmtpException
上有一个名为 StatusCode
的属性,但它无法提供必要的洞察,以防消息太大 StatusCode = TransactionFailed
并且异常消息显示交易失败。服务器响应为:已拒绝 - 消息大小超出固定的最大消息大小。大小:147442 KB,最大大小:20480 KB
最佳答案
您的 MTA 如何处理“太大”以及如何报告该情况取决于 MTA。不同的 MTA 可能具有完全不同的消息。 SMTP
中没有任何内容标准化“太大”。
因此您需要解析消息,并准备好在 MTA 发生更改(包括软件升级和配置更改)时进行更新。
关于c# - 使用 System.Net.Mail 发送电子邮件时如何捕获邮件大小太大异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48943228/