C#使用附件发送电子邮件(图像)

时间:2016-01-14 10:30:16

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

我的方法使用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字节(正确大小)。
  3. 但是,正在发送的电子邮件将图像包含为具有正确文件名的附件,尽管它的大小为0字节。

    我错过了什么?

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:1)

@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);
            }
        }
    
  4. 干杯

相关问题