您的位置:首页 > 其它

Web应用中实现发送带附件的电子邮件

2009-03-11 20:52 197 查看
首先关注MSDN上关于Attachment的两个解释:

Attachment Constructor

First of all, the Stream that you supply to an attachment is not read until you actually send a message. That should make sense enough, but sometimes it's easy to forget. If your stream relies on some other resource that was disposed of by the time the message is sent, the client will fail to send your message.

Secondly, if you are writing into a Stream that will later be read by an Attachment, make sure you set the Position back to 0. Otherwise, you may end up with zero-length attachments even though your stream has data! Attachment does not appear to rewind the Stream for you; it reads from whatever position the Stream is currently at.

针对第二种解释,我在测试过程中MemoryStream.Seek(0,SeekOrigin.Begin),可是附件的长度还是为0,不知道为什么;等有时间再测试一下。

解释:MemoryStream.Write()后,流的当前位置是停在结束位置上,如果再Read(),是从结束位开始读.正确的做法应该在Read() 前重新设置流位置MemoryStream.Seek(0,SeekOrigin.Begin),

现在是变通一下,先发送后删除。

Code

//附件插入代码

if (vfiles.Count > 0)

{

attachment = new Attachment[vfiles.Count];

for (int i = 0; i < vfiles.Count; i++)

{

sFileName = vfiles[i].Name;

sFileID = vfiles[i].ID;

result = FileService.GetFileData(sFileID, string.Empty);

if (result.IsSuccessful)

{

byte[] buffer = (byte[])result.ResultValue;

sPath = HttpContext.Current.Server.MapPath(".") + @"\" + sFileName;

FileStream fs = new FileStream(sPath, FileMode.OpenOrCreate, FileAccess.Write );

fs.Write(buffer, 0, buffer.Length);

fs.Close();

fs.Dispose();

attachment[i] = new Attachment(sPath); ;

}

}

}

//发送邮件

string[] info = GetMailInfo(sObjID);

MailMessage mail = new MailMessage("******", info[0]);

mail.SubjectEncoding = Encoding.UTF8;

mail.Subject = info[2];

mail.IsBodyHtml = true;

mail.BodyEncoding = Encoding.UTF8;

mail.Body = string.Format("<strong>{0}********</strong>", info[0]);

Attachment[] attachment = GetAttachmentList(sObjID);

string[] path = new string[attachment.Length];

for (int i = 0; i < attachment.Length; i++)

{

mail.Attachments.Add(attachment[i]);

path[i] = attachment[i].Name;

}

SmtpClient smtp = new SmtpClient("******");

smtp.Credentials = new NetworkCredential("*****", "*****");

smtp.Send(mail);

mail.Attachments.Dispose();

for (int i = 0; i < path.Length; i++)

{

File.Delete(HttpContext.Current.Server.MapPath(".") + @"\" + path[i]);

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: