private void button7_Click(object sender, EventArgs e)
        {
            String outlookAccString = (String)comboBoxOutlookAcc.SelectedItem;

            Outlook.Account acc = (Outlook.Account)outlookAccs[outlookAccString];
            mailHandler.sendAll(acc);
        }
        /// <summary>
        /// Constructor. Initiated from MailConnection object
        /// </summary>
        /// <param name="store">Outlook.Store oibject</param>
        public MailStore(Outlook.Store store)
        {
            _store   = store;
            _outlook = store.Application;

            // Initalizes the dictionary of supported default Outlook folders
            _folderTypes.Add("olFolderInbox", Outlook.OlDefaultFolders.olFolderInbox);
            _folderTypes.Add("olFolderDeletedItems", Outlook.OlDefaultFolders.olFolderDeletedItems);
            _folderTypes.Add("olFolderDrafts", Outlook.OlDefaultFolders.olFolderDrafts);
            _folderTypes.Add("olFolderJunk", Outlook.OlDefaultFolders.olFolderJunk);
            _folderTypes.Add("olFolderOutbox", Outlook.OlDefaultFolders.olFolderOutbox);
            _folderTypes.Add("olFolderSentMail", Outlook.OlDefaultFolders.olFolderSentMail);

            // Finding Account associated with this store
            // Loops over the Accounts collection of the current Outlook session.
            _userAccount = null;
            Outlook.Accounts accounts = _outlook.Session.Accounts;

            foreach (Outlook.Account account in accounts)
            {
                // When the e-mail address matches, return the account.
                if (account.SmtpAddress == _store.DisplayName)
                {
                    _userAccount = account;
                }
            }

            if (null == _userAccount)
            {
                throw new System.Exception(string.Format("No Account with SmtpAddress: {0} exists!", _store.DisplayName));
            }
        }
        public MailStoreProviderOM(string mailboxName, bool disableOutlookPrompt)
        {
            _disableOutlookPrompt = disableOutlookPrompt;

            if (_disableOutlookPrompt)
            {
                ConfigOutlookPrompts(false);
            }

            ConnectToOutlook();

            if (mailboxName != null)
            {
                mailboxName = mailboxName.ToLower();
                _store = AllMailStores().FirstOrDefault(x => x.DisplayName.ToLower() == mailboxName);

                if (_store == null)
                {
                    throw new ArgumentException(string.Format("Cannot find store (mailbox) {0} in default profile", mailboxName));
                }
            }
            else
            {
                _store = _outlook.Session.DefaultStore;
            }

            _userAccount = FindUserAccount();
            _rootFolder = new Lazy<IMailFolder>(GetRootFolder);
        }
Example #4
0
        public MailStoreProviderOM(string mailboxName, bool disableOutlookPrompt)
        {
            _disableOutlookPrompt = disableOutlookPrompt;

            if (_disableOutlookPrompt)
            {
                ConfigOutlookPrompts(false);
            }

            ConnectToOutlook();

            if (mailboxName != null)
            {
                mailboxName = mailboxName.ToLower();
                _store      = AllMailStores().FirstOrDefault(x => x.DisplayName.ToLower() == mailboxName);

                if (_store == null)
                {
                    throw new ArgumentException(string.Format("Cannot find store (mailbox) {0} in default profile", mailboxName));
                }
            }
            else
            {
                _store = _outlook.Session.DefaultStore;
            }

            _userAccount = FindUserAccount();
            _rootFolder  = new Lazy <IMailFolder>(GetRootFolder);
        }
 // Retrieves the email address for a given account object
 static string EnumerateAccountEmailAddress(Outlook.Account account)
 {
     try
     {
         if (string.IsNullOrEmpty(account.SmtpAddress) || string.IsNullOrEmpty(account.UserName))
         {
             Outlook.AddressEntry oAE = account.CurrentUser.AddressEntry as Outlook.AddressEntry;
             if (oAE.Type == "EX")
             {
                 Outlook.ExchangeUser oEU = oAE.GetExchangeUser() as Outlook.ExchangeUser;
                 return(oEU.PrimarySmtpAddress);
             }
             else
             {
                 return(oAE.Address);
             }
         }
         else
         {
             return(account.SmtpAddress);
         }
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex.Message);
         return("");
     }
 }
Example #6
0
 public string laydiachimail(Outlook.Account account)
 {
     try
     {
         if (string.IsNullOrEmpty(account.SmtpAddress) || string.IsNullOrEmpty(account.UserName))
         {
             Outlook.AddressEntry oAE = account.CurrentUser.AddressEntry as Outlook.AddressEntry;
             if (oAE.Type == "EX")
             {
                 Outlook.ExchangeUser oEU = oAE.GetExchangeUser() as Outlook.ExchangeUser;
                 return(oEU.PrimarySmtpAddress);
             }
             else
             {
                 return(oAE.Address);
             }
         }
         else
         {
             return(account.SmtpAddress);
         }
     }
     catch (Exception ex)
     {
         ghiloi.WriteLogError(ex);
         return("");
     }
 }
        private void button6_Click(object sender, EventArgs e)
        {
            //selected send
            String outlookAccString = (String)comboBoxOutlookAcc.SelectedItem;

            Outlook.Account acc = (Outlook.Account)outlookAccs[outlookAccString];
            mailHandler.sendSelectedMails(listBox1.SelectedItems, acc);
        }
 private void sendMail(string autoReplyResponse)
 {
     //string mailsent="false";
     try
     {
         if (autoReplyResponse != null)
         {
             var AutoReplied   = JObject.Parse(autoReplyResponse);
             var isAutoReplied = AutoReplied["auto_reply_status"];
             if (isAutoReplied.ToString() == "true")
             {
                 //create a new mail and  send
                 Outlook.MailItem mailItem = (Outlook.MailItem)Globals.ThisAddIn.Application.CreateItem(Outlook.OlItemType.olMailItem);
                 mailItem.Subject  = AutoReplied["replySubject"].ToString();
                 mailItem.To       = AutoReplied["from"].ToString();
                 mailItem.HTMLBody = AutoReplied["replyText"].ToString();
                 //var attachmentData = AutoReplied["attachments"];
                 List <Attachment> attachments = JsonConvert.DeserializeObject <List <Attachment> >(AutoReplied["attachments"].ToString());
                 //create attachments
                 foreach (Attachment item in attachments)
                 {
                     string fPath = WebRequestHelper.SaveByteDataAsFile(item.data, item.fileName);
                     mailItem.Attachments.Add(fPath, Outlook.OlAttachmentType.olByValue, 1, item.fileName);
                 }
                 mailItem.Display(false);
                 Outlook.Accounts accounts = Globals.ThisAddIn.Application.Session.Accounts;
                 Outlook.Account  acc      = null;
                 var sFromAddress          = Globals.ThisAddIn.myCredentials.EmailID;
                 //Look for our account in the Outlook
                 foreach (Outlook.Account account in accounts)
                 {
                     if (account.SmtpAddress.Equals(sFromAddress, StringComparison.CurrentCultureIgnoreCase))
                     {
                         //Use it
                         acc = account;
                         break;
                     }
                 }
                 if (acc != null)
                 {
                     //Use this account to send the e-mail.
                     mailItem.SendUsingAccount = acc;
                     mailItem.Send();
                 }
                 else
                 {
                     throw new Exception("Account does not exist in Outlook: " + sFromAddress);
                 }
             }
         }
     }
     catch (Exception ex)
     {
         MessageBox.Show("Exception Occured in Send Mail Method. " + ex.Message + "\n" + ex.StackTrace.ToString());
     }
 }
Example #9
0
        public void OpenInOutlook()
        {
            OutlookApp app = new OutlookApp();

            Outlook.MailItem mailitem = app.CreateItem(Outlook.OlItemType.olMailItem);
            mailitem.Subject              = this.subject;
            mailitem.HTMLBody             = this.body;
            mailitem.To                   = this.to;
            mailitem.CC                   = this.cc;
            mailitem.BCC                  = this.bcc;
            mailitem.ReadReceiptRequested = this.readreceipt == "Yes" ? true : false;

            switch (importance)
            {
            case "High":
                mailitem.Importance = Outlook.OlImportance.olImportanceHigh;
                break;

            case "Low":
                mailitem.Importance = Outlook.OlImportance.olImportanceLow;
                break;

            default:
                mailitem.Importance = Outlook.OlImportance.olImportanceNormal;
                break;
            }

            switch (votingoptions)
            {
            case "Accept.Reject":
                mailitem.VotingOptions = "Accept; Reject;";
                break;

            case "Yes.No":
                mailitem.VotingOptions = "Yes; No;";
                break;

            default:
                Logger.Log("No voting options selected");
                break;
            }

            if (!string.IsNullOrEmpty(this.from))
            {
                Outlook.Account account = app.Session.Accounts[this.from];

                if (account != null)
                {
                    mailitem.SendUsingAccount = account;
                }
            }

            mailitem.Display();
        }
Example #10
0
        unsafe public void SetAccountProp(PropTag propTag, object value)
        {
            // Use IOlkAccount to notify while we're running
            // IOlkAccount can only be accessed on main thread
            Logger.Instance.Trace(this, "SetAccountProp1: {0}: {1}", propTag, value);
            ThisAddIn.Instance.InUI(() =>
            {
                Logger.Instance.Trace(this, "SetAccountProp2: {0}: {1}", propTag, value);
                using (ComRelease com = new ComRelease())
                {
                    Logger.Instance.Trace(this, "SetAccountProp3: {0}: {1}", propTag, value);
                    NSOutlook.Account account = com.Add(FindAccountObject());
                    IOlkAccount olk           = com.Add(account.IOlkAccount);
                    Logger.Instance.Trace(this, "SetAccountProp4: {0}: {1}", propTag, value);

                    switch (propTag.type)
                    {
                    case PropType.UNICODE:
                        Logger.Instance.Trace(this, "SetAccountProp5: {0}: {1}", propTag, value);
                        using (MapiAlloc mem = MapiAlloc.FromString((string)value))
                        {
                            ACCT_VARIANT val = new ACCT_VARIANT()
                            {
                                dwType = (uint)PropType.UNICODE,
                                lpszW  = (char *)mem.Ptr
                            };
                            Logger.Instance.Trace(this, "SetAccountProp5A: {0}: {1}", propTag, value);
                            olk.SetProp(propTag, &val);
                            Logger.Instance.Trace(this, "SetAccountProp6: {0}: {1}", propTag, value);
                            olk.SaveChanges(0);
                            Logger.Instance.Trace(this, "SetAccountProp7: {0}: {1}", propTag, value);
                        }
                        break;

                    case PropType.LONG:
                        {
                            Logger.Instance.Trace(this, "SetAccountProp8: {0}: {1}", propTag, value);
                            ACCT_VARIANT val = new ACCT_VARIANT()
                            {
                                dwType = (uint)PropType.LONG,
                                dw     = (uint)value
                            };
                            olk.SetProp(propTag, &val);
                            Logger.Instance.Trace(this, "SetAccountProp9: {0}: {1}", propTag, value);
                            olk.SaveChanges(0);
                            Logger.Instance.Trace(this, "SetAccountPropA: {0}: {1}", propTag, value);
                            break;
                        }
                    }
                    Logger.Instance.Trace(this, "SetAccountPropDone: {0}: {1}", propTag, value);
                }
            }, true);
        }
Example #11
0
        public static void SendEmailFromAccount(Outlook.Application application, string subject, string body, string to, string smtpAddress)
        {
            // Create a new MailItem and set the To, Subject, and Body properties.
            Outlook.MailItem newMail = (Outlook.MailItem)application.CreateItem(Outlook.OlItemType.olMailItem);
            newMail.To      = to;
            newMail.Subject = subject;
            newMail.Body    = body;

            // Retrieve the account that has the specific SMTP address.
            Outlook.Account account = GetAccountForEmailAddress(application, smtpAddress);
            // Use this account to send the email.
            newMail.SendUsingAccount = account;
            newMail.Send();
        }
        public void LoadSettings(Outlook.Account outlookAccount, EmailAccountsArchiveSettings settings)
        {
            var store = outlookAccount.DeliveryStore;

            _outlookStoreId = store.StoreID;
            var rootFolder  = store.GetRootFolder();
            var smtpAddress = outlookAccount.SmtpAddress;

            ArchiveInboundCheckbox.Text  = $"Archive Mail Received by {smtpAddress}";
            ArchiveOutboundCheckbox.Text = $"Archive Mail Sent by {smtpAddress}";

            GetMailFolders(settings, rootFolder.Folders);
            ArchiveInboundCheckbox.Checked  = settings.AccountsToArchiveInbound.Contains(_outlookStoreId);
            ArchiveOutboundCheckbox.Checked = settings.AccountsToArchiveOutbound.Contains(_outlookStoreId);
        }
        private static string GetSenderSmtpAddress(Outlook.MeetingItem item)
        {
            Outlook.Account account = null;

            try
            {
                account = item.SendUsingAccount;
                return(account.SmtpAddress);
            }
            finally
            {
                if (account != null)
                {
                    Marshal.ReleaseComObject(account);
                }
            }
        }
Example #14
0
        public static void SendEmailFromAccount(Outlook.Application application, string subject, List <string> to, string body, string smtpAddress, string attachment)
        {
            // Create a new MailItem and set the To, Subject, and Body properties.
            Outlook.MailItem newMail = (Outlook.MailItem)application.CreateItem(Outlook.OlItemType.olMailItem);
            string           toStr   = to.Aggregate <string, string>(null, (current, rec) => current + rec + ";");

            newMail.To      = toStr;
            newMail.Subject = subject;
            newMail.Body    = body;
            newMail.Attachments.Add(attachment, Outlook.OlAttachmentType.olByValue, Type.Missing, Type.Missing);

            // Retrieve the account that has the specific SMTP address.
            Outlook.Account account = GetAccountForEmailAddress(application, smtpAddress);
            // Use this account to send the e-mail.
            newMail.SendUsingAccount = account;
            newMail.Send();
        }
Example #15
0
        public string GetSenderAddress(Outlook.MailItem mail)
        {
            if (mail == null)
            {
                return("");
            }

            if ((mail.SenderEmailType != "EX"))
            {
                return(mail.SenderEmailAddress);
            }
            Outlook.Account acc = mail.SendUsingAccount;
            if (acc == null) // use first account
            {
                Outlook.Accounts accounts = mail.GetInspector.Session.Accounts;
                acc = accounts[0];
            }
            return(acc.SmtpAddress);
        }
Example #16
0
        //отправляем каждому необходимые работы
        void SendEmails()
        {
            string prform_path;

            for (int i = 0; i < peers.Count; i++)
            {
                for (int j = 0; j < peers[i].new_guids.Count; j++)
                {
                    prform_path = session.Folder_path + @"\Review " + peers[i].guids_ID[j] + ".xlsm";
                    File.Copy(@"..\..\..\PATemplate_Example.xlsm", prform_path);
                    Excel.Application xlApp = new Excel.Application();
                    Excel.Workbook    Book  = xlApp.Workbooks.Open(prform_path);
                    Excel.Worksheet   Sheet = Book.Sheets[1];
                    Sheet.Cells[1, 2] = peers[i].prform_IDs[j];
                    Book.Close(true);
                    xlApp.Quit();
                    Book  = null;
                    Sheet = null;
                    Microsoft.Office.Interop.Outlook._Application _app = new Microsoft.Office.Interop.Outlook.Application();
                    Microsoft.Office.Interop.Outlook.MailItem     mail = (Microsoft.Office.Interop.Outlook.MailItem)_app.CreateItem(Microsoft.Office.Interop.Outlook.OlItemType.olMailItem);
                    mail.To      = peers[i].email;
                    mail.Subject = peers[i].prform_IDs[j] + " review for " + session.TaskTitle + peers[i].new_guids[j];
                    mail.Body    = "Hello!"
                                   + "\n" + "\t" + "Please see attached files." + "\n" + "Reply to this message with attached complete PR form (" + peers[i].prform_IDs[j] + ".xlsm) only."
                                   + "\n" + "Deadline for reviews is " + session.Review_End + "."
                                   + "\n\t" + "Truly yours, Peer Review Robot.";
                    mail.Attachments.Add(prform_path);
                    mail.Attachments.Add(Directory.GetFiles(session.Folder_path, $"{peers[i].new_guids[j]}*")[0]);
                    mail.Importance = Microsoft.Office.Interop.Outlook.OlImportance.olImportanceNormal;
                    Outlook.Account account = GetOutlookAccount(_app, session.OutlookAccount);
                    mail.SendUsingAccount = account;
                    mail.Send();
                    _app.Quit();
                    _app = null;
                    mail = null;
                    File.Delete(prform_path);
                }
            }
        }
        public void sendSelectedMails(ListBox.SelectedObjectCollection mailAdresses, Outlook.Account acc)
        {
            Hashtable errorsTable  = new Hashtable();
            String    errorMessage = String.Empty;

            foreach (Outlook.MailItem mail in mailList)
            {
                try
                {
                    if (mailAdresses.Contains((String)mail.To))
                    {
                        mail.SendUsingAccount = acc;
                        mail.Send();
                    }
                }catch (Exception ex)
                {
                    if (mailItem != null && !errorsTable.ContainsKey(mailItem.To))
                    {
                        errorsTable.Add(mailItem.To, ex.Message);
                    }
                }
            }
            if (errorsTable.Count > 0)
            {
                foreach (string key in errorsTable.Keys)
                {
                    errorMessage += key + ":\t" + errorsTable[key] + "\n";
                }
            }
            if (errorMessage.Length > 0)
            {
                MessageBox.Show(errorMessage, "Error occured while sending messages", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            {
                MessageBox.Show("Messages sent", "Messages sent", MessageBoxButtons.OK);
            }
        }
Example #18
0
        static void EnumerateAccounts()//checks the number of accounts configured. In our case, there is only one account configured.
        {
            Outlook.Account     primaryAccount = null;
            Outlook.Application Application    = new Outlook.Application();
            Outlook.Accounts    accounts       = Application.Session.Accounts;
            foreach (Outlook.Account account in accounts)
            {
                primaryAccount = account;
                break;
            }

            /* foreach (Outlook.Account account in accounts)     //this loop must be used if there are more than one accounts configured in the system. Replace "Gaurav" with the a word that is contained in the email name.
             * {
             *   if (account.DisplayName.Contains("Gaurav"))
             *    {
             *   primaryAccount = account;
             *   break;
             *   }
             * }*/
            Outlook.Folder selectedFolder = Application.Session.DefaultStore.GetRootFolder() as Outlook.Folder;
            selectedFolder = getFolder(@"\\" + primaryAccount.DisplayName); //Fetches the inbox folder
            enumerateFolders(selectedFolder);                               //Iterates amongst the folders and selects the Inbox folder to retreive the attachment from the inbox
        }
        public void sendAll(Outlook.Account acc)
        {
            Hashtable errorsTable  = new Hashtable();
            String    errorMessage = String.Empty;

            foreach (Outlook.MailItem mailItem in MailList)
            {
                try
                {
                    mailItem.SendUsingAccount = acc;
                    //mailItem.SenderEmailAddress=acc.
                    mailItem.Send();
                }
                catch (Exception ex)
                {
                    if (!errorsTable.ContainsKey(mailItem.To))
                    {
                        errorsTable.Add(mailItem.To, ex.Message);
                    }
                }
            }
            if (errorsTable.Count > 0)
            {
                foreach (string key in errorsTable.Keys)
                {
                    errorMessage += key + ":\t" + errorsTable[key] + "\n";
                }
            }
            if (errorMessage.Length > 0)
            {
                MessageBox.Show(errorMessage, "Error occured while sending messages", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            {
                MessageBox.Show("Message sent", "Messages sent", MessageBoxButtons.OK);
            }
        }
            public void sendOutlookMail(String ToAddress, String CC, String BCC, String Body, String Subject, String FromAddress, Boolean isHTML, String[] arrAttachment)
            {
                try
                {
                    Outlook.Application OutlookApp = new Outlook.Application();
                    Outlook.MailItem    oNewMail   = (Outlook.MailItem)OutlookApp.CreateItem(Outlook.OlItemType.olMailItem);

                    //Adding To, Cc, BCC
                    AddReceipents(oNewMail, ToAddress, CC, BCC);

                    //Mail Type
                    if (isHTML)
                    {
                        oNewMail.HTMLBody = Body;
                    }
                    else
                    {
                        oNewMail.Body = Body;
                    }

                    if (arrAttachment != null)
                    {
                        Outlook.Attachment oAttach;
                        int iPosition   = (int)oNewMail.Body.Length + 1;
                        int iAttachType = (int)Outlook.OlAttachmentType.olByValue;

                        foreach (String attach in arrAttachment)
                        {
                            if (!String.IsNullOrWhiteSpace(attach))
                            {
                                oAttach = oNewMail.Attachments.Add(attach, iAttachType, iPosition);
                            }
                        }
                    }

                    oNewMail.Subject = Subject;

                    if (String.IsNullOrWhiteSpace(FromAddress))
                    {
                    }
                    else
                    {
                        Outlook.Accounts AllAccount  = OutlookApp.Session.Accounts;
                        Outlook.Account  SendAccount = null;

                        foreach (Outlook.Account account in AllAccount)
                        {
                            if (account.SmtpAddress.Equals(FromAddress, StringComparison.CurrentCultureIgnoreCase))
                            {
                                SendAccount = account;
                                break;
                            }
                        }
                        if (SendAccount != null)
                        {
                            oNewMail.SendUsingAccount = SendAccount;
                        }
                        else
                        {
                            throw new Exception("Account does not exist in Outlook : " + FromAddress);
                        }
                    }
                    oNewMail.Send();
                    oNewMail   = null;
                    OutlookApp = null;
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
Example #21
0
        protected bool InviaMail(string nomeFoglio, object siglaEntita, Range rng)
        {
            List <string> attachments   = new List <string>();
            bool          hasVariations = false;

            try
            {
                Excel.Worksheet ws = Globals.ThisWorkbook.Sheets[nomeFoglio];

                //inizializzo l'oggetto mail
                Outlook.Application outlook = GetOutlookInstance();
                Outlook._MailItem   mail    = outlook.CreateItem(Outlook.OlItemType.olMailItem);

                DataView entitaProprieta = Workbook.Repository[DataBase.TAB.ENTITA_PROPRIETA].DefaultView;
                entitaProprieta.RowFilter = "SiglaEntita = '" + siglaEntita + "' AND SiglaProprieta = 'INVIO_PROGRAMMA_ALLEGATO_EXCEL' AND IdApplicazione = " + Workbook.IdApplicazione;
                if (entitaProprieta.Count > 0)
                {
                    //creo file Excel da allegare
                    string excelExport = Path.Combine(@"C:\Emergenza", Workbook.DataAttiva.ToString("yyyyMMdd") + "_" + entitaProprieta[0]["Valore"] + "_" + Workbook.Mercato + ".xls");
                    attachments.Add(excelExport);

                    hasVariations = CreaOutputXLS(ws, attachments.Last(), siglaEntita.Equals("CE_ORX"), rng);

                    //25/01/2017 ENH: path export da file di configurazione
                    var cfgPath = Workbook.GetUsrConfigElement("pathExportFileRosone");

                    //18/01/2017 FIX: inizializzazione fuori dall'if: provocava errore invio mail
                    string pathExport            = PreparePath(cfgPath);
                    string fileNameXML           = null;
                    string fileNameCSV           = null;
                    string pathXmlOrcoExportFull = null;
                    if (siglaEntita.Equals("CE_ORX"))
                    {
                        if (!Directory.Exists(pathExport))
                        {
                            Directory.CreateDirectory(pathExport);
                        }

                        fileNameXML = fileNameCSV = "FMS_UP_ORCO_1_" + Workbook.Mercato + "D_" + Workbook.DataAttiva.ToString("yyyyMMdd");

                        fileNameXML          += ".xml.OEIESRD.out.xml";
                        fileNameCSV          += ".csv.OEIESRD.out.csv";
                        pathXmlOrcoExportFull = pathExport + "\\" + fileNameXML;

                        bool xmlCreated = CreaOutputXML(siglaEntita, pathExport, fileNameXML, Workbook.DataAttiva);
                        bool csvCreated = CreaOutputCSV(siglaEntita, pathExport, fileNameCSV, Workbook.DataAttiva);

                        attachments.Add(Path.Combine(pathXmlOrcoExportFull));
                    }

                    DataView categoriaEntita = Workbook.Repository[DataBase.TAB.CATEGORIA_ENTITA].DefaultView;
                    categoriaEntita.RowFilter = "Gerarchia = '" + siglaEntita + "' AND IdApplicazione = " + Workbook.IdApplicazione;

                    if (categoriaEntita.Count == 0)
                    {
                        categoriaEntita.RowFilter = "SiglaEntita = '" + siglaEntita + "' AND IdApplicazione = " + Workbook.IdApplicazione;
                    }

                    bool interrupt = false;

                    foreach (DataRowView entita in categoriaEntita)
                    {
                        entitaProprieta.RowFilter = "SiglaEntita = '" + entita["SiglaEntita"] + "' AND SiglaProprieta = 'INVIO_PROGRAMMA_ALLEGATO_FMS' AND IdApplicazione = " + Workbook.IdApplicazione;
                        if (entitaProprieta.Count > 0)
                        {
                            //cerco i file XML
                            string nomeFileFMS = PrepareName(Workbook.GetUsrConfigElement("formatoNomeFileFMS").Value, codRup: entita["CodiceRup"].ToString()) + "*.xml";
                            string pathFileFMS = PreparePath(Workbook.GetUsrConfigElement("pathExportFileFMS"));

                            string[] files = Directory.GetFiles(pathFileFMS, nomeFileFMS, SearchOption.TopDirectoryOnly);

                            if (files.Length == 0)
                            {
                                if (!Workbook.DaConsole && System.Windows.Forms.MessageBox.Show("File FMS non presente nell'area di rete. Continuare con l'invio?", Simboli.NomeApplicazione + " - ATTENZIONE!!!", System.Windows.Forms.MessageBoxButtons.YesNo, System.Windows.Forms.MessageBoxIcon.Warning) == System.Windows.Forms.DialogResult.No)
                                {
                                    interrupt = true;
                                    break;
                                }
                            }
                            foreach (string file in files)
                            {
                                attachments.Add(file);
                                //18/01/2017 FIX: non più utile per cambio requisiti
                                //File.Copy(file, Path.Combine(pathExport, file.Split('\\').Last()));
                            }
                        }
                        entitaProprieta.RowFilter = "SiglaEntita = '" + entita["SiglaEntita"] + "' AND SiglaProprieta = 'INVIO_PROGRAMMA_ALLEGATO_RS' AND IdApplicazione = " + Workbook.IdApplicazione;
                        if (entitaProprieta.Count > 0)
                        {
                            string nomeFileFMS = PrepareName(Workbook.GetUsrConfigElement("formatoNomeFileRS_TERNA").Value) + ".xml";
                            string pathFileFMS = PreparePath(Workbook.GetUsrConfigElement("pathExportFileRS"));

                            string[] files = Directory.GetFiles(pathFileFMS, nomeFileFMS, SearchOption.TopDirectoryOnly);

                            if (files.Length == 0)
                            {
                                if (!Workbook.DaConsole && System.Windows.Forms.MessageBox.Show("File Riserva Secondaria non presente nell'area di rete. Continuare con l'invio?", Simboli.NomeApplicazione + " - ATTENZIONE!!!", System.Windows.Forms.MessageBoxButtons.YesNo, System.Windows.Forms.MessageBoxIcon.Warning) == System.Windows.Forms.DialogResult.No)
                                {
                                    interrupt = true;
                                    break;
                                }
                            }

                            foreach (string file in files)
                            {
                                attachments.Add(file);
                                //18/01/2017 FIX: non più utile per cambio requisiti
                                //File.Copy(file, Path.Combine(pathExport, file.Split('\\').Last()));
                            }
                        }
                    }

                    if (!interrupt)
                    {
                        var    config = Workbook.GetUsrConfigElement("destMailTest");
                        string mailTo = config.Test;
                        string mailCC = "";

                        if (Workbook.Ambiente == Simboli.PROD)
                        {
                            entitaProprieta.RowFilter = "SiglaEntita = '" + siglaEntita + "' AND SiglaProprieta = 'INVIO_PROGRAMMA_MAIL_TO' AND IdApplicazione = " + Workbook.IdApplicazione;
                            mailTo = entitaProprieta[0]["Valore"].ToString();
                            entitaProprieta.RowFilter = "SiglaEntita = '" + siglaEntita + "' AND SiglaProprieta = 'INVIO_PROGRAMMA_MAIL_CC' AND IdApplicazione = " + Workbook.IdApplicazione;
                            mailCC = entitaProprieta[0]["Valore"].ToString();
                        }

                        entitaProprieta.RowFilter = "SiglaEntita = '" + siglaEntita + "' AND SiglaProprieta = 'INVIO_PROGRAMMA_CODICE_MAIL' AND IdApplicazione = " + Workbook.IdApplicazione;
                        string codUP = entitaProprieta[0]["Valore"].ToString();

                        config = Workbook.GetUsrConfigElement("oggettoMail");
                        string oggetto = config.Value.Replace("%COD%", codUP).Replace("%DATA%", Workbook.DataAttiva.ToString("dd-MM-yyyy")).Replace("%MSD%", Workbook.Mercato) + (hasVariations ? " - CON VARIAZIONI" : "");
                        config = Workbook.GetUsrConfigElement("messaggioMail");
                        string messaggio = config.Value;

                        messaggio = Regex.Replace(messaggio, @"^[^\S\r\n]+", "", RegexOptions.Multiline);

                        //TODO check se manda sempre con lo stesso account...
                        Outlook.Account senderAccount = outlook.Session.Accounts[1];
                        foreach (Outlook.Account account in outlook.Session.Accounts)
                        {
                            if (account.DisplayName == "Bidding")
                            {
                                senderAccount = account;
                            }
                        }
                        mail.SendUsingAccount = senderAccount;
                        mail.Subject          = oggetto;
                        mail.Body             = messaggio;
                        foreach (string dest in mailTo.Split(';'))
                        {
                            if (dest.Trim() != "")
                            {
                                mail.Recipients.Add(dest.Trim());
                            }
                        }
                        mail.CC = mailCC;

                        //aggiungo allegato XLS
                        foreach (string attachment in attachments)
                        {
                            mail.Attachments.Add(attachment);
                        }

                        mail.Send();
                    }
                    File.Delete(excelExport);
                    if (pathXmlOrcoExportFull != null)
                    {
                        //proviamo a lasciare il file come da richiesta!
                        //File.Delete(pathXmlOrcoExportFull);
                    }

                    return(!interrupt);
                }
            }
            catch (Exception e)
            {
                Workbook.InsertLog(Core.DataBase.TipologiaLOG.LogErrore, "InvioProgrammi - Esporta.InvioMail: " + e.Message);
                System.Windows.Forms.MessageBox.Show(e.Message, Simboli.NomeApplicazione + " - ERRORE!!", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);

                foreach (string file in attachments)
                {
                    File.Delete(file);
                }

                return(false);
            }

            return(false);
        }
Example #22
0
    public bool sendEmailViaOutlook(string sFromAddress, string sToAddress, string sCc, string sSubject, string sBody, List <string> arrAttachments = null, string sBcc = null)
    {
        //Send email via Office Outlook 2010
        //'sFromAddress' = email address sending from (ex: "*****@*****.**") -- this account must exist in Outlook. Only one email address is allowed!
        //'sToAddress' = email address sending to. Can be multiple. In that case separate with semicolons or commas. (ex: "*****@*****.**", or "[email protected]; [email protected]")
        //'sCc' = email address sending to as Carbon Copy option. Can be multiple. In that case separate with semicolons or commas. (ex: "*****@*****.**", or "[email protected]; [email protected]")
        //'sSubject' = email subject as plain text
        //'sBody' = email body. Type of data depends on 'bodyType'
        //'bodyType' = type of text in 'sBody': plain text, HTML or RTF
        //'arrAttachments' = if not null, must be a list of absolute file paths to attach to the email
        //'sBcc' = single email address to use as a Blind Carbon Copy, or null not to use
        //RETURN:
        //      = true if success
        if (sFromAddress == "" || sToAddress == "" || cfgUseUserEmail != "Y")
        {
            trace(string.Format("sFromAddress={0}, sToAddress={1}, Void Notify={2}", sFromAddress, sToAddress, cfgUseUserEmail));
            return(false);
        }
        bool bRes = false;

        try
        {
            //Get Outlook COM objects
            Outlook.Application app     = new Outlook.Application();
            Outlook.MailItem    newMail = (Outlook.MailItem)app.CreateItem(Outlook.OlItemType.olMailItem);

            //Parse 'sToAddress'
            if (!string.IsNullOrWhiteSpace(sToAddress))
            {
                string[] arrAddTos = sToAddress.Split(new char[] { ';', ',' });
                foreach (string strAddr in arrAddTos)
                {
                    if (!string.IsNullOrWhiteSpace(strAddr) &&
                        strAddr.IndexOf('@') != -1)
                    {
                        newMail.Recipients.Add(strAddr.Trim());
                    }
                    else
                    {
                        throw new Exception("Bad to-address: " + sToAddress);
                    }
                }
            }
            else
            {
                throw new Exception("Must specify to-address");
            }

            //Parse 'sCc'
            if (!string.IsNullOrWhiteSpace(sCc))
            {
                string[] arrAddTos = sCc.Split(new char[] { ';', ',' });
                foreach (string strAddr in arrAddTos)
                {
                    if (!string.IsNullOrWhiteSpace(strAddr) &&
                        strAddr.IndexOf('@') != -1)
                    {
                        newMail.Recipients.Add(strAddr.Trim());
                    }
                    else
                    {
                        throw new Exception("Bad CC-address: " + sCc);
                    }
                }
            }

            //Is BCC empty?
            if (!string.IsNullOrWhiteSpace(sBcc))
            {
                newMail.BCC = sBcc.Trim();
            }

            //Resolve all recepients
            if (!newMail.Recipients.ResolveAll())
            {
                throw new Exception("Failed to resolve all recipients: " + sToAddress + ";" + sCc);
            }


            newMail.Body = sBody;

            if (arrAttachments != null)
            {
                //Add attachments
                foreach (string strPath in arrAttachments)
                {
                    if (File.Exists(strPath))
                    {
                        newMail.Attachments.Add(strPath);
                    }
                    else
                    {
                        throw new Exception("Attachment file is not found: \"" + strPath + "\"");
                    }
                }
            }

            //Add subject
            if (!string.IsNullOrWhiteSpace(sSubject))
            {
                newMail.Subject = sSubject;
            }

            Outlook.Accounts accounts = app.Session.Accounts;
            Outlook.Account  acc      = null;

            //Look for our account in the Outlook
            foreach (Outlook.Account account in accounts)
            {
                if (account.SmtpAddress.Equals(sFromAddress, StringComparison.CurrentCultureIgnoreCase))
                {
                    //Use it
                    acc = account;
                    break;
                }
            }

            //Did we get the account
            if (acc != null)
            {
                //Use this account to send the e-mail.
                newMail.SendUsingAccount = acc;

                //And send it
                ((Outlook._MailItem)newMail).Send();

                //Done
                bRes = true;
            }
            else
            {
                throw new Exception("Account does not exist in Outlook: " + sFromAddress);
            }
        }
        catch (Exception ex)
        {
            errorLog("ERROR: Failed to send mail: " + ex.Message);
        }

        return(bRes);
    }
Example #23
0
        protected bool InviaMail(DefinedNames definedNames, object siglaEntita)
        {
            string fileNameFull = "";
            string fileName     = "";

            try
            {
                fileName     = @"PrevisioneGAS_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls";
                fileNameFull = Environment.ExpandEnvironmentVariables(@"%TEMP%\" + fileName);

                Excel.Workbook wb = Globals.ThisWorkbook.Application.Workbooks.Add();

                Workbook.Main.Range[Range.GetRange(definedNames.GetFirstRow(), definedNames.GetFirstCol(), definedNames.GetRowOffset(), definedNames.GetColOffsetRiepilogo()).ToString()].Copy();
                wb.Sheets[1].Range["B2"].PasteSpecial();

                wb.Sheets[1].UsedRange.ColumnWidth = 17;
                wb.Sheets[1].Range["A1"].Select();
                wb.SaveAs(fileNameFull, Excel.XlFileFormat.xlExcel8);
                wb.Close();
                Marshal.ReleaseComObject(wb);

                var    config = Workbook.GetUsrConfigElement("destMailTest");
                string mailTo = config.Test;
                string mailCC = "";

                DataView entitaProprieta = new DataView(Workbook.Repository[DataBase.TAB.ENTITA_PROPRIETA]);

                if (Workbook.Ambiente == Simboli.PROD)
                {
                    entitaProprieta.RowFilter = "SiglaEntita = '" + siglaEntita + "' AND SiglaProprieta = 'PREV_CONSUMO_GAS_MAIL_TO' AND IdApplicazione = " + Workbook.IdApplicazione;

                    if (entitaProprieta.Count > 0)
                    {
                        mailTo = entitaProprieta[0]["Valore"].ToString();
                    }

                    entitaProprieta.RowFilter = "SiglaEntita = '" + siglaEntita + "' AND SiglaProprieta = 'PREV_CONSUMO_GAS_MAIL_CC' AND IdApplicazione = " + Workbook.IdApplicazione;

                    if (entitaProprieta.Count > 0)
                    {
                        mailCC = entitaProprieta[0]["Valore"].ToString();
                    }
                }
                if (DataBase.OpenConnection())
                {
                    Outlook.Application outlook = GetOutlookInstance();
                    Outlook._MailItem   mail    = outlook.CreateItem(Outlook.OlItemType.olMailItem);

                    config = Workbook.GetUsrConfigElement("oggettoMail");
                    string oggetto = config.Value.Replace("%DATA%", DateTime.Now.ToString("dd-MM-yyyy")).Replace("%ORA%", DateTime.Now.ToString("HH:mm"));
                    config = Workbook.GetUsrConfigElement("messaggioMail");
                    string messaggio = config.Value.Replace("%NOMEUTENTE%", Workbook.NomeUtente);
                    messaggio = Regex.Replace(messaggio, @"^[^\S\r\n]+", "", RegexOptions.Multiline);


                    ////TODO check se manda sempre con lo stesso account...
                    Outlook.Account senderAccount = outlook.Session.Accounts[1];
                    foreach (Outlook.Account account in outlook.Session.Accounts)
                    {
                        if (account.DisplayName == "Bidding")
                        {
                            senderAccount = account;
                        }
                    }
                    mail.SendUsingAccount = senderAccount;
                    mail.Subject          = oggetto;
                    mail.Body             = messaggio;
                    foreach (string dest in mailTo.Split(';'))
                    {
                        if (dest.Trim() != "")
                        {
                            mail.Recipients.Add(dest.Trim());
                        }
                    }
                    mail.CC = mailCC;
                    mail.Attachments.Add(fileNameFull);

                    mail.Send();

                    File.Delete(fileNameFull);
                }
                else
                {
                    string emailFolder = @"C:\Emergenza\Email\" + Simboli.NomeApplicazione;

                    if (!Directory.Exists(emailFolder))
                    {
                        Directory.CreateDirectory(emailFolder);
                    }

                    File.Move(fileNameFull, Path.Combine(emailFolder, fileName));
                }
            }
            catch (Exception e)
            {
                Workbook.InsertLog(Core.DataBase.TipologiaLOG.LogErrore, "PrevisioneGAS.Esporta.InvioMail: " + e.Message);

                System.Windows.Forms.MessageBox.Show(e.Message, Simboli.NomeApplicazione + " - ERRORE!!", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);

                if (File.Exists(fileName))
                {
                    File.Delete(fileName);
                }

                return(false);
            }

            return(true);
        }
Example #24
0
        protected bool InviaMail(string nomeFoglio, object siglaEntita, List <Range> export)
        {
            string fileNameFull = "";
            string fileName     = "";

            try
            {
                Excel.Worksheet ws = Globals.ThisWorkbook.Sheets[nomeFoglio];

                DataView entitaProprieta = Workbook.Repository[DataBase.TAB.ENTITA_PROPRIETA].DefaultView;
                entitaProprieta.RowFilter = "SiglaEntita = '" + siglaEntita + "' AND SiglaProprieta = 'SISTEMA_COMANDI_ALLEGATO_EXCEL' AND IdApplicazione = " + Workbook.IdApplicazione;
                if (entitaProprieta.Count > 0)
                {
                    fileName     = entitaProprieta[0]["Valore"] + "_VDT_" + Workbook.DataAttiva.ToString("yyyyMMdd") + ".xls";
                    fileNameFull = Environment.ExpandEnvironmentVariables(@"%TEMP%\" + fileName);
                    //fileName = @"D:\" + entitaProprieta[0]["Valore"] + "_VDT_" + Workbook.DataAttiva.ToString("yyyyMMdd") + ".xls";

                    Excel.Workbook wb = Globals.ThisWorkbook.Application.Workbooks.Add();
                    int            i  = 2;
                    foreach (Range rng in export)
                    {
                        ws.Range[rng.ToString()].Copy();
                        wb.Sheets[1].Range["B" + i++].PasteSpecial();
                    }
                    wb.Sheets[1].Columns["B:C"].EntireColumn.AutoFit();
                    wb.Sheets[1].Range["A1"].Select();
                    wb.SaveAs(fileNameFull, Excel.XlFileFormat.xlExcel12);
                    wb.Close();
                    Marshal.ReleaseComObject(wb);

                    var    config = Workbook.GetUsrConfigElement("destMailTest");
                    string mailTo = config.Test;
                    string mailCC = "";

                    if (Workbook.Ambiente == Simboli.PROD)
                    {
                        entitaProprieta.RowFilter = "SiglaEntita = '" + siglaEntita + "' AND SiglaProprieta = 'SISTEMA_COMANDI_MAIL_TO' AND IdApplicazione = " + Workbook.IdApplicazione;
                        mailTo = entitaProprieta[0]["Valore"].ToString();
                        entitaProprieta.RowFilter = "SiglaEntita = '" + siglaEntita + "' AND SiglaProprieta = 'SISTEMA_COMANDI_MAIL_CC' AND IdApplicazione = " + Workbook.IdApplicazione;
                        mailCC = entitaProprieta[0]["Valore"].ToString();
                    }

                    entitaProprieta.RowFilter = "SiglaEntita = '" + siglaEntita + "' AND SiglaProprieta = 'SISTEMA_COMANDI_CODICE_MAIL' AND IdApplicazione = " + Workbook.IdApplicazione;
                    string codUP = entitaProprieta[0]["Valore"].ToString();

                    config = Workbook.GetUsrConfigElement("oggettoMail");
                    string oggetto = config.Value.Replace("%COD%", codUP).Replace("%DATA%", Workbook.DataAttiva.ToString("dd-MM-yyyy"));
                    config = Workbook.GetUsrConfigElement("messaggioMail");
                    string messaggio = config.Value;
                    messaggio = Regex.Replace(messaggio, @"^[^\S\r\n]+", "", RegexOptions.Multiline);

                    if (DataBase.OpenConnection())
                    {
                        Outlook.Application outlook = GetOutlookInstance();
                        Outlook._MailItem   mail    = outlook.CreateItem(Outlook.OlItemType.olMailItem);

                        //TODO check se manda sempre con lo stesso account...
                        Outlook.Account senderAccount = outlook.Session.Accounts[1];
                        foreach (Outlook.Account account in outlook.Session.Accounts)
                        {
                            if (account.DisplayName == "Bidding")
                            {
                                senderAccount = account;
                            }
                        }
                        mail.SendUsingAccount = senderAccount;
                        mail.Subject          = oggetto;
                        mail.Body             = messaggio;
                        foreach (string dest in mailTo.Split(';'))
                        {
                            if (dest.Trim() != "")
                            {
                                mail.Recipients.Add(dest.Trim());
                            }
                        }
                        mail.CC = mailCC;
                        mail.Attachments.Add(fileNameFull);

                        mail.Send();

                        File.Delete(fileNameFull);
                    }
                    else
                    {
                        string emailFolder = @"C:\Emergenza\Email\" + Simboli.NomeApplicazione;

                        if (!Directory.Exists(emailFolder))
                        {
                            Directory.CreateDirectory(emailFolder);
                        }

                        File.Move(fileNameFull, Path.Combine(emailFolder, fileName));
                    }
                }
            }
            catch (Exception e)
            {
                Workbook.InsertLog(Core.DataBase.TipologiaLOG.LogErrore, "SistemaComandi.Esporta.InvioMail [" + siglaEntita + "]: " + e.Message);

                System.Windows.Forms.MessageBox.Show(e.Message, Simboli.NomeApplicazione + " - ERRORE!!", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);

                if (File.Exists(fileNameFull))
                {
                    File.Delete(fileNameFull);
                }

                return(false);
            }

            return(true);
        }
        public List <string> SendEmail(string EmailAddress, string Profile, string LogPath, string LogData, string SendEmail, string[] EmailTo = null, string[] EmailCC = null, string[] EmailBCC = null, string[] Subject = null, string[] Body = null, string[] IsReadReceiptRequested = null, string[] IsDeliveryReceiptRequested = null, string[] EmailAttachments = null, string[] HighEmailImportance = null, string[] EmailEmbedImagePath = null, string[] EmailEmbedImigeFileName = null)
        {
            NameSpace     nameSpace = null;
            List <string> results   = new List <string>();

            Outlook.Folder     outboxFolder = null;
            Outlook.MAPIFolder oFolder;
            try
            {
                if (LogPath == "")
                {
                    results.Add("Failed: Missing log path");
                    return(results);
                }
                //MessageBox.Show(box);
                //box = EmailTo[0];
                //MessageBox.Show(box);
                //box = "|" + EmailEmbedImagePath[0] + "|";
                //MessageBox.Show(box);
                //box = "|" + EmailEmbedImigeFileName[0] + "|";
                //MessageBox.Show(box);

                string log = "";
                log = "Started";
                File.AppendAllText(LogPath, LogData + log + Environment.NewLine);
                string EmailToItem  = "";
                string EmailCCItem  = "";
                string EmailBCCItem = "";

                List <string> Attachments = new List <string>();
                int           i           = 0;
                //Establishing connection to the Outlook
                Connection conn = new Connection();
                log = "Connection with outlook established";
                File.AppendAllText(LogPath, LogData + log + Environment.NewLine);



                Outlook.Application application = conn.InitializeConnection(EmailAddress, Profile, out nameSpace, out outboxFolder, out oFolder);

                log = "Application object created";
                File.AppendAllText(LogPath, LogData + log + Environment.NewLine);

                log = EmailTo[0];
                File.AppendAllText(LogPath, LogData + log + Environment.NewLine);



                foreach (string item in EmailTo)
                {
                    log = "Processing email to: " + item;
                    File.AppendAllText(LogPath, LogData + log + Environment.NewLine);

                    if (EmailTo[i] != "" && EmailTo[i] != null)
                    {
                        EmailToItem = EmailTo[i].Replace(" ", "");
                    }

                    if (EmailCC.ElementAtOrDefault(i) != null)
                    {
                        EmailCCItem = EmailCC[i].Replace(" ", "");
                    }
                    if (EmailBCC.ElementAtOrDefault(i) != null)
                    {
                        EmailBCCItem = EmailBCC[i].Replace(" ", "");
                    }



                    // Creating email message object
                    Outlook.MailItem message = application.CreateItem(Outlook.OlItemType.olMailItem);

                    // Retrieve the account that has the specific SMTP address.
                    Outlook.Account account = GetAccountForEmailAddress(application, EmailAddress);
                    //// Use this account to send the e-mail.
                    message.SendUsingAccount = account;

                    log = "Found account in Outlook connected to: " + EmailAddress;
                    File.AppendAllText(LogPath, LogData + log + Environment.NewLine);

                    // Set Receipients
                    message.To  = EmailToItem;
                    message.CC  = EmailCCItem;
                    message.BCC = EmailBCCItem;

                    log = "Added all recepients. TO: " + EmailToItem + " CC: " + EmailCCItem + " BCC: " + EmailBCCItem;
                    File.AppendAllText(LogPath, LogData + log + Environment.NewLine);

                    // Email parameters
                    if (IsReadReceiptRequested.ElementAtOrDefault(i) != null)
                    {
                        if (IsReadReceiptRequested[i].ToLower() == "true")
                        {
                            message.ReadReceiptRequested = true;
                            log = "Setting read receipt request";
                            File.AppendAllText(LogPath, LogData + log + Environment.NewLine);
                        }
                    }

                    if (IsDeliveryReceiptRequested.ElementAtOrDefault(i) != null)
                    {
                        if (IsDeliveryReceiptRequested[i].ToLower() == "true")
                        {
                            message.OriginatorDeliveryReportRequested = true;
                            log = "Setting delivery receipt request";
                            File.AppendAllText(LogPath, LogData + log + Environment.NewLine);
                        }
                    }
                    if (HighEmailImportance.ElementAtOrDefault(i) != null)
                    {
                        if (HighEmailImportance[i].ToLower() == "true")
                        {
                            message.Importance = Outlook.OlImportance.olImportanceHigh;
                            log = "Setting email high priority";
                            File.AppendAllText(LogPath, LogData + log + Environment.NewLine);
                        }
                    }



                    // Set Subject
                    if (Subject.ElementAtOrDefault(i) != null)
                    {
                        if (Subject[i] == "")
                        {
                            i++;
                            message = null;
                            results.Add("Failed: Missing subject");
                            log = "Failed: Missing subject";
                            File.AppendAllText(LogPath, LogData + log + Environment.NewLine);
                            continue;
                        }
                        message.Subject = Subject[i];
                        log             = "Subject " + Subject[i] + " have been set";
                        File.AppendAllText(LogPath, LogData + log + Environment.NewLine);
                    }
                    else
                    {
                        i++;
                        message = null;
                        results.Add("Failed: Missing subject");
                        log = "Failed: Missing subject";
                        File.AppendAllText(LogPath, LogData + log + Environment.NewLine);
                        continue;
                    }


                    // Embedded image
                    if (Body.ElementAtOrDefault(i) != null)
                    {
                        log = "Inserting email body";
                        File.AppendAllText(LogPath, LogData + log + Environment.NewLine);

                        message.HTMLBody = Body[i];


                        log = "Inserted email body";
                        File.AppendAllText(LogPath, LogData + log + Environment.NewLine);
                    }
                    else if (EmailEmbedImagePath.ElementAtOrDefault(i) != null && EmailEmbedImigeFileName.ElementAtOrDefault(i) != null)
                    {
                        if (EmailEmbedImagePath[i] != "" && EmailEmbedImigeFileName[i] != "" && EmailEmbedImagePath[i] != null && EmailEmbedImigeFileName[i] != null)
                        {
                            Attachment attachment = message.Attachments.Add(
                                EmailEmbedImagePath[i] + EmailEmbedImigeFileName[i]
                                , OlAttachmentType.olEmbeddeditem
                                , null
                                , EmailEmbedImigeFileName[i]
                                );


                            attachment.PropertyAccessor.SetProperty(
                                "http://schemas.microsoft.com/mapi/proptag/0x3712001E"
                                , EmailEmbedImigeFileName[i]
                                );

                            //message.HTMLBody = String.Format(
                            //    @"<html><head></head><body><img width=245 height=97 id=""1"" src=""cid:" + EmailEmbedImigeFileName[i] + @"""></body></html>"
                            //    , EmailEmbedImigeFileName[i]
                            //    );
                            message.HTMLBody = String.Format(
                                Body[i]
                                , EmailEmbedImigeFileName[i]
                                );

                            log = "Image embedded: " + EmailEmbedImagePath[i] + EmailEmbedImigeFileName[i];
                            File.AppendAllText(LogPath, LogData + log + Environment.NewLine);
                        }
                    }



                    if (EmailAttachments.ElementAtOrDefault(i) != null)
                    {
                        if (EmailAttachments[i] != "" && EmailAttachments[i] != null)
                        {
                            Attachments = EmailAttachments[i].Split(';').ToList();

                            Attachment att = null;
                            foreach (string attachment in Attachments)
                            {
                                att = message.Attachments.Add(attachment, OlAttachmentType.olByValue, Type.Missing, Type.Missing);
                                log = "Attachment added: " + attachment;
                                File.AppendAllText(LogPath, LogData + log + Environment.NewLine);
                            }
                        }
                    }



                    message.Display(false);


                    if (SendEmail.ToLower() == "true")
                    {
                        message.Send();
                    }


                    //Outlook.NameSpace nameSpace = null;


                    if (nameSpace != null)
                    {
                        Marshal.ReleaseComObject(nameSpace);
                    }

                    log = "Email to " + EmailTo[i] + " sent";
                    File.AppendAllText(LogPath, LogData + log + Environment.NewLine);

                    message = null;



                    i++;

                    results.Add("Success");
                }


                //nameSpace = application.GetNamespace("MAPI");
                //outboxFolder = nameSpace.GetDefaultFolder(
                //    Outlook.OlDefaultFolders.olFolderOutbox) as Outlook.Folder;
                //log = "Outbox folder set";
                //File.AppendAllText(LogPath, log + Environment.NewLine);

                do
                {
                    log = "Outbox items: " + outboxFolder.Items.Count.ToString();
                    File.AppendAllText(LogPath, LogData + log + Environment.NewLine);
                    System.Threading.Thread.Sleep(5000);
                } while (outboxFolder.Items.Count.ToString() != "0");
                conn        = null;
                application = null;
                log         = "Disconnected from Outlook";
                File.AppendAllText(LogPath, LogData + log + Environment.NewLine);

                return(results);
            }
            catch (System.Exception ex)
            {
                results.Add("Failed: " + ex.ToString());
                throw;
            }
        }
            public void sendOutlookMailImage(String ToAddress, String CC, String BCC, String Body, String Subject, String FromAddress, String[] arrAttachment, Dictionary <String, String> dictimage)
            {
                try
                {
                    Outlook.Application OutlookApp = new Outlook.Application();
                    Outlook.MailItem    oNewMail   = (Outlook.MailItem)OutlookApp.CreateItem(Outlook.OlItemType.olMailItem);
                    oNewMail.BodyFormat = Outlook.OlBodyFormat.olFormatHTML;

                    AddReceipents(oNewMail, ToAddress, CC, BCC);

                    oNewMail.Subject  = Subject;
                    oNewMail.HTMLBody = Body;

                    if (dictimage != null)
                    {
                        foreach (KeyValuePair <String, String> FileName in dictimage)
                        {
                            Outlook.Attachment Att1 = oNewMail.Attachments.Add(FileName.Value, Outlook.OlAttachmentType.olEmbeddeditem, null, "");
                            Att1.PropertyAccessor.SetProperty("http://schemas.microsoft.com/mapi/proptag/0x3712001E", FileName.Key);
                        }
                    }

                    if (arrAttachment != null)
                    {
                        int iPosition   = (int)oNewMail.HTMLBody.Length + 1;
                        int iAttachType = (int)Outlook.OlAttachmentType.olByValue;
                        Outlook.Attachment oAttach;

                        foreach (String attach in arrAttachment)
                        {
                            if (!String.IsNullOrWhiteSpace(attach))
                            {
                                oAttach = oNewMail.Attachments.Add(attach, iAttachType, iPosition);
                            }
                        }
                    }

                    if (String.IsNullOrWhiteSpace(FromAddress))
                    {
                    }
                    else
                    {
                        Outlook.Accounts AllAccount  = OutlookApp.Session.Accounts;
                        Outlook.Account  SendAccount = null;

                        foreach (Outlook.Account account in AllAccount)
                        {
                            if (account.SmtpAddress.Equals(FromAddress, StringComparison.CurrentCultureIgnoreCase))
                            {
                                SendAccount = account;
                                break;
                            }
                        }
                        if (SendAccount != null)
                        {
                            oNewMail.SendUsingAccount = SendAccount;
                        }
                        else
                        {
                            throw new Exception("Account does not exist in Outlook : " + FromAddress);
                        }
                    }
                    oNewMail.Send();
                    oNewMail   = null;
                    OutlookApp = null;
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
Example #27
0
        //OutLookの下書きフォルダにメールを格納する。(デフォルトのアカウントに保存する
        private void CreateMailItem()
        {
            try {
                mailTempleteDS ds = new mailTempleteDS();
                ds.subject = m_subject.Text;
                ds.body    = m_body.Text;
                ds.account = m_account.Text;
                ds.attach1 = m_temp1.Text;
                ds.attach2 = m_temp2.Text;
                ds.attach3 = m_temp3.Text;
                ds.attach4 = m_temp4.Text;
                ds.attach5 = m_temp5.Text;

                string mailaddress;
                string name;
                //アドレス編集
                for (int i = 0; i < this.m_To_list.Items.Count; i++)
                {
                    name          = this.m_To_list.Items[i].SubItems[0].Text;
                    mailaddress   = this.m_To_list.Items[i].SubItems[1].Text;
                    ds.Toaddress += name + " <" + mailaddress + ">;";
                }

                for (int i = 0; i < this.m_Cc_list.Items.Count; i++)
                {
                    name          = this.m_Cc_list.Items[i].SubItems[0].Text;
                    mailaddress   = this.m_Cc_list.Items[i].SubItems[1].Text;
                    ds.CcAddress += name + " <" + mailaddress + ">;";
                }
                for (int i = 0; i < this.m_Bcc_list.Items.Count; i++)
                {
                    name           = this.m_Bcc_list.Items[i].SubItems[0].Text;
                    mailaddress    = this.m_Bcc_list.Items[i].SubItems[1].Text;
                    ds.BccAddress += name + " <" + mailaddress + ">;";
                }

                //指定されたアカウントを設定する
                String smtpAddress = "";
                smtpAddress = m_account.Text;
                var             app     = new Outlook.Application();
                Outlook.Account account = null;
                if (smtpAddress != null && smtpAddress != "")
                {
                    Outlook.Accounts accounts = app.Session.Accounts;

                    foreach (Outlook.Account maccount in accounts)
                    {
                        // When the e-mail address matches, return the account.
                        if (maccount.SmtpAddress == smtpAddress)
                        {
                            account = maccount;
                        }
                    }
                }
                //
                Outlook.MailItem mail = app.CreateItem(Outlook.OlItemType.olMailItem) as Outlook.MailItem;
                if (account != null)
                {
                    //送信アカウントを設定
                    mail.SendUsingAccount = account;
                }


                mail.Subject = m_subject.Text;

                mail.To  = ds.Toaddress;
                mail.CC  = ds.CcAddress;
                mail.BCC = ds.BccAddress;



                //Outlook.AddressEntry currentUser = app.Session.CurrentUser.AddressEntry;
                mail.Body = m_body.Text;

                //添付ファイル
                // ファイルが存在しているかどうか確認する
                if (System.IO.File.Exists(ds.attach1))
                {
                    mail.Attachments.Add(ds.attach1);
                }
                if (System.IO.File.Exists(ds.attach2))
                {
                    mail.Attachments.Add(ds.attach2);
                }
                if (System.IO.File.Exists(ds.attach3))
                {
                    mail.Attachments.Add(ds.attach3);
                }
                if (System.IO.File.Exists(ds.attach4))
                {
                    mail.Attachments.Add(ds.attach4);
                }
                if (System.IO.File.Exists(ds.attach5))
                {
                    mail.Attachments.Add(ds.attach5);
                }


                //アドレス帳を参照する
                mail.Recipients.ResolveAll();

                //下書きに保存
                mail.Save();

                //送信してしまう
                //mail.Send();
                MessageBox.Show("OutLookに出力しました。");
            }
            catch (Exception ex)
            {
                MessageBox.Show("OutLookに出力する際にエラーが発生しました。エラー:" + ex.Message, "メール出力");
            }
        }