Monday, June 19, 2017

[Matlab] Send emails with Matlab

We can send emails using Matlab command via MS Outlook COM API.

First create a new function for COM API as below.(source from Matlab FileExchange)

-------------------------------------------------------------------------
function sendolmail(to,cc,subject,body,attachments)
%Sends email using MS Outlook. The format of the function is 
%Similar to the SENDMAIL command.
% Create object and set parameters.

% Without attachments, 
% sendolmail('email account','Title','Test message including');

h = actxserver('outlook.Application');
mail = h.CreateItem('olMail');
mail.Subject = subject;
mail.To = to;
mail.Cc = cc;
mail.BodyFormat = 'olFormatHTML';

% for multiline body
% ---
body = cellstr(body); % to get a vector of 1 lione string
mailbody = '';
for i=1:1:numel(body)
    mailbody = cat(2,mailbody, char(body(i)), '
');
end
% ------
mail.HTMLBody = mailbody;


% Add attachments, if specified.
if nargin == 5
    for i = 1:length(attachments)
        mail.attachments.Add(attachments{i});
    end
end
% Send message and release object.
mail.Send;
h.release;
---------------------------------------------------------------------------------

Second, type, for example, " sendolmail('email account','Mail from Matlab','Hello there'); " on the Matlab command or create a new m-file.
Then, we can send and receive an email as below.

-------------------
Sending an email through m script with the function above

to = 'a@email.com;b@email.com';%to = {'a@email.com';'b@email.com'};
cc = 'c@email.com';

title1 = 'Automation tool update ';
title2 = 'Ver 1';
title = sprintf('%s%s',title1,title2);

message ={'各位',...
    '',...
    'お疲れ様です',...
    '',...  
    'よろしくお願いします。'};

sendolmail(to,cc,title,message);
% for N=1:1:length(to)
%     sendolmail(to{N,1},title,message);
% end
----------

* See also the Matlab command "sendmail"










No comments:

Post a Comment