将图像附加到我的电子邮件联系表单,但图像显示“文件为空”C#

时间:2012-01-16 23:35:38

标签: c# forms email attachment

这是代码......

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net.Mail;
using System.IO;

public partial class TestAttachSend : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void btnSend_Click(object sender, EventArgs e)
    {
        if (fuImage.HasFile && fuImage.PostedFile.ContentType == System.Net.Mime.MediaTypeNames.Image.Jpeg)
        {
            SmtpClient emailClient = new SmtpClient();
            MailMessage EmailMsg = new MailMessage();

            EmailMsg.To.Add(txtEmail.Text.Trim());
            EmailMsg.From = new MailAddress(txtEmail.Text.Trim());
            EmailMsg.Subject = "Attached Image";
            EmailMsg.Body = "Image is attached!";

            MemoryStream imgStream = new MemoryStream();
            System.Drawing.Image img = System.Drawing.Image.FromStream(fuImage.PostedFile.InputStream);
            string filename = fuImage.PostedFile.FileName;

            img.Save(imgStream, System.Drawing.Imaging.ImageFormat.Jpeg);
            EmailMsg.Attachments.Add(new Attachment(imgStream, filename, System.Net.Mime.MediaTypeNames.Image.Jpeg));

            emailClient.Send(EmailMsg);

            lblSent.Visible = true;

        }
    }
}

这段代码很有效。但是当您在电子邮件中打开附加图像时,它会显示“文件为空”

谁能看到我哪里出错了?

另外我想使用多种图像格式(gif,png)。但我不知道该怎么做。

1 个答案:

答案 0 :(得分:2)

尝试

imgStream.Seek(0L, SeekOrigin.Begin);
在将imgStream传递给Attachment构造函数之前