简体   繁体   中英

Sending Email using Interop.Excel without saving

I am trying to send the email on every week specific time. But When I use this code, it keeps asking

"A file named "C:\\Windows\\Temp\\employee.xls" already exists in this location. Do you want to replace it?"

Is there any way I can send the email directly without saving those xls file?

This is my code.

    private void SendEmail()
    {
        //get the data from database
        DataTable data = GetData();
        DataTable email_data = GetEmailData();


        // Create an Excel object and add workbook...
        Excel.ApplicationClass excel = new Excel.ApplicationClass();
        Excel.Workbook workbook = excel.Application.Workbooks.Add(true); // true for object template???

        // Global missing reference for objects we are not defining...
        object missing = System.Reflection.Missing.Value;

        // 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...


        workbook.SaveAs(@"C:\Windows\Temp\employee.xls",
        Excel.XlFileFormat.xlWorkbookNormal, missing, missing,
        false, false, Excel.XlSaveAsAccessMode.xlExclusive,
        missing, missing, missing, missing, missing);


        workbook.Close();

        String from = "aa@gmail.com";

        String to = "bb@gmail.com";

        using (MailMessage mm = new MailMessage(from, to))
        {
       SmtpClient smtp = new SmtpClient();
            mm.Subject = "List";
            mm.Attachments.Add(new Attachment(@"C:\Windows\Temp\employee.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;
            smtp.Send(mm);
        }
    }

There is the Workbook.SendMail method, which, according to documentation ,

sends the active workbook to a single recipient

and there is no need to call workbook.SaveAs before (that a mail client may still create a temporary file for the attachment somewhere on disk at its own discretion, is a different story).

A second possibility: Use an open document format library like EPPlus (for the task you perform in your code, there is no need for the heavyweight Excel automation), because there you can bypass the file system by streaming the file directly into the attachment:

https://msdn.microsoft.com/en-us/library/ab7hb4y5(v=vs.110).aspx

using (var package = new ExcelPackage())
{
    var worksheet = package.Workbook.Worksheets.Add("sheet");

    /* fill sheet with data 
     * ... */

    /* compose mail 
     * ... */

    var contenttype = new ContentType("application/vnd.ms-excel");
    var stream = new MemoryStream(package.GetAsByteArray());
    mm.Attachments.Add(new Attachment(stream, contenttype);

    /* send mail */
}

EDIT

Considering the comments: I interpret your problem to be more "how do I get rid of the prompt" instead of "I may not write anything to the file system", so you may be best off just doing this before you save the workbook, and after you sent the mail:

var filename = @"C:\Windows\Temp\employee.xls";
if(File.Exists(filename)  
{
    File.Delete(filename);
}

If this is a software you are planning to distribute, you will need to replace that hardcoded path using GetTempPath .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM