带附件问题的电子邮件发送

时间:2018-01-04 00:46:43

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

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

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

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);
    }
}

1 个答案:

答案 0 :(得分:0)

在发送附件之前,您必须从头开始寻找流:

emailFile.InputStream.Position = 0;

有关详情,请点击此处查看此问题:link

相关问题