Click here to Skip to main content
15,889,335 members
Home / Discussions / C#
   

C#

 
QuestionHow to change Input values Pin
waghniteen13-Apr-17 2:50
professionalwaghniteen13-Apr-17 2:50 
AnswerRe: How to change Input values Pin
User 418025413-Apr-17 4:01
User 418025413-Apr-17 4:01 
GeneralRe: How to change Input values Pin
waghniteen13-Apr-17 5:07
professionalwaghniteen13-Apr-17 5:07 
AnswerRe: How to change Input values Pin
OriginalGriff13-Apr-17 4:22
mveOriginalGriff13-Apr-17 4:22 
GeneralRe: How to change Input values Pin
waghniteen13-Apr-17 5:10
professionalwaghniteen13-Apr-17 5:10 
GeneralRe: How to change Input values Pin
OriginalGriff13-Apr-17 5:17
mveOriginalGriff13-Apr-17 5:17 
AnswerRe: How to change Input values Pin
jsc4225-Apr-17 0:43
professionaljsc4225-Apr-17 0:43 
QuestionEmail Attachment Downloader Pin
RonB8612-Apr-17 12:02
RonB8612-Apr-17 12:02 
I've been working to adapt code by Matthew Proctor. My goal is to remove the prompt, selecting the specific account, and downloading .xls attachments from a specific folder(inbox-attachments).
The program enumerates the email accounts, user selection, enumerates the "inbox's" subfolders, and extracts the .xls files. If anyone can point me in the right direction to accomplish this, I would very much appreciate the help. *I'm sorry that this is so long, but I didn't want to leave anything out that may be relevant.
///
/// Written by Matthew Proctor
/// www.matthewproctor.com
///
using System;
using System.Linq;
using System.IO;
using Outlook = Microsoft.Office.Interop.Outlook;

namespace OutlookAttachmentExtractor
{
    class Program
    {

        // Path where attachments will be saved
        static string basePath = @"c:\temp\DownloadedEmails\";
        // Integer to store to the total size of all the files - displayed
        // after processing to indicate possible PST file size saving
        static int totalfilesize = 0;

        static void Main(string[] args)
        {
            EnumerateAccounts();
        }
 
        // Uses recursion to enumerate Outlook subfolders.
       static void EnumerateFolders(Outlook.Folder folder)
        {
            Outlook.Folders childFolders = folder.Folders;
            if (childFolders.Count > 0)
            {
                // loop through each childFolder (aka sub-folder) in current folder
                foreach (Outlook.Folder childFolder in childFolders)
                {
                    // We only want Inbox folders - ignore Contacts and others
               if (childFolder.FolderPath.Contains(@"Inbox"))
                 
                    {
                        // Write the folder path.
                        Console.WriteLine(childFolder.FolderPath);
                        // Call EnumerateFolders using childFolder, to see if there are any sub-folders within this one
                        EnumerateFolders(childFolder);
                    }
                
                }
            }
            // pass folder to IterateMessages which processes individual email messages
            Console.WriteLine("Looking for items in " + folder.FolderPath);
            IterateMessages(folder);
        }
        
  
        // Loops through each item (aka email) in a folder
        static void IterateMessages(Outlook.Folder folder)
        {
            // attachment extensions to save
            string[] extensionsArray = { ".xls" };

            // Iterate through all items ("messages") in a folder
            var fi = folder.Items;
            if (fi != null)
            {

                try
                {
                    foreach (Object item in fi)
                    {
                        Outlook.MailItem mi = (Outlook.MailItem)item;
                        var attachments = mi.Attachments;
                        // Only process item if it has one or more attachments
                        if (attachments.Count != 0)
                        {

                            // Create a directory to store the attachment 
                            if (!Directory.Exists(basePath))
                            {
                                Directory.CreateDirectory(basePath);
                            }

                            // Loop through each attachment
                            for (int i = 1; i <= mi.Attachments.Count; i++)
                            {
                                // Check wither any of the strings in the extensionsArray are contained within the filename
                                var fn = mi.Attachments[i].FileName.ToLower();
                                if (extensionsArray.Any(fn.Contains))
                                {

                                    // Create a further sub-folder for the sender
                                    if (!Directory.Exists(basePath))
                                    {
                                        Directory.CreateDirectory(basePath);
                                    }
                                    totalfilesize = totalfilesize + mi.Attachments[i].Size;
                                    if (!File.Exists(basePath + @"\" + mi.Sender.Address + @"\" + mi.Attachments[i].FileName))
                                    {
                                        Console.WriteLine("Saving " + mi.Attachments[i].FileName);
                                        mi.Attachments[i].SaveAsFile(basePath + @"\" + mi.Attachments[i].FileName);
                                        // Uncomment next line to delete attachment after saving it
                                        // mi.Attachments[i].Delete();
                                    }
                                    else
                                    {
                                        Console.WriteLine("Already saved " + mi.Attachments[i].FileName);
                                    }
                                }
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    // Console.WriteLine("An error occurred: '{0}'", e);
                }
            }
        }

        // 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 "";
            }
        }

        // Displays introduction text, lists each Account, and prompts user to select one for processing.
        static void EnumerateAccounts()
        {
            Console.Clear();
            Console.WriteLine("Outlook XLS Extractor");
            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");
                    }
                }
            }
        }

        // Returns Folder object based on folder path
        static Outlook.Folder GetFolder(string folderPath)
        {
            Console.WriteLine("Looking for: " + folderPath);
            Outlook.Folder folder;
            string backslash = @"\";
            try
            {
                if (folderPath.StartsWith(@"\\"))
                {
                    folderPath = folderPath.Remove(0, 2);
                }
                String[] folders = folderPath.Split(backslash.ToCharArray());
                Outlook.Application Application = new Outlook.Application();
                folder = Application.Session.Folders[folders[0]] as Outlook.Folder;
                if (folder != null)
                {
                    for (int i = 1; i <= folders.GetUpperBound(0); i++)
                    {
                        Outlook.Folders subFolders = folder.Folders;
                        folder = subFolders[folders[i]] as Outlook.Folder;
                        if (folder == null)
                        {
                            return null;
                        }
                    }
                }
                return folder;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return null;
            }
        }


    }

}

AnswerRe: Email Attachment Downloader Pin
OriginalGriff12-Apr-17 21:35
mveOriginalGriff12-Apr-17 21:35 
GeneralRe: Email Attachment Downloader Pin
RonB8613-Apr-17 3:59
RonB8613-Apr-17 3:59 
GeneralRe: Email Attachment Downloader Pin
OriginalGriff13-Apr-17 4:26
mveOriginalGriff13-Apr-17 4:26 
QuestionGeneric usage is not clear in one program Pin
Tridip Bhattacharjee12-Apr-17 4:40
professionalTridip Bhattacharjee12-Apr-17 4:40 
AnswerRe: Generic usage is not clear in one program Pin
Gerry Schmitz12-Apr-17 4:57
mveGerry Schmitz12-Apr-17 4:57 
GeneralRe: Generic usage is not clear in one program Pin
OriginalGriff12-Apr-17 5:04
mveOriginalGriff12-Apr-17 5:04 
GeneralRe: Generic usage is not clear in one program Pin
Gerry Schmitz12-Apr-17 5:06
mveGerry Schmitz12-Apr-17 5:06 
GeneralRe: Generic usage is not clear in one program Pin
OriginalGriff12-Apr-17 5:43
mveOriginalGriff12-Apr-17 5:43 
AnswerRe: Generic usage is not clear in one program Pin
Richard MacCutchan12-Apr-17 22:00
mveRichard MacCutchan12-Apr-17 22:00 
Questiondynamic Crystal report ASP.NET MVC 5 Pin
Member 1021805212-Apr-17 2:26
Member 1021805212-Apr-17 2:26 
AnswerRe: dynamic Crystal report ASP.NET MVC 5 Pin
Afzaal Ahmad Zeeshan12-Apr-17 9:18
professionalAfzaal Ahmad Zeeshan12-Apr-17 9:18 
QuestionUser name and pasword from web page. Pin
Lubos111-Apr-17 5:09
Lubos111-Apr-17 5:09 
AnswerRe: User name and pasword from web page. Pin
Dave Kreskowiak11-Apr-17 5:30
mveDave Kreskowiak11-Apr-17 5:30 
GeneralRe: User name and pasword from web page. Pin
Lubos111-Apr-17 5:37
Lubos111-Apr-17 5:37 
GeneralRe: User name and pasword from web page. Pin
Lubos111-Apr-17 5:40
Lubos111-Apr-17 5:40 
GeneralRe: User name and pasword from web page. Pin
Lubos111-Apr-17 5:49
Lubos111-Apr-17 5:49 
GeneralRe: User name and pasword from web page. Pin
OriginalGriff11-Apr-17 5:59
mveOriginalGriff11-Apr-17 5:59 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.