【问题标题】:Email sending with attachment issue带有附件问题的电子邮件发送
【发布时间】:2018-06-13 16:59:08
【问题描述】:

我正在尝试向不同的用户发送电子邮件(带有附件)。正在发送电子邮件,但只有一位用户收到附件(图像文件)。其他收件人收到类似空图片或名称和零字节的图片。

我真的不明白出了什么问题。这是我用于发送电子邮件的代码:

public void SendWithFile(string recipientName, string body, string subject = null, HttpPostedFileBase emailFile = null)
{
    using (var msg = new MailMessage())
    {
        msg.To.Add(recipientName);
        msg.From = new MailAddress(ConfigurationManager.AppSettings["MailServerSenderAdress"]);
        msg.Subject = subject;
        msg.Body = body;
        msg.SubjectEncoding = Encoding.UTF8;
        msg.BodyEncoding = Encoding.UTF8;
        msg.IsBodyHtml = true;
        msg.Priority = MailPriority.Normal;

        using (Attachment data = new Attachment(emailFile.InputStream, Path.GetFileName(emailFile.FileName), emailFile.ContentType))
        {
            msg.Attachments.Add(data);

            using (var client = new SmtpClient())
            {
                //client configs
                try
                {
                    client.Send(msg);
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
        }
    }
}

这里是我调用发送电子邮件方法的地方:

foreach (var recipent in notesRecipients)
{
   if (!string.IsNullOrEmpty(userEmail))
   {
       if (emailFile != null)
          emailService.SendWithFile(userEmail, message, null, emailFile);
    }
}

【问题讨论】:

  • 您几乎可以肯定在第一个接收者上将流读取到末尾,然后后续读取将获得 0 字节。您要么需要在调用 Send 后将流返回到开头,要么缓冲数据。
  • 是的,你是对的,在 foreach 循环的下一阶段 HttpPostedFileBase 的 ContentLength 为 0。我如何寻找流?谢谢
  • 如果流支持搜索,那么您可以将 Position 设置为 0。如果它不支持搜索,则必须将其读入辅助流并使用它。
  • 请参阅此处@ФилиппВолошин stackoverflow.com/questions/37975559/…
  • 消息总是相同的吗?您可以一次密件所有人。

标签: c# email model-view-controller attachment


【解决方案1】:

在发送附件之前,您必须像下面这样从头开始寻找流:

emailFile.InputStream.Position = 0;

更多信息你可以在这里参考这个问题:link

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-12-24
    • 2015-09-09
    • 1970-01-01
    • 2015-08-28
    相关资源
    最近更新 更多