Send an Gmail/SMS message from Python
Sometimes you'd like a server to notify you when its done with a job, with a
minimal amount of configuration. Fortunately, Python's
The function below sends an email to from your Gmail account (as specified by
pwd) to a
recipient with an associated
def send_email(user, pwd, recipient, subject, body): import smtplib gmail_user = user gmail_pwd = pwd FROM = user TO = recipient if type(recipient) is list else [recipient] SUBJECT = subject TEXT = body # 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"
You can put this in a script and have it trigger like so:
send_email("firstname.lastname@example.org","mypassword","email@example.com","Job XXXX is done","Done.")
You can also use it to send SMS messages to yourself, if you know your provider's SMS gateway. For instance, I use Ting for my cell service, so I can send myself SMS messages with:
send_email("firstname.lastname@example.org","mypassword","MY_NUMBER@message.ting.com","","Job XXXX is done.")
Credit: We have David Okwii's SO answer to thank for this.