我正在尝试创建一个表单,该表单将发送带有附加图像的电子邮件,并且遇到了一些问题。我正在创建的表单相当大,所以我为此问题创建了一个小测试表单。电子邮件将发送,附件将存在于电子邮件中,但图像已损坏或因为无法查看。
还..
我不想将图像保存到文件系统。您可能认为将文件上载中的图像文件转换为流是令人费解的,但这是因为我正在处理的真实表单将允许通过单个文件上载添加多个文件并将保存在会话中因此,在提交时,图像不会直接来自fileupload控件。
文件:TestAttachSend.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="TestAttachSend.aspx.cs" Inherits="TestAttachSend" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h1>Send Email with Image Attachment</h1>
Email Address TO: <asp:TextBox ID="txtEmail" runat="server"></asp:TextBox><br />
Attach JPEG Image: <asp:FileUpload ID="fuImage" runat="server" /><br />
<br />
<asp:Button ID="btnSend" runat="server" Text="Send" onclick="btnSend_Click" /><br />
<br />
<asp:label ID="lblSent" runat="server" text="Image Sent!" Visible="false" EnableViewState="false"></asp:label>
</div>
</form>
</body>
</html>
文件:TestAttachSend.aspx.cs
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;
}
}
}
答案 0 :(得分:1)
离开我的头顶,你不需要创建一个Image对象。
变化:
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));
到
//can't remember, but you may also need to set the position to 0 ?
//fulImage.PostedFile.InputStream.Position = 0
EmailMsg..Attachments.Add(new Attachment(fulImage.PostedFile.Inputstream, filename, System.Net.Mime.MediaTypeNames.Image.Jpeg));
此外,这假设您上传的图像是JPEG。