%% 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);

attCount = 1;
%% Retrieving last email
for i=0:10
    count = INBOX.Items.Count; %index of the most recent email.
    firstemail=INBOX.Items.Item(count-i); %imports the most recent email
    % secondmail=INBOX.Items.Item(count-1); %imports the 2nd most recent email
    subject = firstemail.get('Subject');
    body = firstemail.get('Body');
    senderName = firstemail.get('SenderName');
    creationTime = firstemail.get('CreationTime');
    fprintf(1, 'Email num: %d\tCreation Time: %s\tSender: %s\tSubject: %s\n', i+1, creationTime, senderName, subject);
    
    %% Saving attachments to current directory
    attachments = firstemail.get('Attachments');
    if attachments.Count >=1
        attName = attachments.Item(1).Filename;
        attName = [attName num2str(attCount)];
        attCount = attCount + 1;
        
        dir = pwd;
        full = [pwd,'\', attName];
        attachments.Item(1).SaveAsFile(full)
        fprintf('Attachment: %s\n\n', attName);
    else
        fprintf('\n');
    end
end