在Visual Studio中使用ASP.Net的网站上,我成功发送了一封包含xls文件的电子邮件。但是当我复制这段代码时,它在windowsService中不起作用。当我调试时,它们没有任何错误,程序只是在
之前挂起Excel.ApplicationClass excel = new Excel.ApplicationClass();
这一部分。
使用LocalSystem运行,我已经尝试制作此文件夹了。
C:\Windows\SysWOW64\config\systemprofile\Desktop
C:\Windows\System32\config\systemprofile\Desktop
但仍然坚持下去。 这是代码。
private void Email()
{
//get the data from database
DataTable data = GetData();
DataTable email_data = GetEmailData();
this.WriteToFile("78");
// Create an Excel object and add workbook...
////////////program stops here
Excel.ApplicationClass excel = new Excel.ApplicationClass();
Excel.Workbook workbook = excel.Application.Workbooks.Add(false); // true for object template???
this.WriteToFile("7");
// Global missing reference for objects we are not defining...
object missing = System.Reflection.Missing.Value;
this.WriteToFile("77");
// Add column headings...
int iCol = 0;
foreach (DataColumn c in data.Columns)
{
iCol++;
excel.Cells[1, iCol] = c.ColumnName;
}
// for each row of data...
int iRow = 0;
foreach (DataRow r in data.Rows)
{
iRow++;
// add each row's cell data...
iCol = 0;
foreach (DataColumn c in data.Columns)
{
iCol++;
excel.Cells[iRow + 1, iCol] = r[c.ColumnName];
}
}
// If wanting to Save the workbook...
this.WriteToFile("1");
workbook.SaveAs(@"C:\Windows\temp\NSOList.xls",
Excel.XlFileFormat.xlWorkbookNormal, missing, missing,
false, false, Excel.XlSaveAsAccessMode.xlExclusive,
missing, missing, missing, missing, missing);
this.WriteToFile("2");
workbook.Close();
using (MailMessage mm = new MailMessage())
{
this.WriteToFile("3");
mm.From = new MailAddress("aa@gmail.com");
for (int i = 0; i < email_data.Rows.Count; i++)
{
mm.Bcc.Add(email_data.Rows[i][0].ToString());
}
using (SmtpClient smtp = new SmtpClient())
{
mm.Subject = "List";
mm.Attachments.Add(new Attachment(@"C:\Windows\temp\List.xls"));
mm.IsBodyHtml = true;
smtp.Host = "smtp.gmail.com";
smtp.EnableSsl = true;
System.Net.NetworkCredential credentials = new System.Net.NetworkCredential();
credentials.UserName = "aa@gmail.com";
credentials.Password = "1234";
smtp.UseDefaultCredentials = true;
smtp.Credentials = credentials;
smtp.Port = 587;
this.WriteToFile("4");
Thread.Sleep(1000);
smtp.Send(mm);
}
}
}