我正在尝试附加我已写入发送的电子邮件的文件,但由于某种原因它只是下载而不附加正确的文件。这就是我到目前为止。我错了什么?
public void ConnectToDatabase(UCountRewards uc)
GridView grid = new GridView();
var query = (from a in db.table
where a.IDNumber.Equals(uc.ID_Number)
select a).ToList();
var tt = query;
grid.DataSource = tt.ToList();
grid.DataBind();
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment; filename=ResultsReport.xls");
Response.ContentType = "application/ms-excel";
Response.Charset = "";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
string strPath = Request.PhysicalApplicationPat+"ResultsReport.xls";
grid.RenderControl(htw);
Response.Output.Write(sw.ToString());
StreamWriter sWriter = new StreamWriter(strPath);
sWriter.Write(sw.ToString());
sWriter.Close();
sWriter.Close();
Response.Flush();
Response.End();
}
我在另一个发送电子邮件的控制器上的代码是:
[HttpPost]
public ActionResult Index(MailModel model)
{
MemoryStream memoryStream = new MemoryStream();
if (ModelState.IsValid)
{
MailMessage mail = new MailMessage();
var fromEmail = ConfigurationManager.AppSettings["adminEmail"].ToString();
var ToEmail = ConfigurationManager.AppSettings["receiverEmail"].ToString();
mail.To.Add(ToEmail);
mail.From = new MailAddress(fromEmail);
mail.Subject = model.Subject;
string Body = model.Body;
mail.Body = Body;
mail.IsBodyHtml = true;
string strPath = "ResultsReport.xls";
byte[] bytes = memoryStream.ToArray();
//mail.Body = Body.Replace("\r\n", "<br />");
mail.Attachments.Add(new Attachment(new MemoryStream(bytes), strPath));
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.Port = 587;
smtp.Timeout = 10000;
smtp.UseDefaultCredentials = false;
smtp.Credentials = new System.Net.NetworkCredential
("myemail@gmail.com", "mypassword.");// Enter seders User name and password
smtp.EnableSsl = true;
smtp.Send(mail);
return RedirectToAction("Sent");
}
else
{
return View(model);
}
}