%% READMAIL
% A simple script highlighting how you can connect to Outlook and
% import emails, including their subjects, bodies & attachements
%
% David Willingham, November 9 2011, MathWorks Australia

%% Connecting to Outlook
outlook = actxserver('Outlook.Application');
mapi=outlook.GetNamespace('mapi');
INBOX=mapi.GetDefaultFolder(6);

%% Retrieving last email
for i=0:50
    count = INBOX.Items.Count; %index of the most recent email.
    email=INBOX.Items.Item(count-i); %imports the most recent email
    subject = email.get('Subject');
    body = email.get('Body');
    senderName = email.get('SenderName');
    fprintf(1, 'Email Num: %d\t\tSender: %s %s\t\tSubject: ', i+1, senderName, subject);
    
    %% Saving attachments to current directory
    attachments = firstemail.get('Attachments');
    if attachments.Count >=1
        fname = attachments.Item(1).Filename;
        dir = pwd;
        full = [pwd,'\',fname];
        attachments.Item(1).SaveAsFile(full)
        fprintf(1, 'Attachment: %s', fname);
    end
    fprintf(1, '\n\n');
end