Reputation: 2433
I am using the following piece of code to email the content of gerrit.txt which is HTML code but its not working?it doesnt show any errors but doesnt work the way its supposed to.any inputs on how to fix this?
from email.mime.text import MIMEText
from subprocess import check_call,Popen,PIPE
def email (body,subject,to=None):
msg = MIMEText("%s" % body)
msg['Content-Type'] = "text/html;"
msg["From"] = "[email protected]"
if to!=None:
to=to.strip()
msg["To"] = "[email protected]"
else:
msg["To"] = "[email protected]"
msg["Subject"] = '%s' % subject
p = Popen(["/usr/sbin/sendmail", "-t"], stdin=PIPE)
def main ():
Subject ="test email"
email('gerrit.txt',Subject,'userid')
if __name__ == '__main__':
main()
Upvotes: 2
Views: 82
Reputation: 69967
The reason nothing is being sent is because once you open the sendmail process, the message is never written to it. Also, you need to read the contents of the text file into a variable to include in the message.
Here is a simple example that builds off your code. I didn't use the MIMEText object for everything so modify it to suit your needs.
from email.mime.text import MIMEText
from subprocess import check_call,Popen,PIPE
def email (body,subject,to=None):
msg = MIMEText("%s" % body)
msg['Content-Type'] = "text/html;"
msg["From"] = "[email protected]"
if to!=None:
to=to.strip()
msg["To"] = to
else:
msg["To"] = "[email protected]"
msg["Subject"] = '%s' % subject
p = Popen(["/usr/sbin/sendmail", "-t", "-f" + msg["From"]], stdin=PIPE)
(stddata, errdata) = p.communicate(input="To: " + msg["To"] + "\r\nFrom: " + msg["From"] + "\r\nSubject: " + subject + "\r\nImportance: Normal\r\n\r\n" + body)
print stddata, errdata
print "Done"
def main ():
# open gerrit.txt and read the content into body
with open('gerrit.txt', 'r') as f:
body = f.read()
Subject ="test email"
email(body, Subject, "[email protected]")
if __name__ == '__main__':
main()
Upvotes: 1