0%

Use Matlab to send emails with attachments

  • Chinese:

The STMP service can be used to send emails to a specified email address through some of Matlab’s own functions. When running a large program, it can be used to notify the program that it has finished running or that there has been an error. Furthermore, Matlab supports the sending of results files saved by the program as attachments. This is also an indirect way of backing up the results.

Sending an email via Matlab is mainly the following code

1
sendmail(receiver,mailtitle,[mailcontent,filePath]);

It contains four parameters, receiver refers to the incoming mailbox, mailtitle is the subject of the message, mailcontent is the body content of the message, and filePath is the attachment file, I use the absolute path to the file. All four of these parameters are string types.

Of course there are some other settings needed to send the mail, and the encapsulated function is as follows.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
function mailMe(mailcontent,filePath,mailtitle)
% Account settings
mail = 'maresult@example.com'; % ① E-mail address
password = 'password'; % ② Password
if nargin <3
mailtitle='Matlab Result';% The subject of the message, which I don't change very often because of my usage habits. So by default
end

% Server settings
setpref('Internet','E_mail',mail);
setpref('Internet','SMTP_Server','smtp.163.com'); % ③ SMTP server
setpref('Internet','SMTP_Username',mail);
setpref('Internet','SMTP_Password',password);
props = java.lang.System.getProperties;
props.setProperty('mail.smtp.auth','true');
props.setProperty('mail.smtp.socketFactory.class', 'javax.net.ssl.SSLSocketFactory');
props.setProperty('mail.smtp.socketFactory.port','465');
% Send email
receiver='myself@example.com'; % ④ My incoming mailbox
try
if nargin==1
sendmail(receiver,mailtitle,mailcontent);
elseif nargin==2
sendmail(receiver,mailtitle,mailcontent,filePath);
elseif nargin==3
sendmail(receiver,mailtitle,mailcontent,filePath);
else
error('Eror input arguments');
end
catch
fprintf('Email failed to send with:\n');
fprintf(mailcontent);
end

In this way, you can send emails with attachments to the specified mailbox.

Note that attachments should not exceed 30mb in general, although China’s 163 and QQ mailboxes both support attachments of 50mb in size, but if the sender’s mailbox is one of these two, the password set is not your original password but an ‘authorisation code’. You can find it in “Settings” or “Security and Password” of your mailbox. The incoming mailbox is recommended to choose QQ mailbox, when the new mail comes, you can be reminded by QQ and WeChat, and there is unlimited mailbox space. Or mobile phone mailboxes from various operators are also good, with 100 or 200 free mailbox SMS alerts per month. You can receive messages from the program in real time.