Пример #1
0
        private void NewAppointment(string subject, string location, DateTime start, DateTime end, short allDay, int reminderMinutes)
        {
            GXLogging.Debug(log, "Adding New Appointment");
            if (session == null)
            {
                GXLogging.Error(log, "Could not start Outlook");
                throw new GXMailException("Could not start Outlook", 4);
            }

            _AppointmentItem appoint;

            try
            {
                appoint             = (_AppointmentItem)session.CreateItem(OlItemType.olAppointmentItem);
                appoint.Subject     = subject;
                appoint.Location    = location;
                appoint.Start       = start;
                appoint.End         = end;
                appoint.AllDayEvent = (allDay == 1);
                appoint.ReminderSet = (reminderMinutes > 0);
                if (appoint.ReminderSet)
                {
                    appoint.ReminderMinutesBeforeStart = reminderMinutes;
                }
                if (editWindow != 1)
                {
                    appoint.Save();
                }
                else
                {
                    appoint.Display(false);
                }
            }
            catch (System.Exception exc)
            {
                GXLogging.Error(log, "Internal error", exc);
                throw new GXMailException("Internal error", 22);
            }
        }
Пример #2
0
        private static void Main(string[] args)
        {
            string sPathCommands = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),
                                                "commands");

            try
            {
                if (!Directory.Exists(sPathCommands))
                {
                    Directory.CreateDirectory(sPathCommands);
                }

                OutlookApp.NewMailEx += OutLookAppNewMailEx;

                if (args.Length > 0 && args[0] == "testes")
                {
                    MailItem mailTestes;

                    mailTestes         = (MailItem)OutlookApp.CreateItem(OlItemType.olMailItem);
                    mailTestes.Subject = "TestesInternos";
                    mailTestes.Body    = "TestesInternos";
                    Processar(mailTestes);

                    mailTestes         = (MailItem)OutlookApp.CreateItem(OlItemType.olMailItem);
                    mailTestes.Subject = "TestesExternos";
                    mailTestes.Body    = "TestesExternos";
                    Processar(mailTestes);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("ERRO :: " + e);
            }

            Console.Read();

            OutlookApp.Quit();
        }
        public void Send(string buttonId, string subject, OlImportance importance)
        {
            try
            {
                Application outlookApp = new ApplicationClass();
                MailItem    newEmail   = (MailItem)outlookApp.CreateItem(OlItemType.olMailItem);

                // Get the recipients
                string[] recipients = StaticHelper.GetRecipients(buttonId);
                newEmail.To  = recipients[0];
                newEmail.CC  = recipients[1];
                newEmail.BCC = recipients[2];

                newEmail.Subject    = subject;
                newEmail.Importance = importance;
                newEmail.Display(true);
            }
            catch (System.Exception ex)
            {
                StaticHelper.LogMessage(MessageType.Error, ex.ToString());
                throw;
            }
        }
Пример #4
0
        static void Main(string[] args)
        {
            ApplicationClass application = new ApplicationClass();

            NameSpace nspace = application.GetNamespace("MAPI");

            nspace.Logon(Missing.Value, Missing.Value, false, false);


            object objappointment = application.CreateItem(OlItemType.olAppointmentItem);

            if (objappointment != null)
            {
                AppointmentItem appointment = (AppointmentItem)objappointment;

                appointment.Importance  = OlImportance.olImportanceHigh;
                appointment.Subject     = "watch tv";
                appointment.Body        = "Не забудь посмотреть телевизор!";
                appointment.Start       = DateTime.Parse("1-1-2006 11:00 am");
                appointment.End         = DateTime.Parse("1-1-2006 1:00 pm");
                appointment.Location    = "Диван";
                appointment.ReminderSet = true;
                appointment.ReminderMinutesBeforeStart = 60;
                appointment.AllDayEvent = false;
                appointment.Save();

                appointment = null;
            }

            nspace.Logoff();
            nspace = null;

            application.Quit();
            application = null;

            Console.ReadLine();
        }
Пример #5
0
        private void button1_Click(object sender, EventArgs e)
        {
            if(validData())
              {

                //Start Timer
                Stopwatch timer = new Stopwatch();
                timer.Start();

                //Get date from user
                string endDate_string = txtEndDate.Text;
                string startDate_string = txtstartDate.Text;

                DateTime endDate_dt = Convert.ToDateTime(endDate_string);
                DateTime startDate_dt = Convert.ToDateTime(startDate_string);

                //convert date from mm-dd-yyyy to yyyy-mm-dd
                string string_Date_End = endDate_dt.Year.ToString() + "-" + endDate_dt.Month.ToString() + "-" + endDate_dt.Day.ToString();
                string string_Date_Start = startDate_dt.Year.ToString() + "-" + startDate_dt.Month.ToString() + "-" + startDate_dt.Day.ToString();

                //Execute stored procedure to produce parameters to then pass into an arrary that will then feed parameters to the DIR Report
                //connect to local DB, AES006DatEnterprise
                SqlConnection connection = new SqlConnection("Data Source=L1SQLHMIS;Initial Catalog=TestAndrew;Integrated Security=True");
                SqlCommand command = new SqlCommand();
                SqlDataAdapter adapter = new SqlDataAdapter();

                DataSet ds = new DataSet();
                DataTable dt = new DataTable();

                connection.Open();
                command.Connection = connection;
                command.CommandType = CommandType.StoredProcedure;
                command.CommandText = "sp_lahsaCustom_DIRP_Auto_ParameterPull_AA";

                //Define SQL parameters
                SqlParameter maxRecordNumber_sqlPrm;
                SqlParameter contractType_sqlPrm;
                SqlParameter agency_sqlPrm;

                //Set SQL String param
                string maxRecrodNumber_string = "-1";
                string contractType_string = selectedContractType;
                string agency_string = selectedAgency;

                //Pass param to SP
                maxRecordNumber_sqlPrm = new SqlParameter("@MaxRecordNumber", maxRecrodNumber_string);
                maxRecordNumber_sqlPrm.Direction = ParameterDirection.Input;
                maxRecordNumber_sqlPrm.DbType = DbType.String;
                command.Parameters.Add(maxRecordNumber_sqlPrm);

                contractType_sqlPrm = new SqlParameter("@contractType", contractType_string);
                contractType_sqlPrm.Direction = ParameterDirection.Input;
                contractType_sqlPrm.DbType = DbType.String;
                command.Parameters.Add(contractType_sqlPrm);

                agency_sqlPrm = new SqlParameter("@agency", agency_string);
                agency_sqlPrm.Direction = ParameterDirection.Input;
                agency_sqlPrm.DbType = DbType.String;
                command.Parameters.Add(agency_sqlPrm);

                command.CommandTimeout = 0;
                command.ExecuteNonQuery();

                adapter.SelectCommand = command;

                adapter.Fill(ds, "myData");
                dt = ds.Tables["myData"];
                dr = dt.Rows[0];

                int rowCount = dt.Rows.Count;

                int spJ = 0;
                List<string> agency_list = new List<string>();
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    string agency = dt.Rows[i].ItemArray[spJ].ToString();
                    agency_list.Add(agency.ToString());
                }

                spJ += 1;
                List<string> programAnalyst_list = new List<string>();
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    string programAnalyst = dt.Rows[i].ItemArray[spJ].ToString();
                    programAnalyst_list.Add(programAnalyst.ToString());
                }

                spJ += 1;
                List<string> contractType_list = new List<string>();
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    string contractType = dt.Rows[i].ItemArray[spJ].ToString();
                    contractType_list.Add(contractType.ToString());
                }

                spJ += 1;
                List<string> program_list = new List<string>();
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    string program = dt.Rows[i].ItemArray[spJ].ToString();
                    program_list.Add(program.ToString());
                }

                spJ += 1;
                List<string> contractNumber_list = new List<string>();
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    string contractNumber = dt.Rows[i].ItemArray[spJ].ToString();
                    contractNumber_list.Add(contractNumber.ToString());
                }

                spJ += 1;
                List<string> maxRecordNumber_list = new List<string>();
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    string maxRecordNumber = dt.Rows[i].ItemArray[spJ].ToString();
                    maxRecordNumber_list.Add(maxRecordNumber.ToString());
                }

                spJ += 1;
                List<string> QPRFlag_list = new List<string>();
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    string QPRFlag = dt.Rows[i].ItemArray[spJ].ToString();
                    QPRFlag_list.Add(QPRFlag.ToString());
                }

                //string[] agency = { "LA_TSA", "LA_HOV", "LA_WCA", "LA_TSA", "LA_TWC", "LA_STJ", "LA_CCL", "LA_AVD", "LA_USF", "LA_UBH", "LA_HIS", "LA_LFH", "LA_LFH", "LA_PAT", "LA_CHC" };
                //string[] contractNumber = { "2014HFSS08", "2014HFSS05Sub", "2014HFSS12", "2014HFSS11", "2014HFSS04", "2014HFSS09", "2014HFSS14", "2014HFSS01", "2014HFSS02", "2014HFSS10", "2014HFSS13", "2014HFSS05", "2014HFSS07", "2014HFSS06", "2014HFSS03" };

                //check email check box, default is 0 aka not send email
                var emailCheck = 0;
                if (checkBox1.Checked)
                {
                    emailCheck = 1;
                }

                //1 will run logic to delete the newly created file after email
                var deleteFile = 1;
                if (saveCheckBox.Checked)
                {
                    deleteFile = 0;
                }

                //Initialize progress bar
                progressBar1.Visible = true;
                progressBar1.Minimum = 0;
                progressBar1.Maximum = (agency_list.Count) * 2;
                progressBar1.Value = 1;
                progressBar1.Step = 1;

                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    try
                    {

                        reportViewer1.ProcessingMode = Microsoft.Reporting.WinForms.ProcessingMode.Remote;
                        ServerReport serverReport = reportViewer1.ServerReport;

                        //Using the local server, no password
                        //reportViewer1.ServerReport.ReportServerUrl = new Uri("http://l1sql2-07/ReportServer");
                        //reportViewer1.ServerReport.ReportPath = "/HMIS - Management Reports/Data Integrity Report (LAHSA)";

                        btnStart.Text = "Connecting to reportServer";
                        //using the passwordProtected Server
                        reportViewer1.ServerReport.ReportServerUrl = new Uri("https://dw24.esserver.com/reportServer");
                        reportViewer1.ServerReport.ReportPath = "/HMIS Management Reports/Data Integrity Report (LAHSA)";

                        //Create an arrary with Report Parameters
                        progressBar1.PerformStep();
                        ArrayList reportParam = new ArrayList();
                        reportParam = ReportDefaultPatam(agency_list, contractNumber_list, contractType_list,string_Date_Start, string_Date_End, i);

                        //pass parameters into parameter arrary
                        ReportParameter[] param = new ReportParameter[reportParam.Count];
                        for (int k = 0; k < reportParam.Count; k++)
                        {
                            param[k] = (ReportParameter)reportParam[k];
                        }

                        //Pass Credentials
                        //NetworkCredential myCred = new NetworkCredential("JDecell", "1contr0lsth3ird3stiny*","");
                        //reportViewer1.ServerReport.ReportServerCredentials.NetworkCredentials = myCred;
                        btnStart.Text = "Loading Credentials";
                        string userName = @"Dw24\GBarbosa";
                        string userPassword = "******";
                        string userDomain = "";//LAHSADOM,Dw24

                        NetworkCredential myCred = new NetworkCredential(userName, userPassword, userDomain);
                        reportViewer1.ServerReport.ReportServerCredentials.NetworkCredentials = myCred;

                        //Set paramets and generate report
                        btnStart.Text = "Pulling report for: " + agency_list[i] + "(" + (i + 1).ToString() + "/" + (dt.Rows.Count).ToString() + ")";
                        reportViewer1.ServerReport.SetParameters(param);
                        reportViewer1.RefreshReport();

                        //function creates and saves file
                        string fileName = ExportReport(reportViewer1, agency_list,contractNumber_list, program_list, i);

                        string reportFileName = fileName;

                        if (emailCheck == 1 && i == (dt.Rows.Count) - 1)
                        {
                            string[] emailList = { "*****@*****.**", "*****@*****.**" };

                            for (int j = 0; j < emailList.Length; j++)
                            {
                                //Create new email using outlook
                                btnStart.Text = "Compliling and Sending Email";
                                ApplicationClass outlookApp = new ApplicationClass();
                                MailItem mailItem = (MailItem)outlookApp.CreateItem(OlItemType.olMailItem);
                                mailItem.To = emailList[j];

                                timer.Stop();
                                //Get elapsed time
                                TimeSpan ts = timer.Elapsed;
                                //Format time
                                string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10);

                                mailItem.Subject = "DIR reports complete";
                                mailItem.Body = "The DIR reports for the time period " + string_Date_Start + " to " + string_Date_End + " are complete.\n The reports can be found here: G:\\DA\\Rene\\AutoDIR \n Total run time " + elapsedTime;

                                //mailItem.Subject = "DIR for " + agency[i];
                                //mailItem.Body = "Here is the DIR for " + agency[i] + " for period " + string_Date_Start + " to " + string_Date_End + " The Report path: " + reportFileName;
                                //mailItem.Attachments.Add(reportFileName, (int)OlAttachmentType.olByValue, 1, reportFileName);

                                //send the email
                                mailItem.Send();
                            }

                        }

                        if (deleteFile == 1)
                        {
                            //Delete file once done
                            File.Delete(reportFileName);
                        }

                        progressBar1.PerformStep();

                    }
                    catch (System.Exception ex)
                    {
                        MessageBox.Show(ex.Message + "\n" + ex.GetType().ToString() + "\n" + ex.StackTrace);
                        throw ex;

                    }
                }

                //pause for 1 min
                //System.Threading.Thread.Sleep(1 * 60 * 1000);
                btnStart.Text = "DIRs Complete, please close program";
            }
        }
        public void Send(string buttonId, string subject, OlImportance importance)
        {
            try
            {
                Application outlookApp = new ApplicationClass();
                MailItem newEmail = (MailItem)outlookApp.CreateItem(OlItemType.olMailItem);

                // Get the recipients
                string[] recipients = StaticHelper.GetRecipients(buttonId);
                newEmail.To = recipients[0];
                newEmail.CC = recipients[1];
                newEmail.BCC = recipients[2];

                newEmail.Subject = subject;
                newEmail.Importance = importance;
                newEmail.Display(true);
            }
            catch (System.Exception ex)
            {
                StaticHelper.LogMessage(MessageType.Error, ex.ToString());
                throw;
            }
        }
        public void Meeting(IRibbonControl control, string subject, OlImportance importance)
        {
            try
            {
                string[]        idParts    = control.Id.Split(new[] { StaticHelper.SplitSequence }, StringSplitOptions.RemoveEmptyEntries);
                Application     outlookApp = new ApplicationClass();
                AppointmentItem newMeeting = (AppointmentItem)outlookApp.CreateItem(OlItemType.olAppointmentItem);
                newMeeting.MeetingStatus = OlMeetingStatus.olMeeting;

                // Get the recipients
                string[] recipients = StaticHelper.GetRecipients(idParts[0], control.Id);
                if (!string.IsNullOrEmpty(recipients[0]))
                {
                    foreach (Recipient recipRequired in recipients[0].Split(new[] { ';' }).Select(s => newMeeting.Recipients.Add(s)))
                    {
                        recipRequired.Type = (int)OlMeetingRecipientType.olRequired;
                    }
                }

                if (!string.IsNullOrEmpty(recipients[1]))
                {
                    foreach (Recipient recipOptional in recipients[1].Split(new[] { ';' }).Select(s => newMeeting.Recipients.Add(s)))
                    {
                        recipOptional.Type = (int)OlMeetingRecipientType.olOptional;
                    }
                }

                newMeeting.Subject    = subject;
                newMeeting.Importance = importance;

                string from = StaticHelper.GetApplicationSetting("MasterEmailAccount");
                if (string.IsNullOrEmpty(from))
                {
                    from = StaticHelper.GetFromAccount(idParts[0]);
                }

                if (!string.IsNullOrEmpty(from))
                {
                    // Retrieve the account that has the specific SMTP address.
                    Account account = GetAccountForEmailAddress(outlookApp, from);
                    if (account != null)
                    {
                        // Use this account to send the e-mail.
                        newMeeting.SendUsingAccount = account;
                    }
                }

                if (control.Context is Inspector)
                {
                    Inspector inspector = (Inspector)control.Context;
                    if (inspector.CurrentItem is AppointmentItem)
                    {
                        AppointmentItem m = inspector.CurrentItem as AppointmentItem;

                        // Get the recipients
                        string[] recipients2 = StaticHelper.GetRecipients(idParts[0], control.Id);
                        if (!string.IsNullOrEmpty(recipients2[0]))
                        {
                            foreach (Recipient recipRequired in recipients2[0].Split(new[] { ';' }).Select(s => newMeeting.Recipients.Add(s)))
                            {
                                recipRequired.Type = (int)OlMeetingRecipientType.olRequired;
                            }
                        }

                        if (!string.IsNullOrEmpty(recipients2[1]))
                        {
                            foreach (Recipient recipOptional in recipients2[1].Split(new[] { ';' }).Select(s => newMeeting.Recipients.Add(s)))
                            {
                                recipOptional.Type = (int)OlMeetingRecipientType.olOptional;
                            }
                        }

                        if (string.IsNullOrEmpty(m.Subject))
                        {
                            m.Subject = newMeeting.Subject;
                        }
                        else
                        {
                            string standardSuffix = StaticHelper.GetStandardSuffix(idParts[0]);
                            if (!string.IsNullOrEmpty(standardSuffix))
                            {
                                newMeeting.Subject = newMeeting.Subject.Replace(standardSuffix, string.Empty);
                            }

                            m.Subject = newMeeting.Subject + m.Subject;
                        }

                        if (!string.IsNullOrEmpty(from))
                        {
                            // Retrieve the account that has the specific SMTP address.
                            Account account = GetAccountForEmailAddress(outlookApp, from);
                            if (account != null)
                            {
                                // Use this account to send the e-mail.
                                m.SendUsingAccount = account;
                            }
                        }
                    }
                }
                else
                {
                    newMeeting.Display();
                }
            }
            catch (System.Exception ex)
            {
                StaticHelper.LogMessage(MessageType.Error, ex.ToString());
                throw;
            }
        }
        public void Send(IRibbonControl control, string subject, OlImportance importance)
        {
            try
            {
                string[]    idParts    = control.Id.Split(new[] { StaticHelper.SplitSequence }, StringSplitOptions.RemoveEmptyEntries);
                Application outlookApp = new ApplicationClass();
                MailItem    newEmail   = (MailItem)outlookApp.CreateItem(OlItemType.olMailItem);

                // Get the recipients
                string[] recipients = StaticHelper.GetRecipients(idParts[0], control.Id);
                newEmail.To         = recipients[0];
                newEmail.CC         = recipients[1];
                newEmail.BCC        = recipients[2];
                newEmail.Subject    = subject;
                newEmail.Importance = importance;

                string from = StaticHelper.GetApplicationSetting("MasterEmailAccount");
                if (string.IsNullOrEmpty(from))
                {
                    from = StaticHelper.GetFromAccount(idParts[0]);
                }

                if (!string.IsNullOrEmpty(from))
                {
                    // Retrieve the account that has the specific SMTP address.
                    Account account = GetAccountForEmailAddress(outlookApp, from);
                    if (account != null)
                    {
                        // Use this account to send the e-mail.
                        newEmail.SendUsingAccount = account;
                    }
                }

                if (control.Context is Inspector)
                {
                    Inspector inspector = (Inspector)control.Context;

                    // This handles sharepoint posts
                    if (inspector.CurrentItem is Microsoft.Office.Interop.Outlook.PostItem)
                    {
                        PostItem m = inspector.CurrentItem as PostItem;

                        if (string.IsNullOrEmpty(m.Subject))
                        {
                            string standardSuffix = StaticHelper.GetStandardSuffix(idParts[0]);
                            if (!string.IsNullOrEmpty(standardSuffix))
                            {
                                m.Subject = newEmail.Subject.Replace(standardSuffix, string.Empty);
                            }
                            else
                            {
                                m.Subject = newEmail.Subject;
                            }
                        }
                        else
                        {
                            string standardSuffix = StaticHelper.GetStandardSuffix(idParts[0]);
                            if (!string.IsNullOrEmpty(standardSuffix))
                            {
                                newEmail.Subject = newEmail.Subject.Replace(standardSuffix, string.Empty);
                            }

                            m.Subject = newEmail.Subject + m.Subject;
                        }

                        return;
                    }

                    if (inspector.CurrentItem is MailItem)
                    {
                        MailItem m = inspector.CurrentItem as MailItem;
                        if (!string.IsNullOrEmpty(newEmail.To))
                        {
                            m.To = newEmail.To;
                        }

                        if (!string.IsNullOrEmpty(newEmail.CC))
                        {
                            m.CC = newEmail.CC;
                        }

                        if (!string.IsNullOrEmpty(newEmail.BCC))
                        {
                            m.BCC = newEmail.BCC;
                        }

                        m.Importance = newEmail.Importance;

                        if (!string.IsNullOrEmpty(from))
                        {
                            // Retrieve the account that has the specific SMTP address.
                            Account account = GetAccountForEmailAddress(outlookApp, from);
                            if (account != null)
                            {
                                // Use this account to send the e-mail.
                                m.SendUsingAccount = account;
                            }
                        }

                        if (string.IsNullOrEmpty(m.Subject))
                        {
                            m.Subject = newEmail.Subject;
                        }
                        else
                        {
                            string standardSuffix = StaticHelper.GetStandardSuffix(idParts[0]);
                            if (!string.IsNullOrEmpty(standardSuffix))
                            {
                                newEmail.Subject = newEmail.Subject.Replace(standardSuffix, string.Empty);
                            }

                            m.Subject = newEmail.Subject + m.Subject;
                        }
                    }
                }
                else
                {
                    string html = StaticHelper.GetTemplate(control.Id);
                    if (!string.IsNullOrEmpty(html))
                    {
                        ////newEmail.HTMLBody += html;

                        ////MailItem newEmail2 = (MailItem)outlookApp.CreateItem(OlItemType.olMailItem);

                        ////Inspector objSigDoc = newEmail2.GetInspector;

                        ////string s = objSigDoc.ToString();
                    }

                    newEmail.Display();
                }
            }
            catch (System.Exception ex)
            {
                StaticHelper.LogMessage(MessageType.Error, ex.ToString());
                throw;
            }
        }
        public void Meeting(IRibbonControl control, string subject, OlImportance importance)
        {
            try
            {
                string[] idParts = control.Id.Split(new[] { StaticHelper.SplitSequence }, StringSplitOptions.RemoveEmptyEntries);
                Application outlookApp = new ApplicationClass();
                AppointmentItem newMeeting = (AppointmentItem)outlookApp.CreateItem(OlItemType.olAppointmentItem);
                newMeeting.MeetingStatus = OlMeetingStatus.olMeeting;

                // Get the recipients
                string[] recipients = StaticHelper.GetRecipients(idParts[0], control.Id);
                if (!string.IsNullOrEmpty(recipients[0]))
                {
                    foreach (Recipient recipRequired in recipients[0].Split(new[] { ';' }).Select(s => newMeeting.Recipients.Add(s)))
                    {
                        recipRequired.Type = (int)OlMeetingRecipientType.olRequired;
                    }
                }

                if (!string.IsNullOrEmpty(recipients[1]))
                {
                    foreach (Recipient recipOptional in recipients[1].Split(new[] { ';' }).Select(s => newMeeting.Recipients.Add(s)))
                    {
                        recipOptional.Type = (int)OlMeetingRecipientType.olOptional;
                    }
                }

                newMeeting.Subject = subject;
                newMeeting.Importance = importance;

                string from = StaticHelper.GetApplicationSetting("MasterEmailAccount");
                if (string.IsNullOrEmpty(from))
                {
                    from = StaticHelper.GetFromAccount(idParts[0]);
                }
 
                if (!string.IsNullOrEmpty(from))
                {
                    // Retrieve the account that has the specific SMTP address.
                    Account account = GetAccountForEmailAddress(outlookApp, from);
                    if (account != null)
                    {
                        // Use this account to send the e-mail.
                        newMeeting.SendUsingAccount = account;
                    }
                }

                if (control.Context is Inspector)
                {
                    Inspector inspector = (Inspector)control.Context;
                    if (inspector.CurrentItem is AppointmentItem)
                    {
                        AppointmentItem m = inspector.CurrentItem as AppointmentItem;

                        // Get the recipients
                        string[] recipients2 = StaticHelper.GetRecipients(idParts[0], control.Id);
                        if (!string.IsNullOrEmpty(recipients2[0]))
                        {
                            foreach (Recipient recipRequired in recipients2[0].Split(new[] { ';' }).Select(s => newMeeting.Recipients.Add(s)))
                            {
                                recipRequired.Type = (int)OlMeetingRecipientType.olRequired;
                            }
                        }

                        if (!string.IsNullOrEmpty(recipients2[1]))
                        {
                            foreach (Recipient recipOptional in recipients2[1].Split(new[] { ';' }).Select(s => newMeeting.Recipients.Add(s)))
                            {
                                recipOptional.Type = (int)OlMeetingRecipientType.olOptional;
                            }
                        }

                        if (string.IsNullOrEmpty(m.Subject))
                        {
                            m.Subject = newMeeting.Subject;
                        }
                        else
                        {
                            string standardSuffix = StaticHelper.GetStandardSuffix(idParts[0]);
                            if (!string.IsNullOrEmpty(standardSuffix))
                            {
                                newMeeting.Subject = newMeeting.Subject.Replace(standardSuffix, string.Empty);
                            }

                            m.Subject = newMeeting.Subject + m.Subject;
                        }

                        if (!string.IsNullOrEmpty(from))
                        {
                            // Retrieve the account that has the specific SMTP address.
                            Account account = GetAccountForEmailAddress(outlookApp, from);
                            if (account != null)
                            {
                                // Use this account to send the e-mail.
                                m.SendUsingAccount = account;
                            }
                        }
                    }
                }
                else
                {
                    newMeeting.Display();
                }
            }
            catch (System.Exception ex)
            {
                StaticHelper.LogMessage(MessageType.Error, ex.ToString());
                throw;
            }
        }
        public void Send(IRibbonControl control, string subject, OlImportance importance)
        {
            try
            {
                string[] idParts = control.Id.Split(new[] { StaticHelper.SplitSequence }, StringSplitOptions.RemoveEmptyEntries);
                Application outlookApp = new ApplicationClass();
                MailItem newEmail = (MailItem)outlookApp.CreateItem(OlItemType.olMailItem);

                // Get the recipients
                string[] recipients = StaticHelper.GetRecipients(idParts[0], control.Id);
                newEmail.To = recipients[0];
                newEmail.CC = recipients[1];
                newEmail.BCC = recipients[2];
                newEmail.Subject = subject;
                newEmail.Importance = importance;

                string from = StaticHelper.GetApplicationSetting("MasterEmailAccount");
                if (string.IsNullOrEmpty(from))
                {
                    from = StaticHelper.GetFromAccount(idParts[0]);
                }

                if (!string.IsNullOrEmpty(from))
                {
                    // Retrieve the account that has the specific SMTP address.
                    Account account = GetAccountForEmailAddress(outlookApp, from);
                    if (account != null)
                    {
                        // Use this account to send the e-mail.
                        newEmail.SendUsingAccount = account;
                    }
                }

                if (control.Context is Inspector)
                {
                    Inspector inspector = (Inspector)control.Context;

                    // This handles sharepoint posts
                    if (inspector.CurrentItem is Microsoft.Office.Interop.Outlook.PostItem)
                    {
                        PostItem m = inspector.CurrentItem as PostItem;

                        if (string.IsNullOrEmpty(m.Subject))
                        {
                            string standardSuffix = StaticHelper.GetStandardSuffix(idParts[0]);
                            if (!string.IsNullOrEmpty(standardSuffix))
                            {
                                m.Subject = newEmail.Subject.Replace(standardSuffix, string.Empty);
                            }
                            else
                            {
                                m.Subject = newEmail.Subject;
                            }
                        }
                        else
                        {
                            string standardSuffix = StaticHelper.GetStandardSuffix(idParts[0]);
                            if (!string.IsNullOrEmpty(standardSuffix))
                            {
                                newEmail.Subject = newEmail.Subject.Replace(standardSuffix, string.Empty);
                            }

                            m.Subject = newEmail.Subject + m.Subject;
                        }

                        return;
                    }

                    if (inspector.CurrentItem is MailItem)
                    {
                        MailItem m = inspector.CurrentItem as MailItem;
                        if (!string.IsNullOrEmpty(newEmail.To))
                        {
                            m.To = newEmail.To;
                        }

                        if (!string.IsNullOrEmpty(newEmail.CC))
                        {
                            m.CC = newEmail.CC;
                        }

                        if (!string.IsNullOrEmpty(newEmail.BCC))
                        {
                            m.BCC = newEmail.BCC;
                        }

                        m.Importance = newEmail.Importance;

                        if (!string.IsNullOrEmpty(from))
                        {
                            // Retrieve the account that has the specific SMTP address.
                            Account account = GetAccountForEmailAddress(outlookApp, from);
                            if (account != null)
                            {
                                // Use this account to send the e-mail.
                                m.SendUsingAccount = account;
                            }
                        }

                        if (string.IsNullOrEmpty(m.Subject))
                        {
                            m.Subject = newEmail.Subject;
                        }
                        else
                        {
                            string standardSuffix = StaticHelper.GetStandardSuffix(idParts[0]);
                            if (!string.IsNullOrEmpty(standardSuffix))
                            {
                                newEmail.Subject = newEmail.Subject.Replace(standardSuffix, string.Empty);
                            }

                            m.Subject = newEmail.Subject + m.Subject;
                        }
                    }
                }
                else
                {
                    string html = StaticHelper.GetTemplate(control.Id);
                    if (!string.IsNullOrEmpty(html))
                    {
                        ////newEmail.HTMLBody += html;

                        ////MailItem newEmail2 = (MailItem)outlookApp.CreateItem(OlItemType.olMailItem);

                        ////Inspector objSigDoc = newEmail2.GetInspector;

                        ////string s = objSigDoc.ToString();
                    }

                    newEmail.Display();
                }
            }
            catch (System.Exception ex)
            {
                StaticHelper.LogMessage(MessageType.Error, ex.ToString());
                throw;
            }
        }
Пример #11
-1
        private void btnMerge_Click(object sender, EventArgs e)
        {
            bool checkBox = true;
            bool sendAsCheck = true;

            //Default index values
            int primaryEmailIndex = 0;
            int cc1Index = 1;
            int cc2Index = 2;
            int cc3Index = 3;

            if (rbtnYes.Checked == true)
            {
                checkBox = isChecked(cboxConfirm);
                sendAsCheck = checkSendAsEmail(ddSendAs);

            }

            if (isPresent(txtSavePath, "Save Path") && isPresent(txtWordDoc, "Word Doc Path") && isPresent(txtExcelDoc, "Excel Path") && checkBox && sendAsCheck)
            {
                if (isWord(txtWordDoc) && isExcel(txtExcelDoc))
                {

                    try
                    {
                        string saveToPath = txtSavePath.Text.ToString() + "\\";

                        //Declare word doc stuff
                        Microsoft.Office.Interop.Word.Application application1 = new Microsoft.Office.Interop.Word.Application();
                        Microsoft.Office.Interop.Word.Document document1 = new Microsoft.Office.Interop.Word.Document();

                        //Get the Word Doc
                        string docPath = txtWordDoc.Text.ToString();

                        //application1.Visible = true;

                        //Declare excel Doc stuff
                        Microsoft.Office.Interop.Excel.Application xlApp;
                        Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
                        Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;

                        string excelPath = txtExcelDoc.Text.ToString();

                        object misValue = System.Reflection.Missing.Value;
                        xlApp = new Microsoft.Office.Interop.Excel.Application();
                        xlWorkBook = xlApp.Workbooks.Add(excelPath);
                        xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

                        //xlApp.Visible = true;

                        DataTable sheet1 = generateDT(excelPath);

                        int rowCount = sheet1.Rows.Count;
                        int colCount = sheet1.Columns.Count;

                        //Adds dynamic fields
                        List<WordField> fields = new List<WordField>();
                        List<int> headerPositions = new List<int>();
                        for (int k = 0; k < colCount; k++)
                        {
                            fields.Add(new WordField() { field = sheet1.Rows[0][k].ToString(), positionIndex = k});

                            if (fields[k].field.Contains("PrimaryEmail")|| fields[k].field.Contains("Email"))
                            {
                                primaryEmailIndex = k;
                            }
                            if (fields[k].field.Contains("CC1"))
                            {
                                cc1Index = k;
                            }
                            if (fields[k].field.Contains("CC2"))
                            {
                                cc2Index = k;
                            }
                            if (fields[k].field.Contains("CC3"))
                            {
                                cc3Index = k;
                            }
                            foreach (string n in listRecieved)
                            {
                                if (fields[k].field.Contains(n))
                                {
                                    headerPositions.Add(k);
                                }

                            }

                        }

                        int totalEmailCount = 0;
                        for (int i = 1; i < rowCount; i++)//i, row value
                        {
                            document1 = application1.Documents.Add(docPath);

                            foreach (Microsoft.Office.Interop.Word.Field field in document1.Fields)
                            {
                                int currentCol = 0;
                                do
                                {
                                    string fieldTarget = field.Code.Text.ToString();
                                    string fieldTest = fields[currentCol].field.ToString();
                                    bool test = fieldTarget.Contains(fieldTest);
                                    if (test)//field.Code.Text.Contains(fields[currentCol].field.ToString())
                                    {
                                        field.Select();

                                        if (fieldTest == "" || String.IsNullOrEmpty(fieldTest))
                                        {
                                            application1.Selection.TypeText(" ");
                                        }
                                        else
                                        {
                                            application1.Selection.TypeText(sheet1.Rows[i][currentCol].ToString());
                                        }

                                        break;
                                    }
                                    currentCol+=1;

                                }
                                while(currentCol< colCount);

                            }
                            //Determine save format
                            string fileExtension;
                            object format = new Microsoft.Office.Interop.Word.WdSaveFormat();
                            if (rbtnPDF.Checked == true)
                            {
                                fileExtension = ".PDF";
                                format = Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatPDF;
                            }
                            else
                            {
                                fileExtension = ".docx";
                                format = Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatDocumentDefault;
                            }

                            //Name of doc
                            string rootName = "";
                            if (headerPositions.Count != listRecieved.Count)
                            {
                                rootName = listRecieved[0].ToString();
                            }

                            string docNameRaw = "";
                            foreach (int pos in headerPositions)
                            {
                                docNameRaw += sheet1.Rows[i][pos].ToString()+"_";
                            }

                            if (rootName.Length > 1)
                            {
                                docNameRaw = rootName + "_" + docNameRaw;
                            }

                            string docName = saveToPath + docNameRaw.Substring(0,docNameRaw.Length-1) + fileExtension;

                            document1.SaveAs2(FileName: docName, FileFormat: format);

                            if (rbtnYes.Checked == true)
                            {

                                    //Email stuff
                                    ApplicationClass oApp = new ApplicationClass();
                                    MailItem mailItem = (MailItem)oApp.CreateItem(OlItemType.olMailItem);

                                    Recipients oRecips = mailItem.Recipients;

                                    List<string> sToRecipsList = new List<string>();

                                    string primaryEmail = sheet1.Rows[i][primaryEmailIndex].ToString();
                                    List<string> sCCRecipsList = new List<string>();
                                    List<int> ccIndexList = new List<int>();
                                    ccIndexList.Add(cc1Index);
                                    ccIndexList.Add(cc2Index);
                                    ccIndexList.Add(cc3Index);

                                    int numofCC = Convert.ToInt16(cmbCCNumber.SelectedItem.ToString());

                                    for (int iC = 0; iC < numofCC; iC++)
                                    {
                                        sCCRecipsList.Add(sheet1.Rows[i][ccIndexList[iC]].ToString());
                                    }

                                    sToRecipsList.Add(primaryEmail);

                                    foreach (string t in sToRecipsList)
                                    {
                                        if (string.IsNullOrEmpty(t) == false && t.Length > 1)
                                        {
                                            Recipient oTORecip = oRecips.Add(t);
                                            oTORecip.Type = (int)OlMailRecipientType.olTo;
                                            oTORecip.Resolve();
                                        }

                                    }

                                    foreach (string t in sCCRecipsList)
                                    {
                                        if (string.IsNullOrEmpty(t) == false && t.Length > 1)
                                        {
                                            Recipient oCCRecip = oRecips.Add(t);
                                            oCCRecip.Type = (int)OlMailRecipientType.olCC;
                                            oCCRecip.Resolve();
                                        }

                                    }

                                    string msgBody = formatLineBreaks(txtEmailBody.Text.ToString());
                                    string subjectLine = txtEmailSubject.Text.ToString();
                                    string msg =
                                       "<html>" +
                                       "<body>" +
                                       "<p>" + msgBody + "</p> <br/>" +
                                       "<p> Sincerely,</p> <br/>" +
                                       "<p><img src='http://www.lahsa.org/images/LAHSAlogoCL.png' alt='LAHSA Logo'/></p>" +
                                       "</body>" +
                                       "</html>";
                                    mailItem.SentOnBehalfOfName = ddSendAs.SelectedValue.ToString();
                                    mailItem.HTMLBody = msg;
                                    mailItem.Subject = subjectLine;
                                    //mailItem.Attachments.Add(@"C:\Users\andrewa\Desktop\Applications Dev\mailMerge_v1\Test Docs\TestWord" + docName + ".PDF", Microsoft.Office.Interop.Outlook.OlAttachmentType.olByValue, 1, @"C:\Users\andrewa\Desktop\Applications Dev\mailMerge_v1\Test Docs\TestWord" + docName + ".PDF");
                                    mailItem.Attachments.Add(docName, Microsoft.Office.Interop.Outlook.OlAttachmentType.olByValue, 1, docName);

                                    if (sToRecipsList[0].Length > 1 )
                                    {
                                        mailItem.Send();
                                        totalEmailCount += 1;
                                    }

                            }

                        }

                        //Alert that all emails have been sent
                        string alrtMsg = "A total of " + totalEmailCount.ToString()  + " emails have been sent, please close the application :-)";
                        MessageBox.Show(alrtMsg, "Emails Succesfully Sent!");

                    }
                    catch (System.Exception ex)
                    {
                        MessageBox.Show(ex.ToString());
                    }

                }
            }
        }