这是代码......
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)。但我不知道该怎么做。
答案 0 :(得分:2)
尝试
imgStream.Seek(0L, SeekOrigin.Begin);
在将imgStream
传递给Attachment
构造函数之前。