我有一个表单,发件人通过该表单发送他的电子邮件ID和密码并选择附件
使用fileupload,收件人的电子邮件ID我从数据库表中获取,电子邮件正好接收到收件人..但
问题是,当我附上附件时,附件的大小为0,除了第一个email-id
,我从桌子上得到....我已粘贴代码..
foreach (string email_to in list_emails)
{
MailMessage mail = new MailMessage();
mail.To.Add(email_to);
mail.Subject = "UPDATES FROM ATTENDANCE S/W";
mail.From = new MailAddress(txtFrom.Text.ToString());
mail.Body = txtMessage.Text;
if (FileUpload1.HasFile)
{
string fileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
Attachment myAttachment =
new Attachment(FileUpload1.FileContent, fileName);
mail.Attachments.Add(myAttachment);
}
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.UseDefaultCredentials = false;
smtp.Credentials = new System.Net.NetworkCredential(txtFrom.Text.ToString(), txtPasswd.Text.ToString());
smtp.EnableSsl = true;
smtp.Send(mail);
}
答案 0 :(得分:2)
这种情况正在发生,因为FileContent
是Stream
,因此当您从中读取时,Stream
的位置会留在最后。考虑这样的事情。在循环的顶部存储字节,无论如何你都不需要继续从Stream
读取它们:
bool hasFile = FileUpload1.HasFile;
int fileLen = FileUpload1.PostedFile.ContentLength;
Stream stream = FileUpload1.FileContent;
byte[] file = new byte[fileLen];
stream.Read(file, 0, fileLen);
然后在循环中向下,利用变量:
new Attachment(new MemoryStream(file) ...
并且您要更改if
语句以利用bool
:
if (hasFile)