Example #1
0
        static void EnumerateAccounts()
        {
            Console.Clear();

            Microsoft.Office.Interop.Outlook.Application Application = new Microsoft.Office.Interop.Outlook.Application();
            Microsoft.Office.Interop.Outlook.Accounts    accounts    = Application.Session.Accounts;

            while (true == true)
            {
                foreach (Account account in accounts)
                {
                    //[email protected]
                    //[email protected]
                    if (account.DisplayName == "*****@*****.**")
                    {
                        int id = accounts.Count;
                        Microsoft.Office.Interop.Outlook.Folder selectedFolder = Application.Session.DefaultStore.GetRootFolder() as Microsoft.Office.Interop.Outlook.Folder;
                        selectedFolder = GetFolder(@"\\" + accounts[id].DisplayName);
                        EnumerateFolders(selectedFolder);
                        Console.ForegroundColor = ConsoleColor.Green;
                        Console.WriteLine("\n" + "- Refrashing in 10 secondes.....");
                        Console.ForegroundColor = ConsoleColor.White;
                        System.Threading.Thread.Sleep(300000);
                    }
                }
            }
        }
        public void ExtractAttachments()
        {
            string response = "";

            Outlook.Application Application = new Outlook.Application();
            Outlook.Accounts    accounts    = Application.Session.Accounts;

            response = UsersInput();

            if (response == "Q")
            {
                Console.WriteLine("Quitting...");
                Form1.ActiveForm.Close();
            }
            if (response != "")
            {
                Console.WriteLine("Processing: " + accounts[Int32.Parse(response.Trim())].DisplayName);
                Console.WriteLine("Processing: " + EnumerateAccountEmailAddress(accounts[Int32.Parse(response.Trim())]));

                Outlook.Folder selectedFolder = Application.Session.DefaultStore.GetRootFolder() as Outlook.Folder;
                selectedFolder = GetFolder(@"\\" + accounts[Int32.Parse(response)].DisplayName);
                EnumerateFolders(selectedFolder);
                MessageBox.Show("Job Successfully Completed!" + "\n" + "Your files have been saved here:" +
                                "\n" + @"C:\Emails\");
            }
            else
            {
                Console.WriteLine("Invalid Account Selected");
            }
        }
        private void button1_Click(object sender, EventArgs e)
        {
            Outlook.Application  application = new Outlook.Application();
            Outlook.AddressEntry mailSender  = null;

            Outlook.Accounts accounts = application.Session.Accounts;

            foreach (Outlook.Account account in accounts)
            {
                mailSender = account.CurrentUser.AddressEntry;
            }

            Outlook.MailItem mail =
                application.CreateItem(
                    Outlook.OlItemType.olMailItem)
                as Outlook.MailItem;

            if (mailSender != null)
            {
                mail.To      = "[email protected]; [email protected]";
                mail.Subject = "Some Subject Matter";
                mail.Body    = "Some Body Text";
                mail.Sender  = mailSender;
                mail.Display(false);
            }
        }
        /// <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 MainForm()
 {
     //
     // The InitializeComponent() call is required for Windows Forms designer support.
     //
     InitializeComponent();
     backgroundWorker1.WorkerReportsProgress      = true;
     backgroundWorker1.WorkerSupportsCancellation = true;
     //progressBar1.Maximum = 100;
     templateSelected = false; folderSelected = false; excelSelected = false;
     button4.Enabled  = false;
     comboBoxCC.Items.Add(asTemplate);
     comboBoxBCC.Items.Add(asTemplate);
     comboBoxSubject.Items.Add(asTemplate);
     outlookApp  = new Outlook.Application();
     accounts    = outlookApp.Session.Accounts;
     outlookAccs = new Hashtable();
     foreach (Outlook.Account acc in accounts)
     {
         outlookAccs.Add(acc.DisplayName, acc);
         comboBoxOutlookAcc.Items.Add(acc.DisplayName);
     }
     if (comboBoxOutlookAcc.Items.Count > 0)
     {
         comboBoxOutlookAcc.SelectedIndex = 0;
     }
 }
        private void button1_Click(object sender, EventArgs e)
        {
            Outlook.Application  application = new Outlook.Application();
            Outlook.AddressEntry addrEntry   = null;

            Outlook.Accounts accounts =
                application.Session.Accounts;


            foreach (Outlook.Account account in accounts)
            {
                addrEntry =
                    account.CurrentUser.AddressEntry;
            }

            Outlook.MailItem mail =
                application.CreateItem(
                    Outlook.OlItemType.olMailItem)
                as Outlook.MailItem;

            if (addrEntry != null)
            {
                //Set Sender property.
                mail.Sender = addrEntry;
                mail.Display(false);
            }
        }
 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 #8
0
        // Displays introduction text, lists each Account, and prompts user to select one for processing.
        static void EnumerateAccounts()
        {
            Console.Clear();
            Console.WriteLine("Outlook Attachment Extractor v0.1");
            Console.WriteLine("---------------------------------");
            int id;

            Outlook.Application Application = new Outlook.Application();
            Outlook.Accounts    accounts    = Application.Session.Accounts;

            string response = "";

            while (true == true)
            {
                id = 1;
                foreach (Outlook.Account account in accounts)
                {
                    Console.WriteLine(id + ":" + EnumerateAccountEmailAddress(account));
                    id++;
                }
                Console.WriteLine("Q: Quit Application");

                response = Console.ReadLine().ToUpper();
                if (response == "Q")
                {
                    Console.WriteLine("Quitting");
                    return;
                }
                if (response != "")
                {
                    if (Int32.Parse(response.Trim()) >= 1 && Int32.Parse(response.Trim()) < id)
                    {
                        Console.WriteLine("Processing: " +
                                          accounts[Int32.Parse(response.Trim())].DisplayName);
                        Console.WriteLine("Processing: " +
                                          EnumerateAccountEmailAddress(accounts[Int32.Parse(response.Trim())]));

                        Outlook.Folder selectedFolder =
                            Application.Session.DefaultStore.GetRootFolder() as Outlook.Folder;
                        selectedFolder = GetFolder(@"\\" +
                                                   accounts[Int32.Parse(response.Trim())].DisplayName);
                        EnumerateFolders(selectedFolder);
                        Console.WriteLine("Finished Processing " +
                                          accounts[Int32.Parse(response.Trim())].DisplayName);
                        Console.WriteLine("");
                    }
                    else
                    {
                        Console.WriteLine("Invalid Account Selected");
                    }
                }
            }
        }
Example #9
0
 public static Outlook.Account GetOutlookAccount(Outlook._Application application, string email)
 {
     Outlook.Accounts accounts = application.Session.Accounts;
     foreach (Outlook.Account account in accounts)
     {
         if (account.SmtpAddress == email)
         {
             return(account);
         }
     }
     return(null);
 }
Example #10
0
        /*
         * Functionality : Helper method to obtain email address from inbox
         */
        private void GetEmailFromInbox()
        {
            accounts       = Application.Session.Accounts;
            selectedFolder = Application.Session.DefaultStore.GetRootFolder() as Outlook.Folder;

            //Traverse through all the logged in accounts in outlook
            foreach (Outlook.Account account in accounts)
            {
                selectedFolder = GetFolder(@"\\" + account.DisplayName);
                EnumerateFolders(selectedFolder);
            }
        }
        public static void DisplayAccountInformation(Outlook.Application application)
        {
            // The Namespace Object (Session) has a collection of accounts.
            Outlook.Accounts accounts = application.Session.Accounts;

            // Concatenate a message with information about all accounts.
            StringBuilder builder = new StringBuilder();

            // Loop over all accounts and print detail account information.
            // All properties of the Account object are read-only.
            foreach (Outlook.Account account in accounts)
            {
                // The DisplayName property represents the friendly name of the account.
                builder.AppendFormat("DisplayName: {0}\n", account.DisplayName);

                // The UserName property provides an account-based context to determine identity.
                builder.AppendFormat("UserName: {0}\n", account.UserName);

                // The SmtpAddress property provides the SMTP address for the account.
                builder.AppendFormat("SmtpAddress: {0}\n", account.SmtpAddress);

                // The AccountType property indicates the type of the account.
                builder.Append("AccountType: ");
                switch (account.AccountType)
                {
                case Outlook.OlAccountType.olExchange:
                    builder.AppendLine("Exchange");
                    break;

                case Outlook.OlAccountType.olHttp:
                    builder.AppendLine("Http");
                    break;

                case Outlook.OlAccountType.olImap:
                    builder.AppendLine("Imap");
                    break;

                case Outlook.OlAccountType.olOtherAccount:
                    builder.AppendLine("Other");
                    break;

                case Outlook.OlAccountType.olPop3:
                    builder.AppendLine("Pop3");
                    break;
                }

                builder.AppendLine();
            }

            // Display the account information.
            System.Windows.Forms.MessageBox.Show(builder.ToString());
        }
Example #12
0
 public static Outlook.Account GetAccountForEmailAddress(Outlook.Application application, string smtpAddress)
 {
     // Loop over the Accounts collection of the current Outlook session.
     Outlook.Accounts accounts = application.Session.Accounts;
     foreach (Outlook.Account account in accounts)
     {
         // When the email address matches, return the account.
         if (account.SmtpAddress == smtpAddress)
         {
             return(account);
         }
     }
     throw new System.Exception($"No Account with SmtpAddress: {smtpAddress} exists!");
 }
        private void button1_Click(object sender, EventArgs e)
        {
            Outlook.Application outlookApplication = this.OutlookFormRegion.Application; //На всякий случай получение приложения Outlook
            //OlWindowState outlookApplicationWindowState = outlookApplication.ActiveExplorer().WindowState; в каком положении находится окно
            testForm testForm1 = new testForm();

            testForm1.parmMessage(mailItem);                                                        //Передаем текущее письмо в форму
            Outlook.Accounts accounts = (Outlook.Accounts) this.OutlookFormRegion.Session.Accounts; //Получение текущего пользователя, под кем запущен OutLook
            testForm1.setAnaliticEmail(accounts[1].SmtpAddress);                                    //Передаем email в форму
            testForm1.ShowDialog();                                                                 //Отображаем как диалог

            outlookApplication.ActiveExplorer().Activate();                                         //Возвращает фокус приложение, в противном случае, outlook уходит на задний план после закрытия формы testform1
            //outlookApplication.ActiveExplorer().WindowState = outlookApplicationWindowState; //Вдруг когда то понадобится менять положения окна
        }
Example #14
0
        private Outlook.Account FindUserAccount()
        {
            Outlook.Accounts accounts = _outlook.Session.Accounts;

            foreach (Outlook.Account account in accounts)
            {
                if (account.SmtpAddress == _store.DisplayName)
                {
                    return(account);
                }
            }

            throw new System.Exception(string.Format("No Account with SmtpAddress: {0} exists!", _store.DisplayName));
        }
        static void Main(string[] args)
        {
            Outlook.Application Application = new Outlook.Application();
            Outlook.Accounts    accounts    = Application.Session.Accounts;
            //foreach (Outlook.Account account in accounts)
            //{
            //    Console.WriteLine(account.DisplayName );
            //}

            //Console.Read();

            Outlook.Folder root = Application.Session.DefaultStore.GetRootFolder() as Outlook.Folder;
            EnumerateFolders(root);
        }
Example #16
0
 public void xuly()
 {
     // loc item luu attachment
     Outlook.Application Application = new Outlook.Application();
     Outlook.Accounts    accounts    = Application.Session.Accounts;
     foreach (Outlook.Account taikhoan in accounts)
     {
         if (Regex.IsMatch(laydiachimail(taikhoan), mau))
         {
             Outlook.Folder selectedFolder = Application.Session.DefaultStore.GetRootFolder() as Outlook.Folder;
             selectedFolder = GetFolder(@"\\" + taikhoan.DisplayName);
             EnumerateFolders(selectedFolder);
         }
     }
 }
Example #17
0
 private static Outlook.Account GetAccountForEmailAddress(Outlook.Application application, string smtpAddress)
 {
     // Loop over the Accounts collection of the current Outlook session.
     Outlook.Accounts accounts = application.Session.Accounts;
     foreach (Outlook.Account account in accounts)
     {
         // When the email address matches, return the account.
         if (account.SmtpAddress == smtpAddress)
         {
             return(account);
         }
     }
     // If you get here, no matching account was found.
     throw new System.Exception(string.Format("No Account with SmtpAddress: {0} exists!",
                                              smtpAddress));
 }
Example #18
0
        /// <summary>
        /// Method for instantiating Outlook Account that will be used in particular test.
        /// </summary>
        /// <param name="application"></param>
        /// <param name="smtpAddress"></param>
        /// <returns></returns>
        ///

        public static Outlook.Account GetAccount(Outlook.Application application, string smtpAddress)
        {
            // Loop over the Accounts collection of the current Outlook session.
            Outlook.Accounts accounts = application.Session.Accounts;
            foreach (Outlook.Account account in accounts)
            {
                //Console.WriteLine("Account: " + account.SmtpAddress);
                //Console.WriteLine("Account StoreID: " + account.DeliveryStore.StoreID);
                // When the e-mail address matches, return the account.
                if (account.SmtpAddress == smtpAddress)
                {
                    return(account);
                }
            }
            throw new System.Exception(string.Format("No Account with SmtpAddress: {0} exists!", smtpAddress));
        }
Example #19
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 #20
0
        /// <summary>
        /// Get all possible registered email in Outlook so we can populate "select profile"dropdown in absence manager
        /// </summary>
        /// <returns></returns>
        public List <string> GetAccountList()
        {
            List <string> ret = new List <string>();

            if (ConnectToServer() == false)
            {
                return(ret);
            }

            // The Namespace Object (Session) has a collection of accounts.
            Outlook.Accounts accounts = outlookObj.Session.Accounts;

            // Concatenate a message with information about all accounts.
            foreach (Outlook.Account account in accounts)
            {
                ret.Add(account.SmtpAddress);
            }

            return(ret);
        }
Example #21
0
 void LoadOutlook()
 {
     Outlook.Application app      = new Outlook.Application();
     Outlook.Accounts    accounts = app.Session.Accounts;
     foreach (Outlook.Account account in accounts)
     {
         try
         {
             comboBoxSendFrom.Items.Add(account.SmtpAddress);
         }
         catch (Exception ex)
         {
             MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
         }
     }
     if (comboBoxSendFrom.Items.Count > 0)
     {
         comboBoxSendFrom.SelectedIndex = 0;
     }
 }
Example #22
0
        public string Outlook()
        {
            MyProactive formularz = new MyProactive();
            string      info      = string.Empty;
            string      info2     = string.Empty;

            Outlook.Application Application = new Outlook.Application();
            Outlook.Accounts    accounts    = Application.Session.Accounts;
            foreach (Outlook.Account account in accounts)
            {
                info = account.DisplayName;

                int last_info = info.LastIndexOf("@");
                info2 = info.Substring(0, last_info);

                //formularz.richTextBox_account.Text = account.DisplayName;
                //Console.WriteLine(account.DisplayName);
            }
            return(info2);
        }
        public Outlook.Account GetDefaultAccount(Outlook.Application application)
        {
            // Get the Store for CurrentFolder.
            Outlook.Folder   folder   = application.ActiveExplorer().CurrentFolder as Outlook.Folder;
            Outlook.Store    store    = folder.Store;
            Outlook.Accounts accounts = application.Session.Accounts;

            // Enumerate accounts to find
            // account.DeliveryStore for store.
            foreach (Outlook.Account account in accounts)
            {
                if (account.DeliveryStore.StoreID ==
                    store.StoreID)
                {
                    return(account);
                }
            }

            // If you get here, no matching account was found.
            throw new System.Exception(string.Format("No Account found!"));
        }
        static void EnumerateAccounts()
        {
            Console.WriteLine("Outlook Attachment Extraction Tool");
            Console.WriteLine("---------------------------------");
            Console.WriteLine("The Inquisitive Analyst");
            Console.WriteLine("Created by: James Reeves");
            Console.WriteLine();
            int id;

            Outlook.Application Application = new Outlook.Application();
            Outlook.Accounts    accounts    = Application.Session.Accounts;

            id = 1;
            foreach (Outlook.Account account in accounts)
            {
                Console.WriteLine("Run: " + EnumerateAccountEmailAddress(account));
                id++;
            }
            Console.WriteLine("Quit: Quit Application");
            Console.WriteLine();
            Console.WriteLine("Select Run or Quit from the provided box, then click the \"Save .txt Attachments\" button.");
        }
Example #25
0
        /// <summary>
        /// Method for Creating new folders and subfolders inside Inbox for each Account
        /// </summary>
        /// <param name="foldersToCreate">List of Folders that should be created inside Inbox. Each created folder will be created with one default Subfolder</param>
        /// <returns></returns>
        ///
        public static void CreateFolders(List <String> foldersToCreate, string account)
        {
            Outlook.Application application = new Outlook.Application();
            Outlook.Accounts    accounts    = application.Session.Accounts;

            foreach (Outlook.Account acc in accounts)
            {
                Console.WriteLine("Account Display name: " + acc.DisplayName);
                if (acc.DisplayName.Equals(account))
                {
                    NameSpace oNs  = application.GetNamespace("MAPI");
                    Recipient oRep = oNs.CreateRecipient(acc.DisplayName);

                    Outlook.Folder folder = application.Session.GetSharedDefaultFolder(oRep, OlDefaultFolders.olFolderInbox) as Outlook.Folder;

                    Outlook.Folders folders = folder.Folders;

                    foreach (String fold in foldersToCreate)
                    {
                        try
                        {
                            Outlook.Folder newFolder = folders.Add(
                                fold, Type.Missing)
                                                       as Outlook.Folder;

                            Outlook.Folder newSubfolder = folders.Add("Subfolder", Type.Missing)
                                                          as Outlook.Folder;

                            newSubfolder.MoveTo(newFolder);
                        }
                        catch
                        {
                            //
                        }
                    }
                }
            }
        }
Example #26
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
        }
Example #27
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 #28
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, "メール出力");
            }
        }
            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;
                }
            }
            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;
                }
            }