【问题标题】:C# Sending Email with attached file (image)C# 发送带有附件的电子邮件(图片)
【发布时间】:2016-01-14 10:30:15
【问题描述】:

我的方法使用 SMTP 中继服务器发送电子邮件。

一切正常(电子邮件已发送),除了附件(图像)以某种方式压缩/不存在并且无法从电子邮件中检索。

方法如下:

public static bool SendEmail(HttpPostedFileBase uploadedImage)
        {
            try
            {              
                var message = new MailMessage() //To/From address
                {
                    Subject = "This is subject."
                    Body = "This is text."
                };                             

                    if (uploadedImage != null && uploadedImage.ContentLength > 0)
                    {
                        System.Net.Mail.Attachment attachment;
                        attachment = new System.Net.Mail.Attachment(uploadedImage.InputStream, uploadedImage.FileName);
                        message.Attachments.Add(attachment);
                    }
                message.IsBodyHtml = true;

                var smtpClient = new SmtpClient();
                //SMTP Credentials
                smtpClient.Send(message);
                return true;
            }
            catch (Exception ex)
            {
            //Logg exception
                return false;
            }
        }
  1. 上传的图片不为空。
  2. ContentLength 为 1038946 字节(大小正确)。

但是,正在发送的电子邮件包含带有正确文件名的图像作为附件,尽管它的大小为 0 字节。

我错过了什么?

【问题讨论】:

    标签: c# asp.net smtp email-attachments


    【解决方案1】:

    System.Net.Mail.Attachment的构造函数的第二个参数不是文件名。这是content type。 也许在创建附件之前确保您的流位置为 0

    【讨论】:

      【解决方案2】:

      @ChrisRun,

      1. 例如,您应该将参数 HttpPostedFileBase 更改为 byte[]。这样您就可以在更多地方重复使用您的课程。
      2. 尝试更改 ContentType 的 FileName 并添加 MediaTypeNames.Image.Jpeg。
      3. 另外,添加 using 指令来处理 MailMessage 和 SmtpClient

            using (var message = new MailMessage
            {
                From = new MailAddress("from@gmail.com"),
                Subject = "This is subject.",
                Body = "This is text.",
                IsBodyHtml = true,
                To = { "to@someDomain.com" }
            })
            {
                if (imageFile != null && imageFile.ContentLength > 0)
                {
                    message.Attachments.Add(new Attachment(imageFile.InputStream, imageFile.ContentType, MediaTypeNames.Image.Jpeg));
                }
        
                using (var client = new SmtpClient("smtp.gmail.com")
                {
                    Credentials = new System.Net.NetworkCredential("user", "password"),
                    EnableSsl = true
                })
                {
                    client.Send(message);
                }
            }
        

      干杯

      【讨论】:

      • 首先:感谢您的意见。第二:也没有使用 ContentType 作为参数。
      • @ChrisRun,我用工作代码编辑了我之前的答案。让我知道它是否适合您。
      • 抱歉,还是不行。我找到的唯一解决方案是首先将文件保存在服务器上,然后将路径设置为该文件的物理位置。
      • 这很奇怪。它对我有用,将文件保存在服务器上没有意义。
      猜你喜欢
      • 2023-03-22
      • 1970-01-01
      • 1970-01-01
      • 2016-08-23
      • 2011-11-10
      • 2015-09-09
      相关资源
      最近更新 更多