Пример #1
2
        private void button1_Click(object sender, RibbonControlEventArgs e)
        {
            Outlook.Application application = new Outlook.Application();
            Outlook.NameSpace ns = application.GetNamespace("MAPI");

            try
            {
                //get selected mail item
                Object selectedObject = application.ActiveExplorer().Selection[1];
                Outlook.MailItem selectedMail = (Outlook.MailItem)selectedObject;

                //create message
                Outlook.MailItem newMail = application.CreateItem(Outlook.OlItemType.olMailItem) as Outlook.MailItem;
                newMail.Recipients.Add(ReadFile());
                newMail.Subject = "SPAM";
                newMail.Attachments.Add(selectedMail, Microsoft.Office.Interop.Outlook.OlAttachmentType.olEmbeddeditem);

                newMail.Send();
                selectedMail.Delete();

                System.Windows.Forms.MessageBox.Show("Spam notification has been sent.");
            }
            catch
            {
                System.Windows.Forms.MessageBox.Show("You must select a message to report.");
            }
        }
Пример #2
1
 public OutlookEmailSender2()
 {
     Outlook.Application olApplication = new Outlook.Application();
     Outlook.NameSpace olNameSpace = olApplication.GetNamespace("mapi");
     olNameSpace.Logon(Type.Missing, Type.Missing, true, true);
     olMailItem = (Outlook.MailItem)olApplication.CreateItem(Outlook.OlItemType.olMailItem);
     olRecipients = olMailItem.Recipients;
     olApplication.ItemSend += new Outlook.ApplicationEvents_11_ItemSendEventHandler(olApplication_ItemSend);
 }
Пример #3
0
 protected override ActivityExecutionStatus Execute(ActivityExecutionContext context)
 {
     // Create an Outlook Application object. 
     Outlook.Application outlookApp = new Outlook.Application();
     // Create a new TaskItem.
     Outlook.NoteItem newNote = (Outlook.NoteItem)outlookApp.CreateItem(Outlook.OlItemType.olNoteItem);
     // Configure the task at hand and save it.
     if (this.Parent.Parent is ParallelActivity)
     {
         newNote.Body = (this.Parent.Parent.Parent.Activities[1] as DummyActivity).TitleProperty;
         if ((this.Parent.Parent.Parent.Activities[1] as DummyActivity).TitleProperty != "")
         {
             MessageBox.Show("Creating Outlook Note");
             newNote.Save();
         }
     }
     else if (this.Parent.Parent is SequentialWorkflowActivity)
     {
         newNote.Body = (this.Parent.Parent.Activities[1] as DummyActivity).TitleProperty;
         if ((this.Parent.Parent.Activities[1] as DummyActivity).TitleProperty != "")
         {
             MessageBox.Show("Creating Outlook Note");
             newNote.Save();
         }
     }
     return ActivityExecutionStatus.Closed;
 }
Пример #4
0
    protected void Page_PreRender(object sender, EventArgs e)
    {
        OutLook._Application outlookObj = new OutLook.Application();

         //Button btnPlaySong =  (Button) this.form.FindControl("btnPlaySong");
        //Song.rr  = Request.PhysicalApplicationPath.ToString();
    }
Пример #5
0
    public static void Main(string[] args)
    {
        Outlook.Application application = null;

        application = Marshal.GetActiveObject("Outlook.Application") as Outlook.Application;
        application = new Outlook.Application();
        Outlook.NameSpace nameSpace = application.GetNamespace("MAPI");

        Outlook.MAPIFolder userFolder = null;
        Outlook.MAPIFolder emailFolder = nameSpace.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox);

        try
        {
            foreach (Outlook.MailItem item in emailFolder.Items)
            {
                if (SearchAttachments(item.Attachments, args[0]))
                {
                    Console.WriteLine(item.Subject);
                    break;
                }

            }
        }
        catch (Exception message)
        {
            Console.WriteLine(message);
        }
    }
Пример #6
0
        public Microsoft.Office.Interop.Outlook.Application Initialise()
        {
           
            if (!MapiProfileHelperIsRegistered())
            {
                RegisterMapiProfileHelper();
                {
                    if (!MapiProfileHelperIsRegistered())
                        throw new System.Exception("You need to register the MapiProfileHelper for these tests to run.");
                }
            }
            m_bOutlookWasRunningBeforeSenderStarted = IsOutlookRuuning();
            HideOutlookLogonProfileDialog();
            SetMailProfile();
            try
            {
                m_outlookApplication = new Microsoft.Office.Interop.Outlook.Application();
            }
            catch (COMException)
            {
                Thread.Sleep(2000); // Outlook 2010 seems twitchy and can respond with an error indicating its not ready - wait and try again
                m_outlookApplication = new Microsoft.Office.Interop.Outlook.Application();
            }


            return m_outlookApplication;
        }
 private void InitializeObjects()
 {
     _myApp = new Microsoft.Office.Interop.Outlook.Application();
     _mapiNameSpace = _myApp.GetNamespace("MAPI");
     _mapiFolder = _mapiNameSpace.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox);
     
 } 
Пример #8
0
        public List<CalendarEvent> GetCalendarEvents(DateTime rangeFrom, DateTime rangeTo)
        {
            var app = new Outlook.Application();

            Outlook.Folder calendarFolder = app.Session.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderCalendar) as Outlook.Folder;

            Outlook.Items outlookEvents = getAppointmentsInRange(calendarFolder, rangeFrom, rangeTo);

            List<CalendarEvent> calendarEvents = new List<CalendarEvent>();

            foreach (Outlook.AppointmentItem outlookEvent in outlookEvents)
            {
                var calendarEvent = new OutlookCalendarEvent()
                {
                    DateFrom = outlookEvent.Start,
                    DateTo = outlookEvent.End,
                    Description = string.Format("{0}", outlookEvent.Body),
                    Location = outlookEvent.Location,
                    Title = outlookEvent.Subject,
                    ID = outlookEvent.GlobalAppointmentID,
                    SourceID = outlookEvent.ItemProperties["SourceID"] != null ? outlookEvent.ItemProperties["SourceID"].ToString() : outlookEvent.GlobalAppointmentID
                };

                calendarEvents.Add(calendarEvent);
            }

            return calendarEvents;
        }
Пример #9
0
        public void SendEmailUsingOutLook(string witBody,String witName, List<Docs> docs)
        {

            Microsoft.Office.Interop.Outlook.Application outlookApplication =
            new Microsoft.Office.Interop.Outlook.Application();

            Microsoft.Office.Interop.Outlook.MailItem email =
            (Microsoft.Office.Interop.Outlook.MailItem)outlookApplication.CreateItem(Microsoft.Office.Interop.Outlook.OlItemType.olMailItem);

            email.BodyFormat = Microsoft.Office.Interop.Outlook.OlBodyFormat.olFormatRichText;
            email.Subject = witName;
            email.HTMLBody = witBody;

            if (docs != null && docs.Count > 0) {

                foreach (var doc in docs) {
                    if (doc.docId != null)
                    {
                        email.Attachments.Add(doc.localPath + "" + doc.fileName, Microsoft.Office.Interop.Outlook.OlAttachmentType.olByValue, 100000, Type.Missing);
                    }
                }
            }
           

            email.Display(true);

        }
Пример #10
0
        private void ThisAddIn_Startup(object sender, System.EventArgs e)
        {
            Microsoft.Office.Interop.Outlook._Application OutlookObject = new Microsoft.Office.Interop.Outlook.Application();
            //Create a new Contact Item
            Microsoft.Office.Interop.Outlook.ContactItem contact = OutlookObject.CreateItem(
                                    Microsoft.Office.Interop.Outlook.OlItemType.olContactItem);

            //Set different properties of this Contact Item.
            contact.FirstName = "Mellissa";
            contact.LastName = "MacBeth";
            contact.JobTitle = "Account Representative";
            contact.CompanyName = "Contoso Ltd.";
            contact.OfficeLocation = "36/2529";
            contact.BusinessTelephoneNumber = "4255551212 x432";
            contact.BusinessAddressStreet = "1 Microsoft Way";
            contact.BusinessAddressCity = "Redmond";
            contact.BusinessAddressState = "WA";
            contact.BusinessAddressPostalCode = "98052";
            contact.BusinessAddressCountry = "United States of America";
            contact.Email1Address = "*****@*****.**";
            contact.Email1AddressType = "SMTP";
            contact.Email1DisplayName = "Melissa MacBeth ([email protected])";

            //Save the Contact to disc
            contact.SaveAs("OutlookContact.vcf", OlSaveAsType.olVCard);
        }
Пример #11
0
        public void AddAppointment(Appointment apt)
        {
            try
            {
                Outlook.Application outlookApp = new Outlook.Application(); // creates new outlook app
                Outlook.AppointmentItem oAppointment = (Outlook.AppointmentItem)outlookApp.CreateItem(Outlook.OlItemType.olAppointmentItem); // creates a new appointment

                oAppointment.Subject = apt.Subject;
                oAppointment.Body = apt.Body;
                oAppointment.Location = apt.Location;
                oAppointment.Start = Convert.ToDateTime(apt.StartTime);
                oAppointment.End = Convert.ToDateTime(apt.EndTime);
                oAppointment.ReminderSet = true;
                oAppointment.ReminderMinutesBeforeStart = apt.ReminderMinutesBeforeStart;
                oAppointment.Importance = Outlook.OlImportance.olImportanceHigh;
                oAppointment.BusyStatus = Outlook.OlBusyStatus.olBusy;
                oAppointment.RequiredAttendees = apt.RequiredAttendees;

                oAppointment.Save();

                Outlook.MailItem mailItem = oAppointment.ForwardAsVcal();
                // email address to send to
                mailItem.To = apt.RequiredAttendees +";" + apt.Organizer; //" [email protected]";
                // send
                mailItem.Send();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message + "\r\n" + ex.InnerException + "\r\n" + "\r\n");
            }
        }
Пример #12
0
 }//end of Email Method
 public static void CreateOutlookEmail(List<string> toList, string subject, string msg, string attachementFileName = null)
 {
     try
     {
         Outlook.Application outlookApp = new Outlook.Application();
         Outlook.MailItem mailItem = (Outlook.MailItem)outlookApp.CreateItem(Outlook.OlItemType.olMailItem);
         mailItem.Subject = subject;
         Outlook.Recipients oRecips = mailItem.Recipients;
         if (toList != null)
         {
             foreach (var i in toList)
             {
                 Outlook.Recipient oRecip = oRecips.Add(i);
                 oRecip.Resolve();
             }
         }
         
         if (attachementFileName != null)
         {
             //int iPosition = (int) mailItem.Body.Length + 1;
             //int iAttachType = (int) Outlook.OlAttachmentType.olByValue;
             //now attached the file
             mailItem.Attachments.Add(attachementFileName);
         }
         mailItem.HTMLBody += msg;
         mailItem.Display(true);
     }
     catch (Exception eX)
     {
         throw new Exception("cDocument: Error occurred trying to Create an Outlook Email"
                             + Environment.NewLine + eX.Message);
     }
 }
        private void sendEmail(EmailObject eml)
        {
            string myDate = today.ToString("dd MMMM yyyy");
            //new outlook instance

            Outlook.Application app = new Outlook.Application();
            Outlook.MailItem mail = app.CreateItem(Outlook.OlItemType.olMailItem);
            {
                string[] files = Directory.GetFiles(AttachmentDestination);
                int fileCount = 0;
                foreach (string file in files)
                {
                    Console.WriteLine("attatching file : " + file);
                    mail.Attachments.Add(file);
                    fileCount++;
                }
                if (fileCount > 0)
                {
                    mail.Importance = Outlook.OlImportance.olImportanceHigh;
                    mail.Subject = myDate + " " + eml.EmailSubject;
                    mail.To = eml.Emails;
                    mail.Body = eml.EmailBody;
                    Console.WriteLine("sending...");
                    mail.Send();
                }
            }
        }
Пример #14
0
		public override string Print(WorkbookItem wi)
		{
			using (new WsActivationContext())
			{
				string destination = Utilities.GetTemporaryFileWithPdfExtension();

				Outlook._Application app = new Outlook.Application();
				Outlook._MailItem mailItem = app.Session.OpenSharedItem(wi.FileName) as Outlook._MailItem;
				try
				{
				if (mailItem == null)
				{
					return null;
				}

					Publisher.PublishWithOutlook(destination, mailItem);
				}
				finally
				{
					if (mailItem != null)
					{
					mailItem.Close(Outlook.OlInspectorClose.olDiscard);
						System.Runtime.InteropServices.Marshal.ReleaseComObject(mailItem);
				}
				}

				return destination;
			}
		}
Пример #15
0
        private void ThisAddIn_Startup(object sender, System.EventArgs e)
        {
            // Create an object of type Outlook.Application
            Outlook.Application objOutlook = new Outlook.Application();

            //Create an object of type olMailItem
            Outlook.MailItem oIMailItem = objOutlook.CreateItem(Outlook.OlItemType.olMailItem);

            //Set properties of the message file e.g. subject, body and to address
            //Set subject
            oIMailItem.Subject = "This MSG file is created using Office Automation.";
            //Set to (recipient) address
            oIMailItem.To = "*****@*****.**";
            //Set body of the email message
            oIMailItem.HTMLBody = "<html><p>This MSG file is created using VBA code.</p>";

            //Add attachments to the message
            oIMailItem.Attachments.Add("image.bmp");
            oIMailItem.Attachments.Add("pic.jpeg");

            //Save as Outlook MSG file
            oIMailItem.SaveAs("testvba.msg");

            //Open the MSG file
            oIMailItem.Display();
        }
Пример #16
0
        protected override ActivityExecutionStatus Execute(ActivityExecutionContext context)
        {
            // Create an Outlook Application object. 
            Outlook.Application outlookApp = new Outlook.Application();
            // Create a new TaskItem.
            Outlook.TaskItem newTask = (Outlook.TaskItem)outlookApp.CreateItem(Outlook.OlItemType.olTaskItem);
            // Configure the task at hand and save it.
            newTask.Body = "Workflow Generated Task";
            newTask.DueDate = DateTime.Now;
            newTask.Importance = Outlook.OlImportance.olImportanceHigh;

            if (this.Parent.Parent is ParallelActivity)
            {
                newTask.Subject = (this.Parent.Parent.Parent.Activities[1] as DummyActivity).TitleProperty;
                if ((this.Parent.Parent.Parent.Activities[1] as DummyActivity).TitleProperty != "")
                {
                    MessageBox.Show("Creating Outlook Task");
                    newTask.Save();
                }
            }
            else if (this.Parent.Parent is SequentialWorkflowActivity)
            {
                newTask.Subject = (this.Parent.Parent.Activities[1] as DummyActivity).TitleProperty;
                if ((this.Parent.Parent.Activities[1] as DummyActivity).TitleProperty != "")
                {
                    MessageBox.Show("Creating Outlook Task");
                    newTask.Save();
                }
            }
            return ActivityExecutionStatus.Closed;
        }
Пример #17
0
 public static void SendEMailThroughOutlook(List<string> toList, string subject, string msg, string attachementFileName = null  )
 {
         // Create the Outlook application.
         Outlook.Application oApp = new Outlook.Application();
         // Create a new mail item.
         Outlook.MailItem oMsg = (Outlook.MailItem)oApp.CreateItem(Outlook.OlItemType.olMailItem);
         // Set HTMLBody. 
         //add the body of the email
         oMsg.HTMLBody += msg;
         //Add an attachment.
          String sDisplayName = "Coopcheck Log";
         int iPosition = (int)oMsg.Body.Length + 1;
         int iAttachType = (int)Outlook.OlAttachmentType.olByValue;
         // now attached the file
         Outlook.Attachment oAttach = oMsg.Attachments.Add(attachementFileName, iAttachType, iPosition, sDisplayName);
         //Subject line
         oMsg.Subject = subject;
         // Add a recipient.
         Outlook.Recipients oRecips = (Outlook.Recipients)oMsg.Recipients;
         // Change the recipient in the next line if necessary.
         foreach (var i in toList)
         {
             Outlook.Recipient oRecip = (Outlook.Recipient) oRecips.Add(i);
             oRecip.Resolve();
         }
         oMsg.Send();
     }
Пример #18
0
 public SettingsManager(Outlook.Application app)
 {
     Application = app;
     this.profile = Application.Session.CurrentProfileName;
     Outlook.Folder oInbox = (Outlook.Folder)Application.Session.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox);
     this.storage = oInbox.GetStorage("calcifyStore", Outlook.OlStorageIdentifierType.olIdentifyBySubject);
 }
Пример #19
0
        //This function is taken from the MSDN :
        //https://msdn.microsoft.com/en-us/library/office/ff462097.aspx
        public static Outlook.Application GetApplicationObject()
        {
            Outlook.Application application = null;

            // Check if there is an Outlook process running.
            if (Process.GetProcessesByName("OUTLOOK").Count() > 0)
            {
                try
                {
                    // If so, use the GetActiveObject method to obtain the process and cast it to an Application object.
                    application = Marshal.GetActiveObject("Outlook.Application") as Outlook.Application;
                }
                catch
                {
                    //log to windows logs
                    application = new Outlook.Application();
                    Outlook.NameSpace nameSpace = application.GetNamespace("MAPI");
                    nameSpace.Logon("", "", false, Missing.Value);
                    nameSpace = null;
                }

            }
            else
            {

                // If not, create a new instance of Outlook and log on to the default profile.
                application = new Outlook.Application();
                Outlook.NameSpace nameSpace = application.GetNamespace("MAPI");
                nameSpace.Logon("", "", false, Missing.Value);
                nameSpace = null;
            }

            // Return the Outlook Application object.
            return application;
        }
Пример #20
0
 private void ThisAddIn_Startup(object sender, System.EventArgs e)
 {
     OutlookApplication = Application as Outlook.Application;
     OutlookInspectors = OutlookApplication.Inspectors;
     OutlookInspectors.NewInspector += new Microsoft.Office.Interop.Outlook.InspectorsEvents_NewInspectorEventHandler(OutlookInspectors_NewInspector);
     OutlookApplication.ItemSend += new Microsoft.Office.Interop.Outlook.ApplicationEvents_11_ItemSendEventHandler(OutlookApplication_ItemSend);
 }
Пример #21
0
		public void TestFixtureSetUp()
		{
			_sender = new EmailSender();
			_app = _sender.Initialise();
			_outlookSession = _app.Session;
			_outlookSession.Logon("Outlook", "", false, true);
		}
Пример #22
0
 public OLCalReader(String profileName)
 {
     myOutlook = new Outlook.Application ();
     myProfile = myOutlook.Session;
     this.profileName = profileName;
     Logon ();
 }
Пример #23
0
        public MainWindow()
        {
            InitializeComponent();
            _outlook = new Outlook.Application(); // TODO: is it ok to instantiate this once?
            _currentUser = _outlook.Application.Session.CurrentUser.AddressEntry;

            txtAlias.Focus();
        }
Пример #24
0
 private void exportToMail_Click(object sender, EventArgs e)
 {
     Outlook.Application oApp = new Outlook.Application();
     Outlook._MailItem oMailItem = (Outlook._MailItem)oApp.CreateItem(Outlook.OlItemType.olMailItem);
     oMailItem.To = "*****@*****.**";
     oMailItem.HTMLBody = this.generateHTML();
     oMailItem.Display(true);
 }
Пример #25
0
        public bool SendMail(DbEmail email)
        {
            Outlook.Attachment oAttach;
            try
            {
                // Create the Outlook application by using inline initialization.
                Outlook.Application oApp = new Outlook.Application();

                //Create the new message by using the simplest approach.
                Outlook.MailItem oMsg = (Outlook.MailItem)oApp.CreateItem(Outlook.OlItemType.olMailItem);

                //Add a recipient
                Outlook.Recipient oRecip = (Outlook.Recipient)oMsg.Recipients.Add(email.Recipient);
                oRecip.Resolve();

                //Set the basic properties.
                oMsg.Subject = email.Subject;
                oMsg.Body = email.Body;

                //Add an attachment

                //if (email.Attachments.Count > 0)
                //{
                //    for (int i = 0; i < email.Attachments.Count(); i++)
                //    {
                //        String sSource = email.Attachments[i];
                //        String sDisplayName = email.Subject;
                //        int iPosition = (int)oMsg.Body.Length + 1;
                //        int iAttachType = (int)Outlook.OlAttachmentType.olByValue;
                //        oAttach = oMsg.Attachments.Add(sSource, iAttachType, iPosition, sDisplayName);
                //    }
                //}

                // If you want to, display the message.
                // oMsg.Display(true);  //modal

                //Send the message.
                oMsg.Save();
                //(oMsg as _Outlook.MailItem).Send();
                //Outlook.Account account = oApp.Session.Accounts[email.Sender];
                //oMsg.SendUsingAccount = account;
                ((Outlook._MailItem)oMsg).Send();

                //Explicitly release objects.
                oRecip = null;
                oAttach = null;
                oMsg = null;
                oApp = null;

                return true;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                //Label1.Text = ex.Message + ex.StackTrace;
                return false;
            }
        }
Пример #26
0
 public ContactHandler(Outlook.Application owner, Outlook.Folder contactFolder)
 {
     outlookApp = owner;
       folder = contactFolder;
       nonContacts = new List<object>();
       itemsToDelete = new List<string>();
       itemsToMerge = new List<string>();
       itemsUnique = new List<string>();
 }
Пример #27
0
        /// <summary>
        /// Call VBA script from an Outlook application.
        /// </summary>
        /// <param name="processName">Name of the process being executed</param>
        /// <param name="officeAppName">One of the office app names</param>
        /// <param name="filePath">File path with the VBA script to be executed</param>
        /// <param name="macroName">VBA script name with module/procedure name</param>
        /// <param name="showAlerts">Boolean status to show alerts on open application</param>
        /// <param name="visibleApp">Boolean status to show open application</param>
        /// <param name="saveFile">Boolean status to save or not the file</param>
        /// <param name="stw">Stream writer object to output message to stream buffer</param>
        /// <returns>Returned string from VBA Main Function</returns>
        private static string _RunVBAonOutlook(string processName, string officeAppName, string filePath, string macroName, bool showAlerts = false, bool visibleApp = false, bool saveFile = false, StreamWriter stw = null)
        {
            Outlook.Application _otApp = new Outlook.Application();

            if (_otApp == null)
            {
                throw new ApplicationException("Outlook could not be started. Check if Office Outlook is properly installed in your machine/server. If the error persists, contact XPress robot developers and show a printscreen of this log.");
            }
            else
            {
                string message = DateTime.Now + " [INFO] " + officeAppName + " opened successfully!";
                if (stw != null)
                {
                    stw.WriteLine(message + "\n\r");
                }
                Console.WriteLine(message);

                message = DateTime.Now + " [INFO] " + processName + " is running at " + officeAppName + "...";
                if (stw != null)
                {
                    stw.WriteLine(message + "\n\r");
                }
                Console.WriteLine(message);

                Outlook.MailItem _otSI;
                // Start outlook and mailItem
                if (filePath != null)
                {
                    _otSI = _otApp.Session.OpenSharedItem(filePath) as Outlook.MailItem;
                }
                else
                {
                    _otSI = _otApp.CreateItem(Outlook.OlItemType.olMailItem) as Outlook.MailItem;
                }

                if (visibleApp)
                {
                    _otSI.Display();
                }

                string _result = null;
                // Run the macros by supplying the necessary arguments
                // @Read: https://stackoverflow.com/questions/50878070/execute-vba-outlook-macro-from-powershell-or-c-sharp-console-app
                try
                {
                    // TODO: Test this workaround to run macros on outlook
                    Outlook.Explorer  _otExp = _otApp.ActiveExplorer();
                    CommandBar        _otCb  = _otExp.CommandBars.Add(macroName + "Proxy", Temporary: true);
                    CommandBarControl _otBtn = _otCb.Controls.Add(MsoControlType.msoControlButton, 1);
                    _otBtn.OnAction = macroName;
                    _otBtn.Execute();
                    _otCb.Delete();
                    ObjectService.ReleaseObject(_otCb);
                    ObjectService.ReleaseObject(_otExp);
                    _result = " [INFO] " + officeAppName + " script executed. Check manually if it was executed successfully.";
                }
                catch (Exception)
                {
                    _result = "ERROR | Something wrong in the " + officeAppName + " script happened. Contact XPress robot developers and show a printscreen of this log.";
                }


                if (filePath != null)
                {
                    // Clean-up: Close the mail item
                    if (!saveFile)
                    {
                        _otSI.Close(Outlook.OlInspectorClose.olDiscard);
                    }
                    else
                    {
                        _otSI.Close(Outlook.OlInspectorClose.olSave);
                    }
                    ObjectService.ReleaseObject(_otSI);
                }

                // Clean-up: Close the excel application
                _otApp.Quit();
                ObjectService.ReleaseObject(_otApp);

                return(_result);
            }
        }
Пример #28
0
        void get_Selected_mail_items()
        {
            Microsoft.Office.Interop.Outlook.Application myOlApp = new Microsoft.Office.Interop.Outlook.Application();
            Microsoft.Office.Interop.Outlook.Explorer    objView = myOlApp.ActiveExplorer();
            int k = 1;
            int i = 1;

            foreach (Microsoft.Office.Interop.Outlook.MailItem olMail in objView.Selection)
            {
                try { i += 1; } finally { }
            }

            UboundSelectedMailItems    = i - 1;
            Selected_mail_items        = ResizeArray(ref Selected_mail_items, 0, i - 2, 18, 0);
            Selected_mail_items[0, 0]  = "To";
            Selected_mail_items[0, 1]  = "CC";
            Selected_mail_items[0, 2]  = "Reply_Recipient_Names";
            Selected_mail_items[0, 3]  = "Sender_Email_Address";
            Selected_mail_items[0, 4]  = "Sender_Name";
            Selected_mail_items[0, 5]  = "Sent_On_Behalf_Of_Name";
            Selected_mail_items[0, 6]  = "Sender_Email_Type";
            Selected_mail_items[0, 7]  = "Sent";
            Selected_mail_items[0, 8]  = "Size";;
            Selected_mail_items[0, 9]  = "Unread";
            Selected_mail_items[0, 10] = "Creation_Time";
            Selected_mail_items[0, 11] = "Last_Modification_Time";
            Selected_mail_items[0, 12] = "Sent_On";
            Selected_mail_items[0, 13] = "Received_Time";
            Selected_mail_items[0, 14] = "Importance";
            Selected_mail_items[0, 15] = "Received_By_Name";
            Selected_mail_items[0, 16] = "Received_On_Behalf_Of_Name";
            Selected_mail_items[0, 17] = "Subject";
            Selected_mail_items[0, 18] = "Body";
            k = 1;

            foreach (Microsoft.Office.Interop.Outlook.MailItem olMail in objView.Selection)
            {
                try
                {
                    if (olMail.To == null)
                    {
                        Selected_mail_items[k, 0] = "";
                    }
                    else
                    {
                        Selected_mail_items[k, 0] = olMail.To.ToString();
                    }
                    if (olMail.CC == null)
                    {
                        Selected_mail_items[k, 1] = "";
                    }
                    else
                    {
                        Selected_mail_items[k, 1] = olMail.CC.ToString();
                    }
                    if (olMail.ReplyRecipientNames == null)
                    {
                        Selected_mail_items[k, 2] = "";
                    }
                    else
                    {
                        Selected_mail_items[k, 2] = olMail.ReplyRecipientNames.ToString();
                    }
                    if (olMail.SenderEmailAddress == null)
                    {
                        Selected_mail_items[k, 3] = "";
                    }
                    else
                    {
                        Selected_mail_items[k, 3] = olMail.SenderEmailAddress.ToString();
                    }
                    if (olMail.SenderName == null)
                    {
                        Selected_mail_items[k, 4] = "";
                    }
                    else
                    {
                        Selected_mail_items[k, 4] = olMail.SenderName.ToString();
                    }
                    if (olMail.SentOnBehalfOfName == null)
                    {
                        Selected_mail_items[k, 5] = "";
                    }
                    else
                    {
                        Selected_mail_items[k, 5] = olMail.SentOnBehalfOfName.ToString();
                    }
                    if (olMail.SenderEmailType == null)
                    {
                        Selected_mail_items[k, 6] = "";
                    }
                    else
                    {
                        Selected_mail_items[k, 6] = olMail.SenderEmailType.ToString();
                    }
                    if (olMail.Sent == null)
                    {
                        Selected_mail_items[k, 7] = "";
                    }
                    else
                    {
                        Selected_mail_items[k, 7] = olMail.Sent.ToString();
                    }
                    if (olMail.Size == null)
                    {
                        Selected_mail_items[k, 8] = "";
                    }
                    else
                    {
                        Selected_mail_items[k, 8] = olMail.Size.ToString();
                    }
                    if (olMail.UnRead == null)
                    {
                        Selected_mail_items[k, 9] = "";
                    }
                    else
                    {
                        Selected_mail_items[k, 9] = olMail.UnRead.ToString();
                    }
                    if (olMail.CreationTime == null)
                    {
                        Selected_mail_items[k, 10] = "";
                    }
                    else
                    {
                        Selected_mail_items[k, 10] = olMail.CreationTime.ToString();
                    }
                    if (olMail.LastModificationTime == null)
                    {
                        Selected_mail_items[k, 11] = "";
                    }
                    else
                    {
                        Selected_mail_items[k, 11] = olMail.LastModificationTime.ToString();
                    }
                    if (olMail.SentOn == null)
                    {
                        Selected_mail_items[k, 12] = "";
                    }
                    else
                    {
                        Selected_mail_items[k, 12] = olMail.SentOn.ToString("yyddmm-hhmmss");
                    }
                    if (olMail.ReceivedTime == null)
                    {
                        Selected_mail_items[k, 13] = "";
                    }
                    else
                    {
                        Selected_mail_items[k, 13] = olMail.ReceivedTime.ToString("yyddmm-hhmmss");
                    }
                    if (olMail.Importance == null)
                    {
                        Selected_mail_items[k, 14] = "";
                    }
                    else
                    {
                        Selected_mail_items[k, 14] = olMail.Importance.ToString();
                    }
                    if (olMail.ReceivedByName == null)
                    {
                        Selected_mail_items[k, 15] = "";
                    }
                    else
                    {
                        Selected_mail_items[k, 15] = olMail.ReceivedByName.ToString();
                    }
                    if (olMail.ReceivedOnBehalfOfName == null)
                    {
                        Selected_mail_items[k, 16] = "";
                    }
                    else
                    {
                        Selected_mail_items[k, 16] = olMail.ReceivedOnBehalfOfName.ToString();
                    }
                    if (olMail.Subject == null)
                    {
                        Selected_mail_items[k, 17] = "";
                    }
                    else
                    {
                        Selected_mail_items[k, 17] = olMail.Subject.ToString();
                    }
                    if (olMail.Body == null)
                    {
                        Selected_mail_items[k, 18] = "";
                    }
                    else
                    {
                        Selected_mail_items[k, 18] = olMail.Body.ToString();
                    }

                    k += 1;
                }
                finally { }
            }
        }
Пример #29
0
        public override void SendMessage()
        {
            try
            {
                oApp = (Outlook.Application)Marshal.GetActiveObject("Outlook.Application");
               // eMail = (Outlook.MailItem)this.oApp.CreateItem(Microsoft.Office.Interop.Outlook.OlItemType.olMailItem);
                Outlook.MailItem mail = oApp.CreateItem(Outlook.OlItemType.olMailItem) as Outlook.MailItem;
                try
                {
                    mail.Subject = this.Subject;

                    //mail.Body = this.MessageBody;
                    // Add recipient using display name, alias, or smtp address
                    AddRecipients(mail);
                    //Add All Attachments to the Message
                    foreach (IAttachment attachment in this.Attachments)
                    {
                        Outlook.Attachment oAttach =
                        mail.Attachments.Add(attachment.AttachemntPath, Outlook.OlAttachmentType.olByValue, Type.Missing, Type.Missing);
                        oAttach = null;
                    }
                    //If There Are Recipient to send the message to then send the message.
                    if (mail.Recipients.Count > 0)
                    {
                        Outlook.Inspector myInspector = mail.GetInspector;
                        String text;
                        text = this.MessageBody + mail.HTMLBody;
                        mail.HTMLBody = text;

                        if (this.MessagePriority == enumMessagePriority.Low)
                        {
                            mail.Importance = Microsoft.Office.Interop.Outlook.OlImportance.olImportanceLow;
                        }
                        if (this.MessagePriority == enumMessagePriority.Medium)
                        {
                            mail.Importance = Microsoft.Office.Interop.Outlook.OlImportance.olImportanceNormal;
                        }
                        if (this.MessagePriority == enumMessagePriority.High)
                        {
                            mail.Importance = Microsoft.Office.Interop.Outlook.OlImportance.olImportanceHigh;
                        }

                        mail.Save();
                        mail.Send();
                    }
                }
                catch (Exception ex)
                {
                    DialogResult Rtn = System.Windows.Forms.MessageBox.Show("Error Send email Via Oultook Open Outlook First and try again - Error : " + ex.Message, "Outlook Error", MessageBoxButtons.RetryCancel, MessageBoxIcon.Warning);
                    if (Rtn == DialogResult.Retry)
                    {
                        this.SendMessage();
                    }
                }
                finally
                {
                    //Explicitly release objects.
                    mail = null;
                }
            }
            catch
            {
                // System.Diagnostics.Process.Start("OUTLOOK.EXE");
                //oApp = (Outlook.Application)Marshal.GetActiveObject("Outlook.Application");
                // open your new instance
            }


        }
        public static new int Convert(String inputFile, String outputFile, Hashtable options)
        {
            Boolean running = (Boolean)options["noquit"];

            Microsoft.Office.Interop.Outlook.Application app = null;
            String tmpDocFile = null;

            try
            {
                try
                {
                    app = (Microsoft.Office.Interop.Outlook.Application)Marshal.GetActiveObject("Outlook.Application");
                }
                catch (System.Exception)
                {
                    app     = new Microsoft.Office.Interop.Outlook.Application();
                    running = false;
                }
                var      session = app.Session;
                FileInfo fi      = new FileInfo(inputFile);
                // Create a temporary doc file from the message
                tmpDocFile = System.IO.Path.GetTempPath() + Guid.NewGuid().ToString() + ".doc";
                switch (fi.Extension)
                {
                case ".msg":
                    var message = (MailItem)session.OpenSharedItem(inputFile);
                    if (message == null)
                    {
                        return((int)ExitCode.FileOpenFailure);
                    }
                    message.SaveAs(tmpDocFile, Microsoft.Office.Interop.Outlook.OlSaveAsType.olDoc);
                    Converter.ReleaseCOMObject(message);
                    Converter.ReleaseCOMObject(session);
                    break;

                case ".vcf":
                    var contact = (ContactItem)session.OpenSharedItem(inputFile);
                    if (contact == null)
                    {
                        return((int)ExitCode.FileOpenFailure);
                    }
                    contact.SaveAs(tmpDocFile, Microsoft.Office.Interop.Outlook.OlSaveAsType.olDoc);
                    Converter.ReleaseCOMObject(contact);
                    Converter.ReleaseCOMObject(session);
                    break;

                case ".ics":
                    var    item     = session.OpenSharedItem(inputFile);
                    string itemType = (string)(string)item.GetType().InvokeMember("MessageClass", System.Reflection.BindingFlags.GetProperty, null, item, null);
                    switch (itemType)
                    {
                    case "IPM.Appointment":
                        var appointment = (AppointmentItem)item;
                        if (appointment != null)
                        {
                            appointment.SaveAs(tmpDocFile, Microsoft.Office.Interop.Outlook.OlSaveAsType.olDoc);
                        }
                        break;

                    default:
                        Console.WriteLine("Unable to convert ICS type " + itemType);
                        break;
                    }
                    Converter.ReleaseCOMObject(item);
                    Converter.ReleaseCOMObject(session);
                    break;
                }

                if (!File.Exists(tmpDocFile))
                {
                    return((int)ExitCode.UnknownError);
                }
                // Convert the doc file to a PDF
                return(WordConverter.Convert(tmpDocFile, outputFile, options));
            }
            catch (System.Exception e)
            {
                Console.WriteLine(e.Message);
                return((int)ExitCode.UnknownError);
            }
            finally
            {
                if (tmpDocFile != null && File.Exists(tmpDocFile))
                {
                    System.IO.File.Delete(tmpDocFile);
                }
                // If we were not already running, quit and release the outlook object
                if (app != null && !running)
                {
                    ((Microsoft.Office.Interop.Outlook._Application)app).Quit();
                }
                Converter.ReleaseCOMObject(app);
            }
        }
Пример #31
0
        public void Initialize()
        {
            this.GetTestCatgoryInformation();
            EndStartedOutLook();
            Thread.Sleep(10000);
            MessageParser.ClearSessions();
            string outLookPath = ConfigurationManager.AppSettings["OutLookPath"].ToString();

            waittimeWindow = int.Parse(ConfigurationManager.AppSettings["WaitTimeWindow"].ToString());
            waittimeItem   = int.Parse(ConfigurationManager.AppSettings["WaitTimeItem"].ToString());
            Process p = Process.Start(outLookPath);

            AutomationElement outlookWindow = null;
            var    desktop           = AutomationElement.RootElement;
            string userName          = ConfigurationManager.AppSettings["Office365Account"].ToString();
            var    condition_Outlook = new PropertyCondition(AutomationElement.NameProperty, "Inbox - " + userName + " - Outlook");

            int count = 0;

            while (outlookWindow == null)
            {
                outlookWindow = desktop.FindFirst(TreeScope.Children, condition_Outlook);
                Thread.Sleep(waittimeItem / 10);
                count += waittimeItem / 10;
                if (count >= waittimeWindow)
                {
                    break;
                }
            }

            Process[] pp = Process.GetProcesses();
            if (pp.Count() > 0)
            {
                foreach (Process pp1 in pp)
                {
                    if (pp1.ProcessName != "OUTLOOK" && pp1.ProcessName != "explorer" && pp1.MainWindowHandle != IntPtr.Zero)
                    {
                        AutomationElement element = AutomationElement.FromHandle(pp1.MainWindowHandle);
                        if (element != null)
                        {
                            try
                            {
                                element.SetFocus();
                            }
                            catch
                            {
                                continue;
                            }
                        }

                        break;
                    }
                }
            }

            Thread.Sleep(waittimeItem);
            try
            {
                outlookApp = Marshal.GetActiveObject("Outlook.Application") as Outlook.Application;
            }
            catch
            {
                throw new Exception("Get active outlook application failed, please check if outlook is running");
            }

            inboxFolders        = outlookApp.Session.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox);
            sentMailFolder      = outlookApp.Session.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderSentMail);
            deletedItemsFolders = outlookApp.Session.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderDeletedItems);
            draftsFolders       = outlookApp.Session.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderDrafts);
        }
Пример #32
0
        private static void Main()
        {
            Logger.Debug("Checking to see if there is an instance running.");
            if (IsAlreadyRunning())
            {
                // let the user know the program is already running.
                Logger.Warn("Instance is already running, exiting.");
                MessageBox.Show(Resources.ProgramIsAlreadyRunning, Resources.ProgramIsAlreadyRunningCaption,
                                MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
            }
            else
            {
                if (!IsOutlook2003OrHigherInstalled())
                {
                    Logger.Debug("Outlook is not available or installed.");
                    MessageBox.Show(
                        Resources.Office2000Requirement + Environment.NewLine +
                        Resources.InstallOutlookMsg, Resources.MissingRequirementsCapation, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                try
                {
                    OutlookApp       = new Application();
                    OutlookNameSpace = OutlookApp.GetNamespace("MAPI");

                    // Before we do anything else, wait for the RPC server to be available, as the program will crash if it's not.
                    // This is especially likely when OotD is set to start with windows.
                    if (!IsRPCServerAvailable(OutlookNameSpace))
                    {
                        return;
                    }

                    OutlookFolder = OutlookNameSpace.GetDefaultFolder(OlDefaultFolders.olFolderCalendar);

                    // WORKAROUND: Beginning with Outlook 2007 SP2, Microsoft decided to kill all outlook instances
                    // when opening and closing an item from the view control, even though the view control was still running.
                    // The only way I've found to work around it and keep the view control from crashing after opening an item,
                    // is to get this global instance of the active explorer and keep it going until the user closes the app.
                    OutlookExplorer = OutlookFolder.GetExplorer();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(Resources.ErrorInitializingApp + ' ' + ex, Resources.ErrorCaption, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                System.Windows.Forms.Application.EnableVisualStyles();

                Logger.Info("Starting the instance manager and loading instances.");
                var instanceManager = new InstanceManager();

                try
                {
                    instanceManager.LoadInstances();
                }
                catch (Exception ex)
                {
                    Logger.Error(ex, "Could not load instances");
                    return;
                }

                System.Windows.Forms.Application.Run(instanceManager);
            }
        }
Пример #33
0
        public List <AdxCalendarItem> GetAllCalendarItems()
        {
            Outlook.Application    OutlookApp = new Outlook.Application();
            List <AdxCalendarItem> result     = new List <AdxCalendarItem>();

            Outlook._NameSpace session = OutlookApp.Session;
            if (session != null)
            {
                try
                {
                    object stores = session.GetType().InvokeMember("Stores", BindingFlags.GetProperty, null, session, null);
                    if (stores != null)
                    {
                        try
                        {
                            int count = (int)stores.GetType().InvokeMember("Count", BindingFlags.GetProperty, null, stores, null);
                            for (int i = 1; i <= count; i++)
                            {
                                object store = stores.GetType().InvokeMember("Item", BindingFlags.GetProperty, null, stores, new object[] { i });
                                if (store != null)
                                {
                                    try
                                    {
                                        Outlook.MAPIFolder calendar = null;
                                        try
                                        {
                                            calendar = (Outlook.MAPIFolder)store.GetType().InvokeMember("GetDefaultFolder", BindingFlags.GetProperty, null, store, new object[] { Outlook.OlDefaultFolders.olFolderCalendar });
                                        }
                                        catch
                                        {
                                            continue;
                                        }
                                        if (calendar != null)
                                        {
                                            try
                                            {
                                                Outlook.Folders folders = calendar.Folders;
                                                try
                                                {
                                                    Outlook.MAPIFolder subfolder = null;
                                                    for (int j = 1; j < folders.Count + 1; j++)
                                                    {
                                                        subfolder = folders[j];
                                                        try
                                                        {
                                                            // add subfolder items
                                                            result.AddRange(GetAppointmentItems(subfolder));
                                                        }
                                                        finally
                                                        { if (subfolder != null)
                                                          {
                                                              Marshal.ReleaseComObject(subfolder);
                                                          }
                                                        }
                                                    }
                                                }
                                                finally
                                                { if (folders != null)
                                                  {
                                                      Marshal.ReleaseComObject(folders);
                                                  }
                                                }
                                                // add root items
                                                result.AddRange(GetAppointmentItems(calendar));
                                            }
                                            finally { Marshal.ReleaseComObject(calendar); }
                                        }
                                    }
                                    finally { Marshal.ReleaseComObject(store); }
                                }
                            }
                        }
                        finally { Marshal.ReleaseComObject(stores); }
                    }
                }
                finally { Marshal.ReleaseComObject(session); }
            }
            return(result);
        }
Пример #34
0
        private void btnSendProposal_Click(object sender, EventArgs e)
        {
            string rwP = string.Empty;

            if (MessageBox.Show("Draft Email Proposal?", "", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                if (dgvProposal.Rows.Count > 0)
                {
                    try
                    {
                        for (int i = 0; i <= dgvProposal.Rows.Count - 1; i++)
                        {
                            DBMethods.InsertPurchaseProposal(_prID, dgvProposal.Rows[i].Cells[2].Value.ToString(), dgvProposal.Rows[i].Cells[3].Value.ToString(),
                                                             dgvProposal.Rows[i].Cells[4].Value.ToString(), dgvProposal.Rows[i].Cells[5].Value.ToString(),
                                                             dgvProposal.Rows[i].Cells[1].Value.ToString());

                            rwP += "<tr>" +
                                   "<td style='border: 1px solid black; border-collapse: collapse'>" + dgvProposal.Rows[i].Cells[1].Value.ToString() + "</td>" +
                                   "<td style='border: 1px solid black; border-collapse: collapse'>" + dgvProposal.Rows[i].Cells[2].Value.ToString() + "</td>" +
                                   "<td style='border: 1px solid black; border-collapse: collapse'>" + dgvProposal.Rows[i].Cells[3].Value.ToString() + "</td>" +
                                   "<td style='border: 1px solid black; border-collapse: collapse; text-align: center'>" + dgvProposal.Rows[i].Cells[4].Value.ToString() + "</td>" +
                                   "<td style='border: 1px solid black; border-collapse: collapse; text-align: center'>" + string.Format("{0:#,#}", Convert.ToDecimal(dgvProposal.Rows[i].Cells[5].Value)) + "</td>" +
                                   "</tr>";
                        }

                        Email.Application Outlook;
                        Email.MailItem    Mail;

                        Outlook = new Email.Application();
                        Mail    = Outlook.CreateItem(Microsoft.Office.Interop.Outlook.OlItemType.olMailItem);

                        Mail.To = rEmail;
                        Mail.CC = "*****@*****.**";
                        //[email protected]

                        Mail.Subject = "Purchase Request ( " + cmbPRFNum.Text + " ) For ( Name : " + rName + " )";

                        Mail.HTMLBody = "Hi " + rName + ",<br><br>" +
                                        "Please see below details for my proposal for your request. Thank you! <br><br>" +
                                        "<i>*******(This is auto email from procurement system)</i><br><br>" +
                                        "<table style = 'width: 100%'>" +
                                        "<tr>" +
                                        "<th style='border: 1px solid black; border-collapse: collapse; background: rgb(24, 30, 54); font-color: white'>Request Item</th>" +
                                        "<th style='border: 1px solid black; border-collapse: collapse; background: rgb(24, 30, 54); font-color: white'>Vendor Name</th>" +
                                        "<th style='border: 1px solid black; border-collapse: collapse; background: rgb(24, 30, 54); font-color: white'>Item</th>" +
                                        "<th style='border: 1px solid black; border-collapse: collapse; background: rgb(24, 30, 54); font-color: white'>Quantity</th>" +
                                        "<th style='border: 1px solid black; border-collapse: collapse; background: rgb(24, 30, 54); font-color: white'>Cost</th>" +
                                        "</tr>" +
                                        rwP +
                                        "</table>";
                        Mail.Display();

                        MessageBox.Show("Draft Email Proposal Success", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        ClearxxProp();
                    }
                    catch (Exception ex)
                    {
                        throw new Exception("Error in Draft Proposal" + Environment.NewLine + ex.Message.ToString(), ex);
                    }
                }
                else
                {
                    MessageBox.Show("Please add proposal list on the table", "", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
        }
        public void removeAttachments_Click(Office.IRibbonControl control)
        {
            int itemCountTotal   = 0;
            int itemCountRemoved = 0;
            int min = 0;

            Outlook.Application application = new Outlook.Application();
            Outlook.Explorer    explorer    = application.ActiveExplorer();
            Outlook.Selection   selected    = explorer.Selection;
            DialogResult        dr_Delete   = MessageBox.Show("Are you sure you want to delete all attachments from the selected items?", "Warning", MessageBoxButtons.YesNo);

            if (dr_Delete == DialogResult.Yes)
            {
                foreach (Object obj in selected)
                {
                    string msg = null;
                    itemCountTotal++;
                    if (obj is Outlook.MailItem)
                    {
                        min = 0;
                        Outlook.MailItem    mailItem    = (Outlook.MailItem)obj;
                        Outlook.Attachments attachments = mailItem.Attachments;
                        // Iterate through attachments of this email
                        if (attachments != null && attachments.Count > 0)
                        {
                            int attachmentCount = attachments.Count;
                            int position        = 1;
                            for (int i = 1; i <= attachmentCount; i++)
                            {
                                Outlook.Attachment attachment = attachments[position];
                                var    flags    = attachment.PropertyAccessor.GetProperty("http://schemas.microsoft.com/mapi/proptag/0x37140003");
                                String fileName = attachments[position].DisplayName;
                                // To ignore embedded attachments
                                if (flags != 4)
                                {
                                    // To ignore embedded attachments in RTF mail with type 6
                                    if ((int)attachment.Type != 6)
                                    {
                                        // Delete attachment and append a message to the body.
                                        attachments[position].Delete();
                                        min  = 1;
                                        msg += fileName + ", ";
                                    }
                                }
                                else
                                {
                                    position++;
                                    flags = attachment.PropertyAccessor.GetProperty("http://schemas.microsoft.com/mapi/proptag/0x37140003");
                                }
                            }
                            if (min == 1)
                            {
                                itemCountRemoved++;
                            }
                        }
                        if (itemCountRemoved >= 1)
                        {
                            msg = msg.Remove(msg.Length - 2);
                            mailItem.HTMLBody = "<p>ATTACHMENTS REMOVED: [" + msg + "]</p>" + mailItem.HTMLBody;
                            mailItem.Save();
                        }
                    }
                }
                if (itemCountRemoved == 0)
                {
                    MessageBox.Show("There are no attachments to remove.");
                }
                else
                {
                    MessageBox.Show("Removed attachments from " + itemCountRemoved + " out of " + itemCountTotal + " emails.");
                }
            }
            else if (dr_Delete == DialogResult.No)
            {
            }
        }
Пример #36
0
        public void UI_sendMailToAdmin_AfterApproved(string SRID)
        {
            string   Name        = string.Empty;
            string   subject     = string.Empty;
            DateTime?createdOn   = null;
            string   adminMailId = string.Empty;
            int?     Role_ID     = null;
            int?     Delegate_ID = null;
            int?     MetaActive  = null;

            try
            {
                foreach (var items in UI_userSRDetailsForMail(SRID))
                {
                    Name      = items.Name;
                    SRID      = items.SRID;
                    subject   = items.SRDescription;
                    createdOn = items.CreatedTimeStamp;
                }

                foreach (var items in adminList())
                {
                    adminMailId = items.AdminEmailID;
                    Role_ID     = items.Role_ID;
                    Delegate_ID = items.Delegate_ID;
                    MetaActive  = items.MetaActive;
                    break;
                }

                // Create the Outlook application.
                Outlook.Application oApp = new Outlook.Application();

                // Create a new mail item.
                Outlook.MailItem oMsg = (Outlook.MailItem)oApp.CreateItem(Outlook.OlItemType.olMailItem);

                // Set the subject.
                oMsg.Subject = "Take Action for " + SRID;

                // send mail to
                oMsg.To = adminMailId;


                // Set HTMLBody.
                String sHtml = "A New Ticket has been Submitted for below SR <br>" +
                               "SR Number : " + SRID + "<br>" +
                               "Created By : " + Name + "<br>" +
                               "SR Description : " + subject + "<br>" +
                               "SR Created Date : " + createdOn + "<br>" + "<br>" +
                               "Please take action against " + SRID + " which is assigned to you";

                oMsg.HTMLBody = sHtml;

                oMsg.Send();

                oMsg = null;

                oApp = null;
            }
            catch (Exception e)
            {
                Log.CreateLog(e);
            }
        }
Пример #37
0
        public void sendMailToApprover2(int srid, string guid)
        {
            int      SRID             = srid;
            string   Name             = string.Empty;
            string   srDescription    = string.Empty;
            string   ApproverEmailID  = string.Empty;
            DateTime?CreatedTimeStamp = null;
            int?     Role_ID          = null;
            int?     Delegate_ID      = null;
            int?     MetaActive       = null;

            try
            {
                foreach (var item in userSRDetailsForMail(srid))
                {
                    srDescription    = item.SRDescription;
                    CreatedTimeStamp = item.CreatedTimeStamp;
                    Name             = item.Name;
                }

                foreach (var items in approverList())
                {
                    ApproverEmailID = items.ApproverEmailID;
                    Role_ID         = items.Role_ID;
                    Delegate_ID     = items.Delegate_ID;
                    MetaActive      = items.MetaActive;
                }

                Outlook.Application oApp = new Outlook.Application();

                Outlook.MailItem oMsg = (Outlook.MailItem)oApp.CreateItem(Outlook.OlItemType.olMailItem);

                oMsg.Subject = "New Service Ticket ID SR000000" + SRID + "  has been submitted";

                oMsg.To = ApproverEmailID;

                string ApproveLink = "http://localhost:56438/api/Mail/MailResponse?Action=Approved&guid=" + guid;
                string rejectlink  = "http://localhost:56438/api/Mail/MailResponse?Action=Rejected&guid=" + guid;

                // Set HTMLBody.
                String sHtml = "Approver 1 couldn't take action for below SR <br>" +
                               "SR Number SR000000" + SRID + "<br>" +
                               "Created By : " + Name + "<br>" +
                               "SR Description : " + srDescription + "<br>" +
                               "Submitted On : " + DateTime.Now + "<br><br>" +

                               "Please take action against below SR000000" + SRID +
                               "<br><a href=" + ApproveLink + ">" + " Approve</a> " +
                               " or <a href=" + rejectlink + "> Reject </a></br>";

                oMsg.HTMLBody = sHtml;

                oMsg.Send();

                oMsg = null;

                oApp = null;
            }
            catch (Exception e)
            {
                Log.CreateLog(e);
            }
        }
Пример #38
0
        private void btnSend_Click(object sender, EventArgs e)
        {
            string rwD = string.Empty;

            if (MessageBox.Show("Send Request Now?", "", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                if (dgvRequest.Rows.Count > 0)
                {
                    try
                    {
                        //---------for auto pick req number
                        _poReq    = DBMethods.RequestNumber(DateTime.Now.ToString("MM")).ToString();
                        _poReqRef = _poReq;
                        //--------insert pr number continous
                        int pId = DBMethods.InsertPRNumber(_poReqRef, DateTime.Now.ToString("MM/dd/yyyy"), 0);

                        switch (_poReq.Length)
                        {
                        case 1:
                            _poReq = "PRF#00" + _poReq + "-" + DateTime.Now.ToString("MM") + "-" + DateTime.Now.ToString("yy");
                            break;

                        case 2:
                            _poReq = "PRF#0" + _poReq + "-" + DateTime.Now.ToString("MM") + "-" + DateTime.Now.ToString("yy");
                            break;

                        case 3:
                            _poReq = "PRF#" + _poReq + "-" + DateTime.Now.ToString("MM") + "-" + DateTime.Now.ToString("yy");
                            break;

                        default:
                            break;
                        }

                        for (int rr = 0; rr <= dgvRequest.Rows.Count - 1; rr++)
                        {
                            DBMethods.InsertPurchaseRequest(txtName.Text, txtDepartment.Text, txtEmail.Text, txtTicketNum.Text,
                                                            cmbPriority.Text, chkPurchase.Checked == true ? "Purchase" : "Service", rbYes.Checked == true ? "1" : "0", txtAccount.Text,
                                                            dgvRequest.Rows[rr].Cells[1].Value.ToString(), dgvRequest.Rows[rr].Cells[2].Value.ToString(),
                                                            dgvRequest.Rows[rr].Cells[3].Value.ToString(), DateTime.Now.ToString("MM/dd/yyyy"), _poReq, pId);

                            rwD += "<tr>" +
                                   "<td style='border: 1px solid black; border-collapse: collapse; text-align: center'>" + dgvRequest.Rows[rr].Cells[1].Value.ToString() + "</td>" +
                                   "<td style='border: 1px solid black; border-collapse: collapse; text-align: center'>" + dgvRequest.Rows[rr].Cells[2].Value.ToString() + "</td>" +
                                   "<td style='border: 1px solid black; border-collapse: collapse'>" + dgvRequest.Rows[rr].Cells[3].Value.ToString() + "</td>" +
                                   "</tr>";
                        }

                        Email.Application Outlook;
                        Email.MailItem    Mail;

                        Outlook = new Email.Application();
                        Mail    = Outlook.CreateItem(Microsoft.Office.Interop.Outlook.OlItemType.olMailItem);

                        //[email protected]
                        Mail.To = "*****@*****.**";
                        Mail.CC = txtEmail.Text;
                        //Mail.BCC = emailBCC;

                        Mail.Subject = "Purchase Request ( " + _poReq + " )";

                        Mail.HTMLBody = "Hi,<br><br>" +
                                        "Please see below details for my request. Thank you! <br><br>" +
                                        "<i>*******(This is auto email from procurement system application)</i><br><br>" +
                                        "<b>Name :</b>" + " " + " " + " " + "" + txtName.Text + "" + "<br>" +
                                        "<b>Department :</b>" + " " + " " + " " + "" + txtDepartment.Text + "" + "<br>" +
                                        "<b>Account :</b>" + " " + " " + " " + "" + txtAccount.Text + "" + "<br>" +
                                        "<b>Priority :</b>" + " " + " " + " " + "" + cmbPriority.Text + "" + "" + "<br><br>" +
                                        "<table style = 'width: 100%'>" +
                                        "<tr>" +
                                        "<th style='border: 1px solid black; border-collapse: collapse; background: rgb(24, 30, 54); font-color: white'>Item #</th>" +
                                        "<th style='border: 1px solid black; border-collapse: collapse; background: rgb(24, 30, 54); font-color: white'>Quantity</th>" +
                                        "<th style='border: 1px solid black; border-collapse: collapse; background: rgb(24, 30, 54); font-color: white'>Description</th>" +
                                        "</tr>" +
                                        rwD +
                                        "</table>";
                        Mail.Display();
                        //Mail.Send();

                        MessageBox.Show("Send Request Success?", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        Clearxx();
                    }
                    catch (Exception ex)
                    {
                        throw new Exception("Error in sending request" + Environment.NewLine + ex.Message.ToString(), ex);
                    }
                }
            }
        }
Пример #39
0
        public static String SendFullDayAppointment(String fromAddress, String startDate, List <String> requiredAttendies, List <String> optionalAttendies, String subj, String body, List <String> attachments, String attachLocation)
        {
            Outlook.Application     application  = new Outlook.Application();
            Outlook.AppointmentItem oAppointment = (Outlook.AppointmentItem)application.CreateItem(Outlook.OlItemType.olAppointmentItem);

            oAppointment.Subject  = subj;
            oAppointment.Body     = body;
            oAppointment.Location = "Appointment location";

            // Set the start date
            oAppointment.Start = Convert.ToDateTime(startDate);

            oAppointment.AllDayEvent = true;

            // Set the reminder 15 minutes before start
            oAppointment.ReminderSet = true;
            oAppointment.ReminderMinutesBeforeStart = 15;

            //Setting the importance:
            //use OlImportance enum to set the importance to low, medium or high

            oAppointment.Importance = Outlook.OlImportance.olImportanceHigh;

            /* OlBusyStatus is enum with following values:
             * olBusy
             * olFree
             * olOutOfOffice
             * olTentative
             */
            oAppointment.BusyStatus    = Outlook.OlBusyStatus.olBusy;
            oAppointment.MeetingStatus = Outlook.OlMeetingStatus.olMeeting;

            if (requiredAttendies != null)
            {
                foreach (String toAddress in requiredAttendies)
                {
                    Outlook.Recipient recipient = oAppointment.Recipients.Add(toAddress);
                    recipient.Type = (int)Outlook.OlMeetingRecipientType.olRequired;
                }
            }

            if (optionalAttendies != null)
            {
                foreach (String optAddress in optionalAttendies)
                {
                    Outlook.Recipient optRecipient = oAppointment.Recipients.Add(optAddress);
                    optRecipient.Type = (int)Outlook.OlMeetingRecipientType.olOptional;
                }
            }

            //Outlook.Recipient organizer = oAppointment.Recipients.Add(fromAddress);
            //organizer.Type = (int)Outlook.OlMeetingRecipientType.olOrganizer;

            oAppointment.Recipients.ResolveAll();
            //String iCalUid = oAppointment.GlobalAppointmentID;

            if (!attachments.Count.Equals(0))
            {
                foreach (String attachName in attachments)
                {
                    String sSource      = attachLocation;
                    String sDisplayName = attachName;

                    int iPosition   = (int)oAppointment.Body.Length + 1;
                    int iAttachType = (int)Outlook.OlAttachmentType.olByValue;

                    oAppointment.Attachments.Add(sSource, iAttachType, iPosition, sDisplayName);
                }
            }

            // Save the appointment
            oAppointment.SaveAs(@"D:\Temp\Test.ics", Outlook.OlSaveAsType.olICal);

            //Outlook.Account acc = OutlookManage.GetAccount(application, fromAddress);
            //oAppointment.SendUsingAccount = acc;

            ((Outlook._AppointmentItem)oAppointment).Send();

            String guid = oAppointment.GlobalAppointmentID;

            Console.WriteLine("guid: " + guid);

            ((Outlook._AppointmentItem)oAppointment).Close(Outlook.OlInspectorClose.olSave);

            //Outlook.MailItem mailItem = oAppointment.ForwardAsVcal();
            //     mailItem.SendUsingAccount = GetAccountForEmailAddress(application, fromAddress);
            //// email address to send to
            //     mailItem.To = "*****@*****.**";
            //
            //((Outlook._MailItem)mailItem).Send();

            return(guid);
        }
Пример #40
0
        bool IRepositoryItemFactory.Send_Outlook(bool actualSend, string MailTo, string Event, string Subject, string Body, string MailCC, List <string> Attachments, List <KeyValuePair <string, string> > EmbededAttachment)
        {
            try
            {
                Outlook.Application objOutLook = null;
                if (string.IsNullOrEmpty(MailTo))
                {
                    Event = "Failed: Please provide TO email address.";
                    return(false);
                }
                if (string.IsNullOrEmpty(Subject))
                {
                    Event = "Failed: Please provide email subject.";
                    return(false);
                }
                // Check whether there is an Outlook process running.
                if (System.Diagnostics.Process.GetProcessesByName("OUTLOOK").Count() > 0)
                {
                    // If so, use the GetActiveObject method to obtain the process and cast it to an ApplicatioInstall-Package Microsoft.Office.Interop.Exceln object.

                    objOutLook = Marshal.GetActiveObject("Outlook.Application") as Outlook.Application;
                }
                else
                {
                    // If not, create a new instance of Outlook and log on to the default profile.
                    objOutLook = new Outlook.Application();
                    Outlook.NameSpace nameSpace = objOutLook.GetNamespace("MAPI");
                    nameSpace.Logon("", "", System.Reflection.Missing.Value, System.Reflection.Missing.Value);
                    nameSpace = null;
                }

                mOutlookMail = objOutLook.CreateItem(Outlook.OlItemType.olMailItem) as Outlook.MailItem;

                mOutlookMail.HTMLBody = Body;
                mOutlookMail.Subject  = Subject;

                Outlook.AddressEntry currentUser = objOutLook.Session.CurrentUser.AddressEntry;

                if (currentUser.Type == "EX")
                {
                    Outlook.ExchangeUser manager = currentUser.GetExchangeUser();

                    // Add recipient using display name, alias, or smtp address
                    string emails    = MailTo;
                    Array  arrEmails = emails.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                    foreach (string email in arrEmails)
                    {
                        mOutlookMail.Recipients.Add(email);
                    }

                    //Add CC
                    if (!String.IsNullOrEmpty(MailCC))
                    {
                        Array arrCCEmails = MailCC.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                        foreach (string MailCC1 in arrCCEmails)
                        {
                            mOutlookMail.Recipients.Add(MailCC1);
                        }
                    }

                    mOutlookMail.Recipients.ResolveAll();

                    mOutlookMail.CC = MailCC;
                    mOutlookMail.To = MailTo;

                    //Add Attachment
                    foreach (string AttachmentFileName in Attachments)
                    {
                        if (String.IsNullOrEmpty(AttachmentFileName) == false)
                        {
                            mOutlookMail.Attachments.Add(AttachmentFileName, Type.Missing, Type.Missing, Type.Missing);
                        }
                    }

                    //attachment which is embeded into the email body(images).
                    foreach (KeyValuePair <string, string> AttachmentFileName in EmbededAttachment)
                    {
                        if (String.IsNullOrEmpty(AttachmentFileName.Key) == false)
                        {
                            if (System.IO.File.Exists(AttachmentFileName.Key))
                            {
                                Outlook.Attachment attachment = mOutlookMail.Attachments.Add(AttachmentFileName.Key, Outlook.OlAttachmentType.olEmbeddeditem, null, "");
                                attachment.PropertyAccessor.SetProperty("http://schemas.microsoft.com/mapi/proptag/0x3712001E", AttachmentFileName.Value);
                            }
                        }
                    }
                    if (actualSend)
                    {
                        //Send Mail
                        mOutlookMail.Send();
                    }
                }
                return(true);
            }
            catch (Exception ex)
            {
                if (ex.Message.Contains("Mailbox Unavailabel"))
                {
                    Event = "Failed: Please provide correct sender email address";
                }
                else if (ex.StackTrace.Contains("System.Runtime.InteropServices.Marshal.GetActiveObject"))
                {
                    Event = "Please make sure ginger/outlook opened in same security context (Run as administrator or normal user)";
                }
                else if (ex.StackTrace.Contains("System.Security.Authentication.AuthenticationException") || ex.StackTrace.Contains("System.Net.Sockets.SocketException"))
                {
                    Event = "Please check SSL configuration";
                }
                else
                {
                    Event = "Failed: " + ex.Message;
                }
                return(false);
            }
        }
Пример #41
0
        private void BtnSubmit_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if ((TxtName.Text == "") || (TxtEmail.Text == ""))
                {
                    if (TxtName.Text == "")
                    {
                        MessageBox.Show("Name is requiered", "Caution", MessageBoxButton.OK);
                        TxtName.Focus();
                    }
                    else if (TxtEmail.Text == "")
                    {
                        MessageBox.Show("Email is required", "Caution", MessageBoxButton.OK);
                        TxtEmail.Focus();
                    }
                }
                else
                {
                    var email = myContext.Suppliers.Where(p => p.Email == TxtEmail.Text).FirstOrDefault();
                    //foreach (var email in myContext.Suppliers)
                    //{
                    //    if (email.Email == TxtEmail.Text)
                    //    {
                    //        validEmail = false;
                    //    }
                    //}
                    if (email == null)
                    {
                        string message = "Halo this message has been sent from wpf";
                        var    push    = new Supplier(TxtName.Text, TxtEmail.Text);
                        myContext.Suppliers.Add(push);
                        var result = myContext.SaveChanges();
                        if (result > 0)
                        {
                            MessageBox.Show(result + " row has been inserted");
                        }


                        Outlook._Application _app = new Outlook.Application();
                        Outlook.MailItem     mail = (Outlook.MailItem)_app.CreateItem(Outlook.OlItemType.olMailItem);
                        mail.Subject    = TxtName.Text;
                        mail.To         = TxtEmail.Text;
                        mail.Body       = message;
                        mail.Importance = Outlook.OlImportance.olImportanceNormal;
                        ((Outlook._MailItem)mail).Send();
                        MessageBox.Show("Your Message has been succesfully sent.", "Message", MessageBoxButton.OK);
                    }

                    else
                    {
                        MessageBox.Show("Email has been used");
                    }
                }
            }

            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Message", MessageBoxButton.OK);
            }

            DataGridSupplier.ItemsSource = myContext.Suppliers.ToList();
            TxtName.Text  = "";
            TxtEmail.Text = "";
        }
        public void saveAttachments_Click(Office.IRibbonControl control)
        {
            bool   firstPrompt      = false;
            int    itemCountTotal   = 0;
            int    itemCountSaved   = 0;
            int    validAttachments = 0;
            int    min  = 0;
            string path = null;

            Outlook.Application application = new Outlook.Application();
            Outlook.Explorer    explorer    = application.ActiveExplorer();
            Outlook.Selection   selected    = explorer.Selection;
            foreach (Object obj in selected)
            {
                itemCountTotal++;
                if (obj is Outlook.MailItem)
                {
                    min = 0;
                    Outlook.MailItem    mailItem    = (Outlook.MailItem)obj;
                    Outlook.Attachments attachments = mailItem.Attachments;
                    if (attachments != null && attachments.Count > 0)
                    {
                        int attachmentCount = attachments.Count;
                        // Iterate through attachments of this email
                        for (int i = 1; i <= attachmentCount; i++)
                        {
                            Outlook.Attachment attachment = attachments[i];
                            var    flags    = attachment.PropertyAccessor.GetProperty("http://schemas.microsoft.com/mapi/proptag/0x37140003");
                            String fileName = attachments[i].DisplayName;
                            // To ignore embedded attachments
                            if (flags != 4)
                            {
                                // To ignore embedded attachments in RTF mail with type 6
                                if ((int)attachment.Type != 6)
                                {
                                    if (firstPrompt != true)
                                    {
                                        DialogResult result = folderBrowserDialog1.ShowDialog();
                                        if (result == DialogResult.OK)
                                        {
                                            path = folderBrowserDialog1.SelectedPath;
                                        }
                                        else if (result == DialogResult.Cancel)
                                        {
                                            return;
                                        }
                                        firstPrompt = true;
                                    }
                                    validAttachments++;
                                    // If file exists, prompt user to overwrite; otherwise save the file. If user clicks yes, overwrite; user clicks no, do nothing.
                                    if (File.Exists(path + "\\" + fileName))
                                    {
                                        DialogResult dialogResult = MessageBox.Show("A file named \"" + fileName + "\" already exists in this directory. Would you like to save this as an additional copy?", "File exists", MessageBoxButtons.YesNo);
                                        if (dialogResult == DialogResult.Yes)
                                        {
                                            int count = 1;
                                            min = 1;
                                            string fullPath     = path + "\\" + fileName;
                                            string fileNameOnly = Path.GetFileNameWithoutExtension(fullPath);
                                            string extension    = Path.GetExtension(fullPath);
                                            path = Path.GetDirectoryName(fullPath);
                                            string newFullPath = fullPath;
                                            while (File.Exists(newFullPath))
                                            {
                                                string tempFileName = string.Format("{0}({1})", fileNameOnly, count++);
                                                newFullPath = Path.Combine(path, tempFileName + extension);
                                            }
                                            attachments[i].SaveAsFile(newFullPath);
                                        }
                                        else if (dialogResult == DialogResult.No)
                                        {
                                        }
                                    }
                                    else
                                    {
                                        attachments[i].SaveAsFile(path + "\\" + fileName);
                                        min = 1;
                                    }
                                }
                            }
                        }
                        if (min == 1)
                        {
                            itemCountSaved++;
                        }
                    }
                }
            }
            if (validAttachments == 0)
            {
                MessageBox.Show("There are no attachments to save.");
            }
            else
            {
                MessageBox.Show("Saved attachments from " + itemCountSaved + " out of " + itemCountTotal + " emails.");
            }
        }
Пример #43
0
        /// <summary>
        /// The method used to close "Microsoft Outlook" window
        /// </summary>
        /// <param name="src">AutomationElement type window which need to close </param>
        /// <param name="e">AutomationEventArgs</param>
        public static void OnWindowOpen(object src, AutomationEventArgs e)
        {
            if (e.EventId != WindowPattern.WindowOpenedEvent)
            {
                return;
            }
            AutomationElement sourceElement = null;

            try
            {
                sourceElement = src as AutomationElement;
                AutomationElement desktop = AutomationElement.RootElement;
                if (sourceElement.Current.IsEnabled == true)
                {
                    if (sourceElement.Current.Name == "Microsoft Outlook")
                    {
                        // Get outlook window
                        Outlook.Application oApp         = Marshal.GetActiveObject("Outlook.Application") as Outlook.Application;
                        var nameSpace                    = oApp.GetNamespace("MAPI");
                        Outlook.MAPIFolder folder        = nameSpace.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox);
                        string             userName      = folder.Parent.Name;
                        var condition_Outlook            = new PropertyCondition(AutomationElement.NameProperty, "Inbox - " + userName + " - Outlook");
                        AutomationElement window_outlook = Utilities.WaitForElement(desktop, condition_Outlook, TreeScope.Children, 10);
                        // Click OK in Microsoft Outlook dialog box
                        var           condition_Dailog      = new PropertyCondition(AutomationElement.NameProperty, "Microsoft Outlook");
                        var           window_Dailog         = Utilities.WaitForElement(window_outlook, condition_Dailog, TreeScope.Children, 10);
                        var           condition_DailogOK    = new PropertyCondition(AutomationElement.NameProperty, "OK");
                        var           item_DailogOK         = Utilities.WaitForElement(window_Dailog, condition_DailogOK, TreeScope.Children, 10);
                        InvokePattern clickPattern_DailogOK = (InvokePattern)item_DailogOK.GetCurrentPattern(InvokePattern.Pattern);
                        clickPattern_DailogOK.Invoke();
                    }
                    else if (sourceElement.Current.Name.Contains(" - Meeting Occurrence"))
                    {
                        // Get the first recurring meeting and change the meeting time
                        Outlook.AppointmentItem appointment = Utilities.GetAppointment();
                        // Get Meeting Window
                        var condition_MeetingWindow = new PropertyCondition(AutomationElement.NameProperty, appointment.Subject + " - Meeting Occurrence  ");
                        var window_Meeting          = Utilities.WaitForElement(desktop, condition_MeetingWindow, TreeScope.Children, 10);

                        // update starttime and endtime
                        Condition         cd_start      = new AndCondition(new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Edit), new PropertyCondition(AutomationElement.NameProperty, "Start time"));
                        AutomationElement item_start    = Utilities.WaitForElement(window_Meeting, cd_start, TreeScope.Descendants, 10);
                        ValuePattern      Pattern_start = (ValuePattern)item_start.GetCurrentPattern(ValuePattern.Pattern);
                        item_start.SetFocus();
                        Pattern_start.SetValue(DateTime.Now.AddMinutes(30).Hour.ToString() + ":" + DateTime.Now.AddMinutes(30).Minute.ToString());
                        Condition         cd_end      = new AndCondition(new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Edit), new PropertyCondition(AutomationElement.NameProperty, "End time"));
                        AutomationElement item_end    = Utilities.WaitForElement(window_Meeting, cd_end, TreeScope.Descendants, 10);
                        ValuePattern      Pattern_end = (ValuePattern)item_end.GetCurrentPattern(ValuePattern.Pattern);
                        item_end.SetFocus();
                        Pattern_end.SetValue(DateTime.Now.AddMinutes(60).Hour.ToString() + ":" + DateTime.Now.AddMinutes(60).Minute.ToString());
                        // Check receiver name and sendupdate
                        Condition         cd_CheckName      = new AndCondition(new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Button), new PropertyCondition(AutomationElement.NameProperty, "Check Names"));
                        AutomationElement item_CheckName    = Utilities.WaitForElement(window_Meeting, cd_CheckName, TreeScope.Descendants, 10);
                        InvokePattern     Pattern_CheckName = (InvokePattern)item_CheckName.GetCurrentPattern(InvokePattern.Pattern);
                        Pattern_CheckName.Invoke();
                        Condition         cd_send      = new AndCondition(new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Button), new PropertyCondition(AutomationElement.NameProperty, "Send Update"));
                        AutomationElement item_send    = Utilities.WaitForElement(window_Meeting, cd_send, TreeScope.Descendants, 10);
                        InvokePattern     Pattern_send = (InvokePattern)item_send.GetCurrentPattern(InvokePattern.Pattern);
                        Pattern_send.Invoke();
                    }
                }
            }
            catch (ElementNotAvailableException ex)
            {
                throw new Exception(ex.Message);
            }
        }
Пример #44
0
 public void Dispose()
 {
     oApp = null;
 }
Пример #45
0
        private void gridControl3_DoubleClick(object sender, EventArgs e)
        {
            DevExpress.XtraGrid.Views.Grid.ViewInfo.GridHitInfo hi =
                gridView5.CalcHitInfo((sender as System.Windows.Forms.Control).PointToClient(System.Windows.Forms.Control.MousePosition));
            DataRow FocusRow;

            if (hi.RowHandle >= 0)
            {
                FocusRow = gridView5.GetDataRow(hi.RowHandle);
                string strType = FocusRow.ItemArray[3].ToString();
                string strPath = FocusRow.ItemArray[4].ToString();
                if (strType == "OUTLOOK")
                {
                    try
                    {
                        Email.Application oApp      = new Email.Application();
                        Email._MailItem   oMailItem = (Email._MailItem)oApp.CreateItemFromTemplate(strPath, Type.Missing);
                        //oMailItem.Subject = "abc";

                        oMailItem.Display(false);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                }
                else if (strType == "WORD")
                {
                    try
                    {
                        Word.Application wordApp;
                        Word.Document    doc;
                        wordApp         = new Word.ApplicationClass();
                        wordApp.Visible = true;
                        object fileName  = strPath;
                        object missing   = Type.Missing;
                        object fReadOnly = false;
                        doc = wordApp.Documents.Open(ref fileName,
                                                     ref missing, ref fReadOnly, ref missing, ref missing, ref missing,
                                                     ref missing, ref missing, ref missing, ref missing, ref missing,
                                                     ref missing, ref missing, ref missing, ref missing, ref missing);
                        //doc.Activate();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                }
                else if (strType == "EXCEL")
                {
                    try
                    {
                        Excel.ApplicationClass oExcel   = new Excel.ApplicationClass();
                        Excel.Workbook         workBook = oExcel.Workbooks.Open(strPath, 0, true, 5, null, null, true, Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, null, null);
                        //Excel.Worksheet ws = (Excel.Worksheet)oExcel.ActiveSheet;
                        //ws.Activate();
                        //ws.get_Range("A1", "IV65536").Font.Size = 8;
                        oExcel.Visible = true;
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                }
                else if (strType == "PDF")
                {
                    ACMS.ACMSStaff.To_Do_List.frmPDFviewer frm = new ACMS.ACMSStaff.To_Do_List.frmPDFviewer(strPath);
                    frm.Show();
                }
                else if (strType == "VIDEO")
                {
                    ACMS.ACMSStaff.To_Do_List.frmVideoPlayer frmPlayer = new ACMS.ACMSStaff.To_Do_List.frmVideoPlayer(strPath);
                    frmPlayer.Show();
                }
            }
            else if (gridView5.FocusedRowHandle >= 0)
            {
                FocusRow = gridView5.GetDataRow(gridView5.FocusedRowHandle);
                string strType = FocusRow.ItemArray[3].ToString();
                string strPath = FocusRow.ItemArray[4].ToString();
                //ACMS.ACMSStaff.WorkFlow.MyCustomEditForm frm = new ACMS.ACMSStaff.WorkFlow.MyCustomEditForm((int)FocusRow.ItemArray[0], oUser.NDepartmentID());
                //frm.Show();
            }
        }
Пример #46
0
 private void ContractSync_Load(object sender, RibbonUIEventArgs e)
 {
     _app = Globals.ThisAddIn.Application;
 }
        private void sendReviewButton_Click(object sender, EventArgs e)
        {
            File.WriteAllText(m_commitMessageFilePath, reviewDescriptionTextBox.Text);

            try
            {
                Outlook.Application oApp = new Outlook.Application();

                Outlook.MailItem oMsg = (Outlook.MailItem)oApp.CreateItem(Outlook.OlItemType.olMailItem);

                oMsg.Body = reviewDescriptionTextBox.Text;

                String sDisplayName = "Patch to review";
                int    iPosition    = (int)oMsg.Body.Length + 1;
                int    iAttachType  = (int)Outlook.OlAttachmentType.olByValue;

                Outlook.Attachment oAttach = oMsg.Attachments.Add(m_reviewPatchFilePath, iAttachType, iPosition, sDisplayName);

                if (System.IO.File.Exists(Path.Combine(m_workingCopyPath, "binaryFiles.zip")))
                {
                    String sDisplayName2 = "Binary files";
                    int    iPosition2    = (int)oMsg.Body.Length + 2;
                    int    iAttachType2  = (int)Outlook.OlAttachmentType.olByValue;

                    Outlook.Attachment oAttach2 = oMsg.Attachments.Add(Path.Combine(m_workingCopyPath, "binaryFiles.zip"), iAttachType2, iPosition2, sDisplayName2);
                }

                oMsg.Subject = "[CodeReview] - ";

                Outlook.Recipients oRecips = (Outlook.Recipients)oMsg.Recipients;
                Outlook.Recipient  oRecip  = (Outlook.Recipient)oRecips.Add(GroupTextBox.Text);
                oRecip.Resolve();

                oMsg.Send();

                oRecip  = null;
                oRecips = null;
                oMsg    = null;
                oApp    = null;
            }
            catch (Exception ex)
            {
            }

            Settings.Default.reviewerEmail = GroupTextBox.Text;
            Settings.Default.Save();

            string strCmdText;

            strCmdText = @"post --branch ""{0}"" --target-groups ""{1}"" --markdown --description- file ""{2}""";
            string branch = "trunk";
            string group  = "ips";

            Process process = new Process();

            process.StartInfo.FileName         = "rbt";
            process.StartInfo.WorkingDirectory = m_workingCopyPath;
            process.StartInfo.Arguments        = string.Format(strCmdText, branch, group, m_commitMessageFilePath);
            process.Start();
            process.WaitForExit();

            Close();
        }
Пример #48
0
        private void processCSV(string csvPath)
        {
            int lineCount = 0;

            try
            {
                lineCount = File.ReadLines(csvPath).Count();
            }
            catch (System.Exception e)
            {
                writeToLog("Exception: " + e.Message, true);
                return;
            }

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

            Info infoWindow = new Info();

            infoWindow.progressBar.Maximum = lineCount;
            infoWindow.Show();

            using (TextFieldParser parser = new TextFieldParser(csvPath, Encoding.Default, true))
            {
                parser.TextFieldType = FieldType.Delimited;
                parser.SetDelimiters(",");

                OutlookApp outlookApp = new OutlookApp();

                while (!parser.EndOfData)
                {
                    string[] fields = parser.ReadFields();

                    if (fields.Count() > 6)
                    {
                        string name  = fields[3].Trim();
                        string email = fields[6].Replace(" ", "");

                        if ((name.Count() > 0) && (email.Count() > 3))
                        {
                            try
                            {
                                sendEmail(name, email, ref outlookApp);
                            }
                            catch (System.Exception ex)
                            {
                                string errorMessage = "An exception is occurred in the code of add-in. Message: " + ex.Message;
                                writeToLog(errorMessage);
                                errorList.Add(errorMessage);
                            }

                            ++infoWindow.progressBar.Value;
                        }
                        else
                        {
                            string errorMessage = "Could not send email: name is " + name + " email is " + email;
                            writeToLog(errorMessage);
                            errorList.Add(errorMessage);
                        }
                    }
                    else
                    {
                        string errorMessage = "Could not send email: Csv bad format. There should be at least 7 fields in a row. Fields data: " + fields;
                        writeToLog(errorMessage);
                        errorList.Add(errorMessage);
                    }
                }
            }

            infoWindow.Close();

            if (errorList.Count() > 0)
            {
                Report reportWindow = new Report();
                reportWindow.listBox.Items.Clear();

                foreach (string item in errorList)
                {
                    reportWindow.listBox.Items.Add(item);
                }

                reportWindow.ShowDialog();
            }
        }
Пример #49
0
        static void Main(string[] args)
        {
            Microsoft.Office.Interop.Outlook.Application app = new Microsoft.Office.Interop.Outlook.Application();
            Microsoft.Office.Interop.Outlook.NameSpace   ns  = app.GetNamespace("MAPI");

            try
            {
                if (args.Length == 1)
                {
                    if (args[0] == "GetAllFolders")
                    {
                        GetAllFolders(ns);
                    }
                    else if (args[0] == "GetGlobalAddressEx")
                    {
                        GetGlobalAddress(ns);
                    }
                    else if (args[0] == "GetContactsEx")
                    {
                        GetContacts(ns);
                    }
                    else if (args[0] == "GetConfig")
                    {
                        GetConfig(ns, "short");
                    }
                    else if (args[0] == "GetConfigEx")
                    {
                        GetConfig(ns, "all");
                    }
                    else
                    {
                        Console.WriteLine("[!] Wrong parameter");
                    }
                }
                else if (args.Length == 2)
                {
                    if (args[0] == "ListMail")
                    {
                        ListMail(ns, args[1], "short");
                    }
                    else if (args[0] == "ListUnreadMail")
                    {
                        ListUnreadMail(ns, args[1], "short");
                    }
                    else if (args[0] == "ListMailEx")
                    {
                        ListMail(ns, args[1], "all");
                    }
                    else if (args[0] == "ListUnreadMailEx")
                    {
                        ListUnreadMail(ns, args[1], "all");
                    }
                    else
                    {
                        Console.WriteLine("[!] Wrong parameter");
                    }
                }

                else if (args.Length == 3)
                {
                    if (args[0] == "SaveAttachment")
                    {
                        SaveAttachment(ns, args[1], args[2]);
                    }
                    else
                    {
                        Console.WriteLine("[!] Wrong parameter");
                    }
                }
                else
                {
                    ShowUsage();
                }
            }
            catch (System.Exception ex)
            {
                Console.WriteLine("[!] Exception:" + ex.Message);
            }
        }
Пример #50
0
        private void LoadIncEmail()
        {
            Log("Begin Load IncEmail from Local Machine");
            var dict       = new Dictionary <string, List <IncEmailItem> >();
            var otherEmail = new Dictionary <string, List <IncEmailItem> >();

            Func <string, IncEmailItem, List <string> > ExtractIncidentName = (s, i) =>
            {
                s = s.Trim();
                var matches1      = Regex.Matches(s, @"ICT_INC\d+");
                var matches2      = Regex.Matches(s, @"ICT_WO\d+");
                var matchesValues = matches1.Cast <Match>().Where(x => x.Success).Select(x => x.Value).Union(matches2.Cast <Match>().Where(x => x.Success).Select(x => x.Value)).ToList();
                foreach (var matchItem in matchesValues)
                {
                    if (!dict.ContainsKey(matchItem))
                    {
                        dict.Add(matchItem, new List <IncEmailItem>());
                    }

                    dict[matchItem].Add(i);
                }

                if (!matchesValues.Any())
                {
                    var upperTitle = s.ToUpper();
                    if (upperTitle.StartsWith("FW:") || upperTitle.StartsWith("RE:") || upperTitle.StartsWith("CT:"))
                    {
                        if (upperTitle.Length > 3)
                        {
                            s = s.Substring(3).Trim();
                        }
                    }
                    if (!otherEmail.ContainsKey(s))
                    {
                        otherEmail.Add(s, new List <IncEmailItem>());
                    }

                    otherEmail[s].Add(i);
                }

                return(matchesValues);
            };


            oApp   = new Microsoft.Office.Interop.Outlook.Application();
            oNS    = oApp.GetNamespace("mapi");
            stores = oNS.Stores;
            var folders = settings.ScanFolders;

            foreach (Store store in stores)
            {
                // continue;
                Log("Read Store: " + store.DisplayName);
                MAPIFolder YOURFOLDERNAME = store.GetRootFolder();
                Log("MAPIFolder: " + YOURFOLDERNAME.Name);
                foreach (MAPIFolder subF in YOURFOLDERNAME.Folders)
                {
                    var f = subF.Name;
                    Log("MAPIFolder: " + f + "#");
                    if (folders.Contains(f))
                    {
                        ScanFolder(ExtractIncidentName, subF);
                    }
                    else
                    {
                        // Log("SKip read Mail in folder " + subF.Name);
                    }
                }
            }

            Log("Proceed mail...");
            foreach (var item in dict)
            {
                this.incEmails.Add(item.Key, item.Value.OrderByDescending(x => x.ReceivedTime).ToList());
            }

            foreach (var item in otherEmail)
            {
                this.otherEmails.Add(item.Key, item.Value.OrderByDescending(x => x.ReceivedTime).ToList());
            }

            Log("Log off outlook...");
            //Log off.
            oNS.Logoff();
        }
        private void loadCalenderEvents()
        {
            calender_events_table.ColumnCount     = 8;
            calender_events_table.Columns[0].Name = "Subject";
            calender_events_table.Columns[1].Name = "Organizer";
            calender_events_table.Columns[2].Name = "Location";

            calender_events_table.Columns[3].Name = "StartTime";
            //Styling
            calender_events_table.Columns["StartTime"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            //
            calender_events_table.Columns[4].Name = "EndTime";
            //Styling
            calender_events_table.Columns["EndTime"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            //
            calender_events_table.Columns[5].Name = "StartDate";
            //Styling
            calender_events_table.Columns["StartDate"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            //
            calender_events_table.Columns[6].Name = "EndDate";
            //Styling
            calender_events_table.Columns["EndDate"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            //
            calender_events_table.Columns[7].Name = "AllDayEvent";
            //Styling
            calender_events_table.Columns["AllDayEvent"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            //

            //Styling
            for (int i = 3; i <= 7; i++)
            {
                calender_events_table.Columns[i].HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
                calender_events_table.Columns[i].SortMode = DataGridViewColumnSortMode.NotSortable;
            }

            Microsoft.Office.Interop.Outlook.Application oApp = null;
            NameSpace  mapiNamespace        = null;
            MAPIFolder CalendarFolder       = null;
            Items      outlookCalendarItems = null;

            oApp                 = new Microsoft.Office.Interop.Outlook.Application();
            mapiNamespace        = oApp.GetNamespace("MAPI");;
            CalendarFolder       = mapiNamespace.GetDefaultFolder(OlDefaultFolders.olFolderCalendar);
            outlookCalendarItems = CalendarFolder.Items;
            outlookCalendarItems.IncludeRecurrences = true;

            foreach (AppointmentItem item in outlookCalendarItems)
            {
                if (item.IsRecurring)
                {
                    RecurrencePattern rp   = item.GetRecurrencePattern();
                    DateTime          date = DateTime.Now;

                    DateTime        first = new DateTime((int)date.Year, (int)date.Month, (int)date.Day, item.Start.Hour, item.Start.Minute, 0);
                    DateTime        last  = new DateTime((int)date.Year, (int)date.Month, (int)date.Day);
                    AppointmentItem recur = null;

                    for (DateTime cur = first; cur <= last; cur = cur.AddDays(1))
                    {
                        try
                        {
                            recur = rp.GetOccurrence(cur);
                            //MessageBox.Show(recur.Subject + " -> " + cur.ToLongDateString());
                            int             rowID = calender_events_table.Rows.Add();
                            DataGridViewRow row   = calender_events_table.Rows[rowID];
                            row.Cells["Subject"].Value   = recur.Subject;
                            row.Cells["Organizer"].Value = recur.Organizer;
                            if (recur.Location == null)
                            {
                                row.Cells["Location"].Value = "Not Set";
                            }
                            else
                            {
                                row.Cells["Location"].Value = recur.Location;
                            }
                            row.Cells["StartTime"].Value   = recur.Start.TimeOfDay.ToString();
                            row.Cells["EndTime"].Value     = recur.End.TimeOfDay.ToString();
                            row.Cells["StartDate"].Value   = recur.Start.Date.ToShortDateString();
                            row.Cells["End Date"].Value    = recur.End.Date.ToShortDateString();
                            row.Cells["AllDayEvent"].Value = recur.AllDayEvent;
                        }
                        catch
                        { }
                    }
                }
                else
                {
                    int             rowID = calender_events_table.Rows.Add();
                    DataGridViewRow row   = calender_events_table.Rows[rowID];
                    row.Cells["Subject"].Value   = item.Subject;
                    row.Cells["Organizer"].Value = item.Organizer;
                    if (item.Location == null)
                    {
                        row.Cells["Location"].Value = "Not Set";
                    }
                    else
                    {
                        row.Cells["Location"].Value = item.Location;
                    }
                    row.Cells["StartTime"].Value   = item.Start.TimeOfDay.ToString();
                    row.Cells["EndTime"].Value     = item.End.TimeOfDay.ToString();
                    row.Cells["StartDate"].Value   = item.Start.Date.ToShortDateString();
                    row.Cells["EndDate"].Value     = item.End.Date.ToShortDateString();
                    row.Cells["AllDayEvent"].Value = item.AllDayEvent;
                }
            }

            calender_events_table.Columns[0].HeaderText = "Subject";
            calender_events_table.Columns[1].HeaderText = "Organizer";
            calender_events_table.Columns[2].HeaderText = "Location";
            calender_events_table.Columns[3].HeaderText = "Start Time";
            calender_events_table.Columns[4].HeaderText = "End Time";
            calender_events_table.Columns[5].HeaderText = "Start Date";
            calender_events_table.Columns[6].HeaderText = "End Date";
            calender_events_table.Columns[7].HeaderText = "All Day Event";

            DataGridViewImageColumn viewBtn   = new DataGridViewImageColumn();
            DataGridViewImageColumn deleteBtn = new DataGridViewImageColumn();

            viewBtn.Name        = "view_btn";
            viewBtn.HeaderText  = "";
            viewBtn.Image       = Resources.view;
            viewBtn.ImageLayout = DataGridViewImageCellLayout.Zoom;
            calender_events_table.Columns.Insert(8, viewBtn);

            deleteBtn.Name        = "delete_btn";
            deleteBtn.HeaderText  = "";
            deleteBtn.Image       = Resources.delete;
            deleteBtn.ImageLayout = DataGridViewImageCellLayout.Zoom;
            calender_events_table.Columns.Insert(9, deleteBtn);
            //Set Column Width
            for (int i = 0; i <= 7; i++)
            {
                DataGridViewColumn tt_id_col = calender_events_table.Columns[i];
                if (i == 0)
                {
                    tt_id_col.Width = 230;
                }
                else if (i == 1)
                {
                    tt_id_col.Width = 160;
                }
                else if (i == 2)
                {
                    tt_id_col.Width = 100;
                }
                else if (i == 3)
                {
                    tt_id_col.Width = 80;
                }
                else if (i == 4)
                {
                    tt_id_col.Width = 80;
                }
                else if (i == 5)
                {
                    tt_id_col.Width = 80;
                }
                else if (i == 6)
                {
                    tt_id_col.Width = 80;
                }
                else if (i == 7)
                {
                    tt_id_col.Width = 110;
                }
            }
        }
        static void Main(string[] args)
        {
repiat:
            Console.Clear();
            Console.WriteLine("НАчинаю работу приложения");
            /************************переменные для логера**************************/
            const string Error_   = "Ошибка";
            const string Warning_ = "Предупреждение";
            const string Event_   = "Событие";

            /************************переменные для логера конец********************/
            //Logger.Run_();
            Logger.WriteLog(Event_, 0, "Старт");
            /**********Выполняем батники для отправки**********/
            /***********Переменные для батников*********/
            string batPuttyOut1 = @"C:\tkM\copyOUTputty.bat";
            string batPuttyOut2 = @"C:\tkM\copyOUTarch.bat";
            string batInPutty1  = @"C:\tkM\copyOUTarch.bat";
            string batInPutty2  = @"C:\tkM\copyOUTarch.bat";

            string pathBat = @"C:\tkM";

            string descrBatO1 = "fromPuttyToOut1";
            string descrBatO2 = "fromPuttyToOut2";
            string descrBatI3 = "fromPuttyToIN1";
            string descrBatI4 = "fromPuttyToIN2";


            //*************батники на отправку*********//
            FileM.ProcManage(batPuttyOut1, pathBat, descrBatO1);
            FileM.ProcManage(batPuttyOut2, pathBat, descrBatO2);


            //try
            //{
            //System.Diagnostics.Process proc = new System.Diagnostics.Process();
            //proc.StartInfo.FileName = @"C:\tkM\copyOUTarch.bat";
            //proc.StartInfo.WorkingDirectory = @"C:\tkM";
            //proc.Start();

            //proc.WaitForExit();
            //    Console.WriteLine("Батники на отправку успешно отработали");
            //    Logger.WriteLog(Event_ , 0, "Батники на отправку успешно отработали");
            //    proc = null; //ufc
            //}
            //catch(System.Exception ex)
            //{

            //    Logger.WriteLog(Error_, 100 , "ошибка выолнения батников" +  Convert.ToString(ex.Message));
            //    Console.WriteLine("ошибка выолнения батников" + Convert.ToString(ex.Message));
            //}
            /********************/

            Logger.WriteLog(Event_, 0, "Выполняю модуль отправки писем"); Console.WriteLine("Выполняю модуль отправки писем");
            //Outlook.Application application; //
            Outlook._NameSpace nameSpace;
            Outlook.MAPIFolder folderInbox;
            //////////////////////////////////
            //Microsoft.Office.Interop.Outlook._Folders oFolders;

            ///////////////1 модуль отправки файлов///////////////////
            string[] dirs;
            dirs = Directory.GetFiles(@"C:\tkM\OUT");                                //дирректория - откуда берём файл
            String dirs1count = Directory.GetFiles(@"C:\tkM\OUT").Length.ToString(); //если в папке out что то есть то отправляем письмо

            for (int i = 0; i < dirs.Length; i++)                                    //для отправки 1 письмо + 1 файл
            {
                Logger.WriteLog(Event_, 0, "Запускаю цикл обработки и отправки входящих файлов");

                if (Convert.ToInt32(dirs1count) > 0)

                {
                    Logger.WriteLog(Event_, 0, "Колличество файлов на отправку: " + dirs1count); Console.WriteLine("Выполняю модуль отправки писем");
                    //string dirArch = "C://OUT//ARCH//";
                    try
                    {
                        //тело отправляемого сообщения


                        Outlook._Application _app = new Outlook.Application();
                        Outlook.MailItem     mail = (Outlook.MailItem)_app.CreateItem(Outlook.OlItemType.olMailItem);
                        mail.To         = "*****@*****.**";               //"*****@*****.**";
                        mail.Subject    = "test1567";                              // тема
                        mail.Body       = "This is test message1156711";           //текст письма
                        mail.Importance = Outlook.OlImportance.olImportanceNormal; //какае то нужная вещь


                        foreach (string s in dirs)
                        {
                            try
                            {
                                Console.WriteLine(s);
                                mail.Attachments.Add(s);                          //добавляем вложения в письмо - возможно добавить сразу все вложения
                                File.Move(s, s.Replace("OUT", "ARCH"));           //После успешного прикрепления файла, переносим их в папку C:\ARCH
                                ((Outlook._MailItem)mail).Send();                 //отправляем письмо
                                Console.WriteLine("Файл" + s + "отправлен в ТК"); // если все хорошо, то выдаём в консоль сообщение
                                Logger.WriteLog(Event_, 0, "Файл" + s + "отправлен в ТК");
                                break;                                            // выхожу из цикла, что бы реализовать фичу 1 фал = 1 письмо, и так сойдёт :) рефакторинг потом
                            }
                            catch (System.Exception ex)
                            {
                                Logger.WriteLog(Warning_, 201, "Системное исключение" + ex.Message);
                                Logger.WriteLog(Warning_, 200, "С таким именем файла уже отправлялось\n" + "Перемещаю файл" + s + "в папку Bad также прочти системное исключение");

                                Console.WriteLine("С таким именем файла уже отправлялось\n" + "Перемещаю файл в папку Bad");
                                FileM.MoveReplaceFile(s, s.Replace("OUT", "Bad")); //прописываю каталог C:\tkM\Bad так быстрее не люблю много переменных
                                System.Threading.Thread.Sleep(1000);               //спим 1000 мс что б увидеть работу кода
                            }
                        }
                        Logger.WriteLog(Event_, 0, "успешно передан файл" + dirs[i]);
                        _app = null; //убиваем ссылки на экземпляр класса
                        mail = null;

                        //Console.Read();
                    }
                    catch (System.Exception ex)
                    {
                        Logger.WriteLog(Error_, 111, "Системная информация" + ex.Message);
                        Console.WriteLine("Что то пошло не так"); // если какае то бага то пишем это сообщение
                        Console.WriteLine("Не удалось отправить файлы, переходим к приёму файлов");
                        System.Threading.Thread.Sleep(1000);
                        Logger.WriteLog(Warning_, 300, "Переходим к модулю обработки входящих писем");
                        goto importStart; //если модуль отправки не отработал то программа переходит к модулю чтения сообщений
                    }
                    ////////////////////////////Чтение сообщений и копирование вложений///////////////////////////////////////////
                }
                else
                {
                    Console.WriteLine("Файлов для отправки нет"); Logger.WriteLog(Event_, 0, "Файлов для отправки нет - Переходим к модулю обраюлтки входящих писем"); break;
                }                                               //если нет файлов во вложении то выходим из цикла
                dirs1count = Directory.GetFiles(@"C:\tkM\OUT").Length.ToString();
                dirs       = Directory.GetFiles(@"C:\tkM\OUT"); //переинициализируем переменную с каждым шагом цикла - так как файлов то меньше на 1
                System.Threading.Thread.Sleep(1000);
            }
importStart:
            Logger.WriteLog(Event_, 0, "Обрабатываем входящие письма");

            Outlook.Application oApp = new Outlook.Application();// создали новый экземпляр
            Outlook.NameSpace   oNS  = oApp.GetNamespace("MAPI");

            //Это кусорк для чтения входящих сообщений для теста и понимания как это работает(раюотаем из папки входящие)
            //oNS.Logon(Missing.Value, Missing.Value, false, true);
            //Outlook.MAPIFolder oInbox = oNS.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox);

            //for (int x = 1; x <= oInbox.Items.Count; x++)
            //{
            //    if (oInbox.Items[x] is MailItem)
            //    {
            //        //Выводим Имя отправителя
            //        Console.WriteLine(oInbox.Items[x].SenderName + "\n" + "--------------------------------------------" + "\n");

            //    }
            //}
            nameSpace = oApp.GetNamespace("MAPI");
            object missingValue = System.Reflection.Missing.Value;

            folderInbox = nameSpace.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox);                        //Outlook.OlDefaultFolders.olFolderInbox
                                                                                                                     //количество не прочитанных писем в папке Входящие (Inbox)
            Outlook.MAPIFolder rootFolder      = nameSpace.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox); //получаем доступ к папке входящие
            Outlook.MAPIFolder processedFolder = null;                                                               //processedFolder это экземпляр класса который выбирает нужную папку
            foreach (Outlook.MAPIFolder folder in rootFolder.Folders)                                                // ищем циклом папку в OUTLOOK
            {
                if (folder.Name == "IN")                                                                             //берем из папки IN
                {
                    processedFolder = folder;                                                                        // выбираю папку с которой будем работать(в OUTLOOK нужно создать правило, что бы все вообщения от почты ТК переносились в папку IN, которую мы заранее создаём в OUTLOOK)
                    break;
                }
            }


            Outlook.Items unreadItems = processedFolder.Items.Restrict("[Unread]=true");           // работаем с данной папкой и ищем не прочитанные письма
            Console.WriteLine("Непрочитанных писем в папке in = " + unreadItems.Count.ToString()); // выдать в консоль колличество непрочитанных сообщений
            Logger.WriteLog(Event_, 0, "Непрочитанных писем в папке in = " + unreadItems.Count.ToString());
            //////////здесь вываодим в консоль все данные непрочитанные письма в папке in    можно заккоментить/////////////////////////
            StringBuilder str = new StringBuilder(); //читаем текст и данные письма выыодим в консоль не обязательно, но можно оставить для логирования

            try
            {
                DateTime sysdate_ = DateTime.Now;
                foreach (Outlook.MailItem mailItem in unreadItems)
                {
                    Logger.WriteLog(Event_, 0, "Читаю письмо");
                    str.AppendLine("----------------------------------------------------");
                    str.AppendLine("SenderName: " + mailItem.SenderName);
                    str.AppendLine("To: " + mailItem.To);
                    str.AppendLine("CC: " + mailItem.CC);
                    str.AppendLine("Subject: " + mailItem.Subject);
                    str.AppendLine("Body: " + mailItem.Body);
                    str.AppendLine("CreationTime: " + mailItem.CreationTime);
                    str.AppendLine("ReceivedByName: " + mailItem.ReceivedByName);
                    str.AppendLine("ReceivedTime: " + mailItem.ReceivedTime);
                    str.AppendLine("UnRead: " + mailItem.UnRead);
                    str.AppendLine(mailItem.ReceivedTime.Date.ToShortDateString() + sysdate_.ToShortDateString());
                    str.AppendLine("----------------------------------------------------");
                    Console.WriteLine(str.ToString());
                    Logger.WriteLog(Event_, 0, str.ToString());
                }
            }
            catch (System.Exception ex)     // если письмо бракованное то пробуем ещё раз
            {
                //System.Threading.Thread.Sleep(300); //пауза

                //goto repeatReadMail;
                Logger.WriteLog(Error_, 102, "Ощибка сохранения письма или" + ex.Message);
                string errorInfo = (string)ex.Message.Substring(0, 11);
                Console.WriteLine(errorInfo);    // вывести любую ошибку
                if (errorInfo == "Cannot save")
                {
                    Console.WriteLine(@"Create Folder C:\TestFileSave");
                }
                Logger.WriteLog(Event_, 0, "Перехожу к чтению вложений");
                goto repeatReadAndAddAttachmentIsMail; // перейти к чтению и вытаскиванию вложения в случае ошибки здесь
            }
            //foreach (Outlook.MailItem mail in unreadItems) //пометить как прочитанное реализация не удалять
            //{
            //    if (mail.UnRead)
            //    {
            //        mail.UnRead = false;
            //        mail.Save();
            //    }
            //}
            //////////////////Вытаскивание вложение и пометить письмо как прочитанное
repeatReadAndAddAttachmentIsMail:
            Outlook.Items inBoxItems = processedFolder.Items.Restrict("[Unread]=true");    //show unread message and inicialise varible

            Outlook.MailItem newEmail = null;
            try
            {
                foreach (object collectionItem in inBoxItems)
                {
                    newEmail = collectionItem as Outlook.MailItem;
                    DateTime sysdate_ = DateTime.Now;                                                                           //SYSDATE
                    //mailItem.ReceivedTime.Date.ToShortDateString() + sysdate_.ToShortDateString();
                    if (newEmail != null /*&& newEmail.ReceivedTime.Date.ToShortDateString() == sysdate_.ToShortDateString()*/) //checj date of mail
                    {
                        if (newEmail.Attachments.Count > 0)
                        {
                            for (int i = 1; i <= newEmail.Attachments.Count; i++)
                            {
                                string   fileName = newEmail.Attachments[i].FileName; Console.WriteLine(@"Имя файла:" + fileName);
                                string[] dirsaRCH = Directory.GetFiles(@"C:\tkM\ARCH\");//создадим перепенную с именами файлов в папке  ARCH что бы проверять файлы в архиве
                                if (FileM.ValueOf(dirsaRCH, fileName) != "noDuble")
                                {
                                    Console.WriteLine(@"Найдено совпаление  с файлом: " + fileName + "\n Список файлов в папке:");
                                    Logger.WriteLog(Warning_, 0, @"Найдено совпаление  с файлом: " + fileName + "не обратываем");

                                    //for (int i1 = 0; i1 < dirsaRCH.Length; i1++)
                                    //{
                                    //    Console.Write( dirsaRCH[i1] + " " + File.GetCreationTime(dirsaRCH[i1]) + " - не обратываем" + ";\n");
                                    //    Logger.WriteLog(Warning_, 205, dirsaRCH[i1] + " " + File.GetCreationTime(dirsaRCH[i1]) + " - не обратываем" + ";\n");
                                    //}
                                }
                                else
                                {
                                    Console.WriteLine(@"нет совпадения файлов"); Logger.WriteLog(Event_, 0, @"Совпадений по имени не найдено");
                                    //Console.WriteLine(@"Имя файла:" + fileName);
                                    //for (int i1 = 0; i1 < dirsaRCH.Length; i1++)
                                    //{
                                    //    Console.Write("Имя файлов(а) в папке:" + dirsaRCH[i1]);
                                    //}
                                    newEmail.Attachments[i].SaveAsFile(@"C:\tkM\IN\" + newEmail.Attachments[i].FileName);
                                    Console.WriteLine(@"Файл сохранён с названием: " + newEmail.Attachments[i].FileName + " По пути:" + @"C:\tkM\IN\"); // выводим инфу об успешно копировании файла
                                    Logger.WriteLog(Event_, 0, @"Файл сохранён с названием: " + newEmail.Attachments[i].FileName + " По пути:" + @"C:\tkM\IN\");
                                }

                                //    {
                                Console.WriteLine(@"Обрабатываю письмо как прочитанное");
                                Logger.WriteLog(Event_, 0, @"Обрабатываю письмо как прочитанное");

                                System.Threading.Thread.Sleep(1000);
                                if (newEmail.UnRead) // пометить письмо как прочитанное
                                {
                                    newEmail.UnRead = false;
                                    newEmail.Save();
                                }

                                /********батники на IN************/
                                FileM.ProcManage(batInPutty1, pathBat, descrBatI3);
                                FileM.ProcManage(batInPutty2, pathBat, descrBatI4);
                                /********************/
                                string[] dirIN = Directory.GetFiles(@"C:\tkM\IN");
                                foreach (string d in dirIN)
                                {
                                    FileM.MoveReplaceFile(d, d.Replace("IN", "ARCH"));
                                }

                                Console.WriteLine(@"Завершаю работу");

                                //}
                            }
                        }
                    }
                    else
                    {
                        Console.WriteLine("Нет писем с вложением");
                    }
                }
            }
            catch (System.Exception ex)
            {
                string errorInfo = (string)ex.Message
                                   .Substring(0, 11);
                Console.WriteLine(errorInfo);
                if (errorInfo == "Cannot save")
                {
                    Console.WriteLine(@"Create Folder C:\IN");
                }
            }

            //////////выход из приложения
            oNS.Logoff();
            //oInbox = null;
            oNS  = null;
            oApp = null;
            //Console.ReadKey(); //Удалить все чтения ввода с консоли, для автоматической работы
            Logger.Flush();
            Console.WriteLine($"Закончили обработку в {DateTime.Now} " +
                              $"\nСледующий запуск приложения в {DateTime.Now.Add(TimeSpan.FromMinutes(5))} ");
            System.Threading.Thread.Sleep(15000);


            goto repiat;
        }
Пример #53
0
        private void btnNext_Click(object sender, EventArgs e)
        {
            if (btnNext.Text == "Next")
            {
                LoadMergeData();
                tabControlAdvancedMerge.SelectedTab = tabControlAdvancedMerge.TabPages[1];
                btnNext.Text = "Merge";
            }
            else if (btnNext.Text == "Merge" & btnNext.Enabled)
            {
                Word.Fields wordFields = Globals.ThisAddIn.Application.ActiveDocument.Fields;
                if (wordFields.Count > 0 && dataTableMergeData != null)
                {
                    if (Globals.ThisAddIn.Application.ActiveDocument.Saved)
                    {
                        MessageBox.Show("File is saved");
                    }
                    else
                    {
                        Globals.ThisAddIn.Application.ActiveDocument.Save();
                    }
                    string keyField = ReadDocumentProperty("KeyField");
                    Outlook.Application outlookApp      = new Outlook.Application();
                    Outlook.Accounts    outlookAccounts = outlookApp.Session.Accounts;
                    Outlook.MailItem    mailItem        = outlookApp.CreateItem(Outlook.OlItemType.olMailItem);

                    Word.Document wordDocument = Globals.ThisAddIn.Application.ActiveDocument;

                    var grouped = from table in dataTableMergeData.AsEnumerable()
                                  group table by new { keyCol = table[textBoxKeyField.Text] } into grp
                        select new
                    {
                        Value        = grp.Key,
                        ColumnValues = grp
                    };
                    foreach (var key in grouped)
                    {
                        Word.Application wordApplication = new Word.Application();
                        wordApplication.ShowAnimation = false;
                        wordApplication.Visible       = false;
                        object        missing     = System.Reflection.Missing.Value;
                        Word.Document newDocument = wordApplication.Documents.Open(wordDocument.Path + @"\" + wordDocument.Name, ReadOnly: true);

                        Word.MailMerge mailMerge = newDocument.MailMerge;


                        DataRow[] selectedRows = dataTableMergeData.Select(textBoxKeyField.Text + " ='" + key.Value.keyCol.ToString() + "'");

                        foreach (Word.MailMergeField mailMergeField in mailMerge.Fields)
                        {
                            if (mailMergeField.Code.Text.IndexOf(" MERGEFIELD " + "FirstName" + " ") > -1)
                            {
                                mailMergeField.Select();

                                mailMerge.Application.Selection.TypeText(selectedRows[1][2].ToString());
                            }
                            else if (mailMergeField.Code.Text.IndexOf(" MERGEFIELD " + "Product_name" + " ") > -1)
                            {
                                mailMergeField.Select();
                                mailMerge.Application.Selection.TypeText(selectedRows[1][4].ToString());
                                for (int i = 0; i < selectedRows.Length; i++)
                                {
                                    if (i < selectedRows.Length - 1)


                                    {
                                        for (int tableIndex = 0; tableIndex < newDocument.Tables.Count; tableIndex++)
                                        {
                                        }

/*                                        foreach  (Word.Table table in wordDocument.Tables)
 *                                      {
 *                                          foreach (Word.Row row in table.Rows)
 *                                          {
 *                                              foreach (Word.Cell cell in row.Cells)
 *                                              {
 *
 *                                              }
 *                                          }
 *
 *                                      }*/
                                        mailMerge.Application.Selection.InsertAfter("\r\n" + selectedRows[i + 1][4].ToString());
                                    }
                                }
                            }
                        }

                        mailItem.Subject = "Test";
                        mailItem.To      = "*****@*****.**";
                        mailItem.Body    = newDocument.Content.Text;
                        mailItem.Send();
                        newDocument.Close(false);
                        wordApplication.Quit(false);
                        Marshal.ReleaseComObject(newDocument);
                        Marshal.ReleaseComObject(wordApplication);
                    }
                }
            }
        }
Пример #54
0
        public bool EmailDocument(short _docType, string _fileName, string _documentReference)
        {
            try
            {
                if (LoadDocument(_docType, _fileName, _documentReference))
                {
                    MicrosoftWord.Application appWord = new MicrosoftWord.Application();

                    Object template    = _fileName;
                    Object newTemplate = false;
                    Object docType     = MicrosoftWord.WdNewDocumentType.wdNewBlankDocument;
                    Object visible     = true;

                    MicrosoftWord.Document doc = appWord.Documents.Add(ref template, ref newTemplate, ref docType, ref visible);

                    Object fileName                = documentFileName + ".docx";
                    Object fileFormat              = MicrosoftWord.WdSaveFormat.wdFormatDocumentDefault; //.wdFormatPDF;
                    Object lockComments            = Type.Missing;
                    Object password                = Type.Missing;
                    Object addToRecentFiles        = Type.Missing;
                    Object writePassword           = Type.Missing;
                    Object readOnlyRecommended     = false;
                    Object embedTrueTypeFonts      = Type.Missing;
                    Object saveNativePictureFormat = Type.Missing;
                    Object saveFormsData           = false;
                    Object saveAsAOCELetter        = Type.Missing;
                    Object encoding                = Type.Missing;
                    Object insertLineBreaks        = Type.Missing;
                    Object allowSubstitutions      = Type.Missing;
                    Object lineEnding              = Type.Missing;
                    Object addBiDiMarks            = Type.Missing;

                    doc.SaveAs(ref fileName, ref fileFormat, ref lockComments,
                               ref password, ref addToRecentFiles, ref writePassword,
                               ref readOnlyRecommended, ref embedTrueTypeFonts,
                               ref saveNativePictureFormat, ref saveFormsData,
                               ref saveAsAOCELetter, ref encoding, ref insertLineBreaks,
                               ref allowSubstitutions, ref lineEnding, ref addBiDiMarks);

                    Object saveChanges    = MicrosoftWord.WdSaveOptions.wdDoNotSaveChanges;
                    Object originalFormat = Type.Missing;
                    Object routeDocument  = Type.Missing;

                    Outlook.Application outlook = new Outlook.Application();
                    Outlook.MailItem    mail    = (Outlook.MailItem)outlook.CreateItem(Outlook.OlItemType.olMailItem);
                    mail.To         = emailAddress;
                    mail.Subject    = emailSubject;
                    mail.BodyFormat = Outlook.OlBodyFormat.olFormatHTML;
                    mail.HTMLBody   = EmailBody;
                    mail.Importance = Outlook.OlImportance.olImportanceNormal;
                    mail.Attachments.Add(fileName, Outlook.OlAttachmentType.olByValue, 1, emailSubject);

                    mail.Display(false);

                    doc.Close(ref saveChanges, ref originalFormat, ref routeDocument);
                    appWord.Quit(ref saveChanges, ref originalFormat, ref routeDocument);

                    return(true);
                }
                else
                {
                    return(false);
                }
            }
            catch (Exception err)
            {
                MessageBox.Show(err.Message, $"{err.Source}.{err.TargetSite.Name}", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return(false);
            }
        }
Пример #55
0
        public static new int Convert(String inputFile, String outputFile, Hashtable options)
        {
            Boolean running = (Boolean)options["noquit"];

            Microsoft.Office.Interop.Outlook.Application app = null;
            String tmpDocFile = null;

            try
            {
                try
                {
                    app = (Microsoft.Office.Interop.Outlook.Application)Marshal.GetActiveObject("Outlook.Application");
                }
                catch (System.Exception)
                {
                    app     = new Microsoft.Office.Interop.Outlook.Application();
                    running = false;
                }
                if (app == null)
                {
                    Console.WriteLine("Unable to start outlook instance");
                    return((int)ExitCode.ApplicationError);
                }
                var      session = app.Session;
                FileInfo fi      = new FileInfo(inputFile);
                // Create a temporary doc file from the message
                tmpDocFile = System.IO.Path.GetTempPath() + Guid.NewGuid().ToString() + ".doc";
                switch (fi.Extension.ToLower())
                {
                case ".msg":
                    var message = (MailItem)session.OpenSharedItem(inputFile);
                    if (message == null)
                    {
                        Converter.releaseCOMObject(message);
                        Converter.releaseCOMObject(session);
                        return((int)ExitCode.FileOpenFailure);
                    }
                    message.SaveAs(tmpDocFile, Microsoft.Office.Interop.Outlook.OlSaveAsType.olDoc);
                    ((_MailItem)message).Close(OlInspectorClose.olDiscard);
                    Converter.releaseCOMObject(message);
                    Converter.releaseCOMObject(session);
                    break;

                case ".vcf":
                    var contact = (ContactItem)session.OpenSharedItem(inputFile);
                    if (contact == null)
                    {
                        Converter.releaseCOMObject(contact);
                        Converter.releaseCOMObject(session);
                        return((int)ExitCode.FileOpenFailure);
                    }
                    contact.SaveAs(tmpDocFile, Microsoft.Office.Interop.Outlook.OlSaveAsType.olDoc);
                    Converter.releaseCOMObject(contact);
                    Converter.releaseCOMObject(session);
                    break;

                case ".ics":
                    // Issue #47 - there is a problem opening some ics files - looks like the issue is down to
                    // it trying to open the icalendar format
                    // See https://msdn.microsoft.com/en-us/library/office/bb644609.aspx
                    object item = null;
                    try
                    {
                        session.GetDefaultFolder(OlDefaultFolders.olFolderCalendar);
                        item = session.OpenSharedItem(inputFile);
                    }
                    catch
                    {
                    }
                    if (item != null)
                    {
                        // We were able to read in the item
                        // See if it is an item that can be converted to an intermediate Word document
                        string itemType = (string)(string)item.GetType().InvokeMember("MessageClass", System.Reflection.BindingFlags.GetProperty, null, item, null);
                        switch (itemType)
                        {
                        case "IPM.Appointment":
                            var appointment = (AppointmentItem)item;
                            if (appointment != null)
                            {
                                appointment.SaveAs(tmpDocFile, Microsoft.Office.Interop.Outlook.OlSaveAsType.olDoc);
                                Converter.releaseCOMObject(appointment);
                            }
                            break;

                        case "IPM.Schedule.Meeting.Request":
                            var meeting = (MeetingItem)item;
                            if (meeting != null)
                            {
                                meeting.SaveAs(tmpDocFile, Microsoft.Office.Interop.Outlook.OlSaveAsType.olDoc);
                                Converter.releaseCOMObject(meeting);
                            }
                            break;

                        case "IPM.Task":
                            var task = (TaskItem)item;
                            if (task != null)
                            {
                                task.SaveAs(tmpDocFile, Microsoft.Office.Interop.Outlook.OlSaveAsType.olDoc);
                                Converter.releaseCOMObject(task);
                            }
                            break;

                        default:
                            Console.WriteLine("Unable to convert ICS type " + itemType);
                            break;
                        }
                        Converter.releaseCOMObject(item);
                    }
                    else
                    {
                        Console.WriteLine("Unable to convert this type of ICS file");
                    }
                    Converter.releaseCOMObject(session);
                    break;
                }

                if (!File.Exists(tmpDocFile))
                {
                    return((int)ExitCode.UnknownError);
                }
                // Convert the doc file to a PDF
                options["IsTempWord"] = true;
                return(WordConverter.Convert(tmpDocFile, outputFile, options));
            }
            catch (System.Exception e)
            {
                Console.WriteLine(e.Message);
                return((int)ExitCode.UnknownError);
            }
            finally
            {
                if (tmpDocFile != null && File.Exists(tmpDocFile))
                {
                    try
                    {
                        System.IO.File.Delete(tmpDocFile);
                    }
                    catch (System.Exception) { }
                }
                // If we were not already running, quit and release the outlook object
                if (app != null && !running)
                {
                    ((Microsoft.Office.Interop.Outlook._Application)app).Quit();
                }
                Converter.releaseCOMObject(app);
            }
        }
Пример #56
0
        static void Main(string[] args)
        {
            //Outlook.Application application; //
            Outlook._NameSpace nameSpace;
            Outlook.MAPIFolder folderInbox;
            //////////////////////////////////
            //Microsoft.Office.Interop.Outlook._Folders oFolders;
            ///////////////1 модуль отправки файлов///////////////////
            string[] dirs;
            dirs = Directory.GetFiles(@"C:\tkM\OUT");                           //дирректория - откуда берём файл
            String dirs1 = Directory.GetFiles(@"C:\tkM\OUT").Length.ToString(); //если в папке out что то есть то отправляем письмо

            for (int i = 0; i <= dirs.Length + 1; i++)                          //для отправки 1 письмо + 1 файл
            {
                if (Convert.ToInt32(dirs1) > 0)
                {
                    //string dirArch = "C://OUT//ARCH//";
                    try
                    {
                        //тело отправляемого сообщения


                        Outlook._Application _app = new Outlook.Application();
                        Outlook.MailItem     mail = (Outlook.MailItem)_app.CreateItem(Outlook.OlItemType.olMailItem);
                        mail.To         = "*****@*****.**";               //"*****@*****.**";
                        mail.Subject    = "test1567";                              // тема
                        mail.Body       = "This is test message1156711";           //текст письма
                        mail.Importance = Outlook.OlImportance.olImportanceNormal; //какае то нужная вещь


                        foreach (string s in dirs)
                        {
                            try
                            {
                                Console.WriteLine(s);
                                mail.Attachments.Add(s);                   //добавляем вложения в письмо - возможно добавить сразу все вложения
                                File.Move(s, s.Replace("OUT", "OUTaRCH")); //После успешного прикрепления файла, переносим их в папку C:\ARCH
                                ((Outlook._MailItem)mail).Send();          //отправляем письмо
                                Console.WriteLine("Файл отправлен в ТК");  // если все хорошо, то выдаём в консоль сообщение
                                break;                                     // выхожу из цикла, что бы реализовать фичу 1 фал = 1 письмо, и так сойдёт :) рефакторинг потом
                            }
                            catch (System.Exception ex)
                            {
                                Console.WriteLine(ex.Message);
                                Console.WriteLine("С таким именем файла уже отправлялось\n" + "Перемещаю файл в папку Bad");
                                FileM.MoveReplaceFile(s, s.Replace("OUT", "Bad")); //прописываю каталог C:\tkM\Bad так быстрее не люблю много переменных
                                System.Threading.Thread.Sleep(1000);               //спим 1000 мс что б увидеть работу кода
                                Console.ReadKey();
                            }
                        }
                        _app = null; //убиваем ссылки на экземпляр класса
                        mail = null;

                        //Console.Read();
                    }
                    catch
                    {
                        Console.WriteLine("Что то пошло не так"); // если какае то бага то пишем это сообщение
                        Console.WriteLine("Не удалось отправить файлы, переходим к приёму файлов нажми любую клавишу");
                        System.Threading.Thread.Sleep(1000);
                        goto importStart; //если модуль отправки не отработал то программа переходит к модулю чтения сообщений
                    }
                    ////////////////////////////Чтение сообщений и копирование вложений///////////////////////////////////////////
                }
                else
                {
                    Console.WriteLine("Файлов для отправки нет"); break;
                }                                         //если нет файлов во вложении то выходим из цикла
                Console.ReadKey();
                dirs = Directory.GetFiles(@"C:\tkM\OUT"); //присваивание переменной с каждой итерацией цикла для обновления данных в массиве
                System.Threading.Thread.Sleep(1000);
            }
importStart:
            Outlook.Application oApp = new Outlook.Application();    // создали новый экземпляр
            Outlook.NameSpace oNS = oApp.GetNamespace("MAPI");

            //Это кусорк для чтения входящих сообщений для теста и понимания как это работает(раюотаем из папки входящие)
            oNS.Logon(Missing.Value, Missing.Value, false, true);
            Outlook.MAPIFolder oInbox = oNS.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox);

            for (int x = 1; x <= oInbox.Items.Count; x++)
            {
                if (oInbox.Items[x] is MailItem)
                {
                    //Выводим Имя отправителя
                    Console.WriteLine(oInbox.Items[x].SenderName + "\n" + "--------------------------------------------" + "\n");
                }
            }
            nameSpace = oApp.GetNamespace("MAPI");
            object missingValue = System.Reflection.Missing.Value;

            folderInbox = nameSpace.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox);                        //Outlook.OlDefaultFolders.olFolderInbox
                                                                                                                     //количество не прочитанных писем в папке Входящие (Inbox)
            Outlook.MAPIFolder rootFolder      = nameSpace.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox); //получаем доступ к папке входящие
            Outlook.MAPIFolder processedFolder = null;                                                               //processedFolder это экземпляр класса который выбирает нужную папку
            foreach (Outlook.MAPIFolder folder in rootFolder.Folders)                                                // ищем циклом папку в OUTLOOK
            {
                if (folder.Name == "IN")                                                                             //берем из папки IN
                {
                    processedFolder = folder;                                                                        // выбираю папку с которой будем работать(в OUTLOOK нужно создать правило, что бы все вообщения от почты ТК переносились в папку IN, которую мы заранее создаём в OUTLOOK)
                    break;
                }
            }


            Outlook.Items unreadItems = processedFolder.Items.Restrict("[Unread]=true");           // работаем с данной папкой и ищем не прочитанные письма
            Console.WriteLine("Непрочитанных писем в папке in = " + unreadItems.Count.ToString()); // выдать в консоль колличество непрочитанных сообщений

            //////////здесь вываодим в консоль все данные непрочитанные письма в папке in    можно заккоментить/////////////////////////
            StringBuilder str = new StringBuilder();     //читаем текст и данные письма выыодим в консоль не обязательно, но можно оставить для логирования

            try
            {
                DateTime sysdate_ = DateTime.Now;
                foreach (Outlook.MailItem mailItem in unreadItems)
                {
                    str.AppendLine("----------------------------------------------------");
                    str.AppendLine("SenderName: " + mailItem.SenderName);
                    str.AppendLine("To: " + mailItem.To);
                    str.AppendLine("CC: " + mailItem.CC);
                    str.AppendLine("Subject: " + mailItem.Subject);
                    str.AppendLine("Body: " + mailItem.Body);
                    str.AppendLine("CreationTime: " + mailItem.CreationTime);
                    str.AppendLine("ReceivedByName: " + mailItem.ReceivedByName);
                    str.AppendLine("ReceivedTime: " + mailItem.ReceivedTime);
                    str.AppendLine("UnRead: " + mailItem.UnRead);
                    str.AppendLine(mailItem.ReceivedTime.Date.ToShortDateString() + sysdate_.ToShortDateString());
                    str.AppendLine("----------------------------------------------------");
                    Console.WriteLine(str.ToString());
                }
            }
            catch (System.Exception ex)     // если письмо бракованное то пробуем ещё раз
            {
                //System.Threading.Thread.Sleep(300); //пауза

                //goto repeatReadMail;

                string errorInfo = (string)ex.Message.Substring(0, 11);
                Console.WriteLine(errorInfo);    // вывести любую ошибку
                if (errorInfo == "Cannot save")
                {
                    Console.WriteLine(@"Create Folder C:\TestFileSave");
                }
                goto repeatReadAndAddAttachmentIsMail;     // перейти к чтению и вытаскиванию вложения в случае ошибки здесь
            }
            //foreach (Outlook.MailItem mail in unreadItems) //пометить как прочитанное реализация не удалять
            //{
            //    if (mail.UnRead)
            //    {
            //        mail.UnRead = false;
            //        mail.Save();
            //    }
            //}
            //////////////////Вытаскивание вложение и пометить письмо как прочитанное
repeatReadAndAddAttachmentIsMail:
            Outlook.Items inBoxItems = processedFolder.Items.Restrict("[Unread]=true");

            Outlook.MailItem newEmail = null;
            try
            {
                foreach (object collectionItem in inBoxItems)
                {
                    newEmail = collectionItem as Outlook.MailItem;
                    DateTime sysdate_ = DateTime.Now;                                                                       //дата текущий день
                    //mailItem.ReceivedTime.Date.ToShortDateString() + sysdate_.ToShortDateString();
                    if (newEmail != null && newEmail.ReceivedTime.Date.ToShortDateString() == sysdate_.ToShortDateString()) //проарка на дату файла
                    {
                        if (newEmail.Attachments.Count > 0)
                        {
                            for (int i = 1; i <= newEmail.Attachments.Count; i++)
                            {
                                string   fileName   = newEmail.Attachments[i].FileName; Console.WriteLine(@"Имя файла:" + fileName);
                                string[] dirsINaRCH = Directory.GetFiles(@"C:\tkM\INaRCH\");//создадим перепенную с именами файлов в папке IN или IN_ARCH
                                if (FileM.ValueOf(dirsINaRCH, fileName) != "noDuble")
                                {
                                    Console.WriteLine(@"Найдено совпаление  с файлом: " + fileName + "\n Список файлов в папке:");

                                    for (int i1 = 0; i1 < dirsINaRCH.Length; i1++)
                                    {
                                        Console.Write(dirsINaRCH[i1] + " " + File.GetCreationTime(dirsINaRCH[i1]) + ";\n");
                                    }
                                }
                                else
                                {
                                    Console.WriteLine(@"нет совпадения файлов");
                                    //Console.WriteLine(@"Имя файла:" + fileName);
                                    //for (int i1 = 0; i1 < dirsINaRCH.Length; i1++)
                                    //{
                                    //    Console.Write("Имя файлов(а) в папке:" + dirsINaRCH[i1]);
                                    //}
                                    newEmail.Attachments[i].SaveAsFile(@"C:\tkM\IN\" + newEmail.Attachments[i].FileName);
                                    Console.WriteLine(@"Файл сохранён с названием: " + newEmail.Attachments[i].FileName + " По пути:" + @"C:\tkM\IN\"); // выводим инфу об успешно копировании файла
                                }

                                //    {
                                Console.WriteLine(@"Обрабатываю письмо как прочитанное");
                                System.Threading.Thread.Sleep(1000);
                                if (newEmail.UnRead) // пометить письмо как прочитанное
                                {
                                    newEmail.UnRead = false;
                                    newEmail.Save();
                                }
                                Console.WriteLine(@"Завершаю работу");
                                //}
                            }
                        }
                    }
                    else
                    {
                        Console.WriteLine("Нет писем с вложением");
                    }
                }
            }
            catch (System.Exception ex)
            {
                string errorInfo = (string)ex.Message
                                   .Substring(0, 11);
                Console.WriteLine(errorInfo);
                if (errorInfo == "Cannot save")
                {
                    Console.WriteLine(@"Create Folder C:\IN");
                }
            }

            //////////выход из приложения
            oNS.Logoff();
            oInbox = null;
            oNS    = null;
            oApp   = null;
            //Console.ReadKey(); //Удалить все чтения ввода с консоли, для автоматической работы
            System.Threading.Thread.Sleep(1000);
        }
Пример #57
-1
        protected override ActivityExecutionStatus Execute(ActivityExecutionContext context)
        {
            // Create an Outlook Application object. 
            Outlook.Application outlookApp = new Outlook.Application();

            Outlook._MailItem oMailItem = (Outlook._MailItem)outlookApp.CreateItem(Outlook.OlItemType.olMailItem);
            oMailItem.To = outlookApp.Session.CurrentUser.Address;
            oMailItem.Subject = "Auto-Reply";
            oMailItem.Body = "Out of Office";

            //adds it to the outbox  
            if (this.Parent.Parent is ParallelActivity)
            {
                if ((this.Parent.Parent.Parent.Activities[1] as DummyActivity).TitleProperty != "")
                {
                    MessageBox.Show("Process Auto-Reply for Email");
                    oMailItem.Send();
                }
            }
            else if (this.Parent.Parent is SequentialWorkflowActivity)
            {
                if ((this.Parent.Parent.Activities[1] as DummyActivity).TitleProperty != "")
                {
                    MessageBox.Show("Process Auto-Reply for Email");
                    oMailItem.Send();
                }
            }
            return ActivityExecutionStatus.Closed;
        }
Пример #58
-1
 private void CreateRecurringAppointment()
 {
     Outlook.Application outlookApp = new Outlook.Application();
     try
     {
         Outlook.AppointmentItem appt = outlookApp.CreateItem(
             Outlook.OlItemType.olAppointmentItem)
             as Outlook.AppointmentItem;
         appt.Subject = "Customer Review";
         appt.MeetingStatus = Outlook.OlMeetingStatus.olMeeting;
         appt.Location = "36/2021";
         appt.Start = DateTime.Parse("10/20/2006 10:00 AM");
         appt.End = DateTime.Parse("10/20/2006 11:00 AM");
         appt.Body = "Testing";
         Outlook.Recipient recipRequired =
             appt.Recipients.Add("Ryan Gregg");
         recipRequired.Type =
             (int)Outlook.OlMeetingRecipientType.olRequired;
         Outlook.Recipient recipOptional =
             appt.Recipients.Add("Peter Allenspach");
         recipOptional.Type =
             (int)Outlook.OlMeetingRecipientType.olOptional;
         Outlook.Recipient recipConf =
            appt.Recipients.Add("Conf Room 36/2021 (14) AV");
         recipConf.Type =
             (int)Outlook.OlMeetingRecipientType.olResource;
         appt.Recipients.ResolveAll();
         appt.Display(false);
     }
     catch (Exception ex)
     {
         System.Windows.MessageBox.Show("The following error occurred: " + ex.Message);
     }
 }
Пример #59
-1
		public void Setup()
		{
			if (!Global.IsReadyRedlineEnabled)
				return;

			_outlookApp = new MsOutlook.ApplicationClass();				
		}
Пример #60
-1
		public OutlookPortal()
		{
			oApp = new Microsoft.Office.Interop.Outlook.Application();
			oNameSpace = oApp.GetNamespace("MAPI");
			oOutboxFolder = oNameSpace.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderOutbox);
			oNameSpace.Logon(null, null, false, false);
			oMailItem =	(Microsoft.Office.Interop.Outlook._MailItem)oApp.CreateItem(Microsoft.Office.Interop.Outlook.OlItemType.olMailItem);
			
		}