Search code examples
matlabsmtpgmail

Using the sendmail function to send an email through MATLAB


I am trying to send an email, using the MATLAB sendmail function. I have been following the instructions of the sendmail function analysis in Mathworks on this link: https://uk.mathworks.com/help/matlab/import_export/sending-email.html

The code which I used on the command window is the following:

setpref ('Internet','E_mail','[email protected]');
setpref ('Internet','SMTP_Server','smtp.gmail.com') ;
sendmail('[email protected]','texttobesent') ;

The message that I am getting after running those commands is the following:

Error using sendmail (line 169)

Could not connect to SMTP host: smtp.gmail.com, port: 25;

Connection timed out: connect

From what I understand I must change the arguments inside the second setpref function that I call, though I am not sure what exactly to include it them, based on the the gmail smtp port that is returned.


Solution

  • As @Xiangru Li said on his answer, setting up related to SSL is indeed needed. But that was not enough. Eventually, I had to change my google settings to turn on access for less secure apps. Information about doing this can be found in this link: https://support.google.com/accounts/answer/6010255?hl=en

    So after doing this, the following code was successful and I managed to send an email with it:

    setpref('Internet','SMTP_Server','smtp.gmail.com');  
    setpref('Internet','E_mail','myemailaddress');
    setpref('Internet','SMTP_Username','myusername');
    setpref('Internet','SMTP_Password','mypassword');
    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');
    sendmail('emailofreceiver','testtobesent') ;