Google

Tuesday, September 9, 2008

Email Attachments using C#

How to automatically generate e-mails with attachments from your C# Code ?

Now-a-days everyone wants Emails to be generated from the applciaiton itself. in my previous blog I have already discussed how to generate simple text e-mails.

But if you want to generate e-mails with attachments , still its not difficult at all. I have done it for sending an Excel Attachment. The txt attachment again is simpler, you just need to follow the same logic as excel but less complicated to copy and send. So, Lets Start.

PART I 

The code below shows the following steps for copying the excel sheet to be posted into the mailing attachment sheet(If you already have the sheet and just need to mail it, you can skip this part):-
1. Create a new excel workbook.
2. Create a new Directory.
3. Copy the old sheet to the new workbook sheet
4. You can turn on the displays on/off for the sheet by just doing
          application.displayAlerts = false/true;
5. Save the new workbook with the name required and close the excel.For saving
          you can use
            newWorkbook.saveAs(Save Name,System.Type.Missing,
            System.Type.Missing,System.Type.Missing,false, false,
            XlSaveAsAccessMode.xlNoChange,System.Type.Missing,
            System.Type.Missing,System.Type.Missing,
            System.Type.Missing,System.Type.Missing);
          and for closing you can use
            newWorkbook.Close(false,false,System.Type.Missing);
PART II 

Now, the steps below shows the e-mailing of the excel sheet as an attachment.
1. Make an object of MailMessage.
2. Set the parameters ,
          TO(toAddress); FROM(fromAddress); SUBJECT(a string one liner);     
          BODY(message to write inside the main body of mail);
3. Set the MailAttachment object with the filename to send an simply add the
           Attachment to the mail message.
4. SmtpMail.SmptServer needs to be set. It is the address of your office mail
          server.And then finally the message needs to be send, SmtpMail.Send();
private void SendEmail()
{

    Excel.Workbook newWorkbook = this.thisApplication.Workbooks.Add
                                 (XlWBATemplate.xlWBATWorksheet);

    string windowsLogin = Environment.UserName.ToString();

    object m = System.Reflection.Missing.Value;

    string fMsg = windowsLogin + @"@gmail.com";

    string note = "";

    try
    {

         Directory.CreateDirectory("ForEmail");

         Directory.SetCurrentDirectory("ForEmail");

         oldSheet.Copy(newWorkbook.Sheets[1],System.Type.Missing);

         Excel.Worksheet emailingSheet = ExcelHelpers.GetWorksheet
                                          (newWorkbook, "Recap");

         Excel.Range tempRange= emailingSheet.UsedRange;

         Excel.Worksheet copySheet = ExcelHelpers.GetWorksheet
                                          (newWorkbook, "Sheet1");

         newWorkbook.Sheets.FillAcrossSheets
                                 (tempRange,XlFillWith.xlFillWithAll);
         string accountName = acctComboBox.Text.Trim();

         copySheet.Cells[5,2] = accountName;

         thisApplication.DisplayAlerts = false;

         emailingSheet.Delete();

         thisApplication.DisplayAlerts = true;

         copySheet.Columns.AutoFit();

         newWorkbook.SaveAs("Info.xls",System.Type.Missing,
            System.Type.Missing,System.Type.Missing,false, false,
            XlSaveAsAccessMode.xlNoChange,System.Type.Missing,
            System.Type.Missing,System.Type.Missing,
            System.Type.Missing,System.Type.Missing);

         newWorkbook.Close(false,false,System.Type.Missing);
       

       

//***************************PART TWO BEGINS HERE******************************//

         string to = null;

         for(int r = 2; r < 10; r++)

         {

             if(((Range)mEmailSheet.Cells[r, 1]).Text != null &&

                  ((string)((Range)mEmailSheet.Cells[r, 1]).Text).Length < 1)

             {

                     break;

             }

             if(to == null)
               to = (string)((Range)mEmailSheet.Cells[r, 1]).Text+";";

             else

               to = to +((Range)mEmailSheet.Cells[r, 1]).Value2.ToString()+ ";";

         }

         MailMessage message = new MailMessage();

         message.To = to;

         message.From = fMsg.ToString();

         message.Subject="Email Submitted " ;  

         message.Body ="Attachment enclosed";

         Thread.Sleep(3000);

         DirectoryInfo dirInfo = new DirectoryInfo(Directory.GetCurrentDirectory
                                                                            ());

         FileInfo[] fInfo = dirInfo.GetFiles();

         string fileName = fInfo[0].Name;

         MailAttachment attach = new MailAttachment
                                 (Directory.GetCurrentDirectory() +

                                 @"\"+fileName,
                                 System.Web.Mail.MailEncoding.Base64);

         message.Attachments.Add(attach);

         SmtpMail.SmtpServer = "xyz.CompanyDomain.com";

         SmtpMail.Send(message);

         MessageBox.Show("E-Mail send.");

         Directory.SetCurrentDirectory("..");

         Directory.Delete("ForEmail",true);

     }

     catch(Exception e)

     {

          Console.WriteLine(e);

          newWorkbook.Close(false,false,System.Type.Missing);

          Directory.SetCurrentDirectory("..");

          Directory.Delete("ForEmail",true);

     }

}

1 comment:

Anonymous said...

this is a question rather then a comment. If u could please tell me how i send an scanned image as an attachment. thanks