C#发送带有附件(图片)的电子邮件

5

我的方法使用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. uploadedImage 不为空。
  2. ContentLength 为 1038946 字节(正确大小)。

然而,发送的电子邮件包含正确文件名的图像作为附件,尽管其大小为 0 字节。

我错了什么?

2个回答

1
@ChrisRun,
  1. You should change the parameter HttpPostedFileBase as byte[] for example. This way you could re-use your class in more places.
  2. Try changing FileName for ContentType and add the MediaTypeNames.Image.Jpeg.
  3. Also, add the using directive for dispose the MailMessage and 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
@ChrisRun,我已经编辑了我的上一个答案,并提供了可用的代码。如果它对你有用,请告诉我。 - Eulogy
抱歉,还是不起作用。我找到的唯一解决办法是先将文件保存在服务器上,然后将路径设置为该文件的物理位置。 - ChrisRun
很奇怪,这对我有效,将文件保存在服务器上没有意义。 - Eulogy

1
< p > System.Net.Mail.Attachment 的构造函数的第二个参数不是文件名,而是内容类型。在创建附件之前,请确保您的流位置为0。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接