SmtpClient-附件偶尔为0个字节

时间:2018-08-13 21:31:50

标签: c# asp.net email-attachments smtpclient memorystream

我有一个使用SmtpClient发送电子邮件的C#应用​​程序。电子邮件似乎都可以正常发送,但是在发送带有附件的电子邮件时,附件的周期为0字节。

我正在使用MemoryStream编写附件,并且将流游标显式设置为流的开头。

我正在使用gmails smtp服务器发送邮件。麻烦的是,有时附件发送正常,而其他时候附件为0字节。我也无法在测试时找到任何一致的模式。我将手动将5封分离的电子邮件全部发送到具有相同附件的相同电子邮件地址。随机只有1或2封电子邮件包含附件,其余均为0字节。

有猜到吗?这是我创建和发送邮件的代码段。

private void DispatchSmtpAsync(MessagePayload payload, IUnitOfWork unitOfWork)
    {
        MailMessage message = new MailMessage();
        SmtpClient client = new SmtpClient();

        foreach (EmailAddress recipient in payload.To)
            message.To.Add(new MailAddress(recipient.Email, recipient.Name));
        foreach (EmailAddress recipient in payload.Cc)
            message.CC.Add(new MailAddress(recipient.Email, recipient.Name));
        foreach (EmailAddress recipient in payload.Bcc)
            message.Bcc.Add(new MailAddress(recipient.Email, recipient.Name));

        foreach (MyApp.Services.Email.Common.Models.Attachment attachment in payload.Content.Attachments)
        {
            byte[] content = Convert.FromBase64String(attachment.Content);
            MemoryStream stream = new MemoryStream();
            stream.Seek(0, SeekOrigin.Begin);
            stream.Write(content, 0, content.Length);
            message.Attachments.Add(new System.Net.Mail.Attachment(stream, attachment.Name, MimeMapping.GetMimeMapping(attachment.Name)));
        }

        message.From = new MailAddress(payload.From.Email, payload.From.Name);
        message.Body = payload.Content.Html;
        message.Subject = payload.Content.Subject;
        message.IsBodyHtml = true;

        client.Host = unitOfWork.SystemSettingRepository.GetValue<string>(SystemSettingName.SmtpHost);
        client.Port = unitOfWork.SystemSettingRepository.GetValue<int>(SystemSettingName.SmtpPort);
        client.EnableSsl = unitOfWork.SystemSettingRepository.GetValue<bool>(SystemSettingName.SmtpSsl);
        client.Credentials = new NetworkCredential(unitOfWork.SystemSettingRepository.GetValue<string>(SystemSettingName.SmtpUsername),
                unitOfWork.SystemSettingRepository.GetValue<string>(SystemSettingName.SmtpPassword));

            client.SendAsync(message, Guid.NewGuid().ToString());
    } 

0 个答案:

没有答案