We all know the problem; it’s getting late in the office, all your colleagues left hours ago, and your eyes are watering from staring at the analysis output of a script that should have finished running ages ago. Yet for some inexplicable reason, it’s still not done. Wouldn’t it be great if you could just nip out to get some fresh air and be informed when the script is finally done? Well actually, you can! Here’s a handy little tip explaining how to embed email alerts in MATLAB and Python scripts:
MATLAB MATLAB comes with a handy function that supports sending emails within scripts. But before we can actually get to the email sending, we need to configure some server information. Here is an example for a gmail account:
mail = 'Me@gmail.com'; %Your GMail email address
password = 'secret'; %Your GMail password
setpref('Internet','SMTP_Server','smtp.gmail.com');
setpref('Internet','E_mail',mail);
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');
Now, we are ready to send an email:
sendmail(‘someone@coldmail.com’,’Hello there!’);
The second argument in the sendmail function corresponds to the subject line of the email. If you are keen to let MATLAB send a more elaborate email, you can also include a text body:
sendmail('someone@coldmail.com','Hello there!','Have you seen that great post on the Forging Connections Blog?');
It is even possible to send attachments:
sendmail('recipient@someserver.com','Hello there!','Have you seen that great post on the Forging Connections Blog?',{'/Users/Fred/image.jpeg’});
By including these few lines of code in your time-consuming MATLAB script, you can now get notified when it is time to go back to the office for the results.
Python Python offers a simple solution to send emails from within scripts via the smtplib module. Here is a function that provides the configuration for gmail: def send_email(): import smtplib
gmail_user = "Fred@gmail.com"
gmail_pwd = "Password"
FROM = 'Fred@gmail.com'
TO = ['Luke@gmail.com']
SUBJECT = "Meeting at 3pm"
TEXT = "Are you coming to the meeting?"
# Prepare actual message
message = """\From: %s\nTo: %s\nSubject: %s\n\n%s
""" % (FROM, ", ".join(TO), SUBJECT, TEXT)
try:
server = smtplib.SMTP("smtp.gmail.com", 587)
server.ehlo()
server.starttls()
server.login(gmail_user, gmail_pwd)
server.sendmail(FROM, TO, message)
server.close()
print 'successfully sent the mail'
except:
print "failed to send mail"
留言