Below are 2 code blocks. The first will send a message to gmail with the correct subject and sender. However, when I put the first code into a function, the email loses the sender and subject info.
Why is this and how do I fix it?
I would like to be able to call this function from other python scripts to notify me when my job is complete. The function works and runs without error, and the email makes it to my inbox, but I lose the sender info and more importantly, the subject heading.
1st code that runs as expected:
import smtplib
gmail_user = 'name@domain.com'
gmail_password = 'password'
sent_from = gmail_user
to = ['recipient@domain.com']
subject = "job complete"
body = "python script " + str(name) + " has finished"
email_text = """\
From: %s
To: %s
Subject: %s
%s
""" % (sent_from, ", ".join(to), subject, body)
server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
server.ehlo()
server.login(gmail_user, gmail_password)
server.sendmail(sent_from, to, email_text)
server.close()
2nd code that loses subject and sender info:
def mailer(subject, body):
import smtplib
gmail_user = 'name@domain.com'
gmail_password = 'password'
sent_from = gmail_user
to = ['recipient@domain.com']
subject = subject
body = body
email_text = """\
From: %s
To: %s
Subject: %s
%s
""" % (sent_from, ", ".join(to), subject, body)
server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
server.ehlo()
server.login(gmail_user, gmail_password)
server.sendmail(sent_from, to, email_text)
server.close()
subject = "job complete"
body = "python script " + str(name) + " has finished"
mailer(subject, body)