使用System.Net.Mail发送电子邮件时如何捕获邮件大小太大的异常?

时间:2018-02-23 07:37:06

标签: c# exception-handling smtpclient system.net.mail

我正在使用System.Net.Mail库在C#中发送电子邮件。我想以某种方式检查没有发送消息的情况,因为它太大了。这是我编写的示例代码,用于说明问题:

internal class Program
{
    private static void Main()
    {
        var client = new SmtpClient();
        try
        {
            var mail = new MailMessage();
            mail.From = new MailAddress("sender@mail.com");
            mail.To.Add(new MailAddress("recipient@mail.com"));
            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并且它没有提供必要的见解异常消息显示Transaction failed. The server response was: Rejected - Message size exceeds fixed maximum message size. Size: 147442 KB, Max size: 20480 KB

1 个答案:

答案 0 :(得分:2)

您的MTA如何处理“太大”以及它如何报告它取决于该MTA。不同的MTA可能会有完全不同的消息。 SMTP中没有任何内容标准化“太大”。

因此,您需要解析消息,并准备好在MTA更改(包括软件升级和配置更改)时进行更新。

相关问题