Python 在unix平台上通过电子邮件发送文本文件的内容

Python 在unix平台上通过电子邮件发送文本文件的内容,python,Python,我正在使用下面的代码通过电子邮件发送gerrit.txt的内容,它是HTML代码,但不起作用?它没有显示任何错误,但没有按预期的方式工作。有没有关于如何修复此问题的输入 from email.mime.text import MIMEText from subprocess import check_call,Popen,PIPE def email (body,subject,to=None): msg = MIMEText("%s" % body) msg['Con

我正在使用下面的代码通过电子邮件发送gerrit.txt的内容,它是HTML代码,但不起作用?它没有显示任何错误,但没有按预期的方式工作。有没有关于如何修复此问题的输入

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"] = "userid@company.com"
      if to!=None:
          to=to.strip()
          msg["To"] = "userid@company.com"
      else:
          msg["To"] = "userid@company.com"
      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()

未发送任何内容的原因是,一旦打开sendmail进程,消息将永远不会写入其中。此外,还需要将文本文件的内容读入要包含在消息中的变量中

下面是一个基于代码构建的简单示例。我并不是什么都使用MIMEText对象,所以请修改它以满足您的需要

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"] = "you@yoursite.com"
      if to!=None:
          to=to.strip()
          msg["To"] = to
      else:
          msg["To"] = "user@domain.com"
      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, "from@domain.com")

if __name__ == '__main__':
    main()

它看起来不像是在向管道中写入内容。实际上,..gerrit.txt包含HTML代码..我希望以HTML格式通过电子邮件发送输出,而不是完全相同的内容…例如:gerrit.txt的内容只需添加一个
内容类型:text/HTML;charset=UTF8
消息头,它将是HTML格式。您能告诉我应该在代码中添加哪个部分吗?代码中不是已经有了吗?
(stddata,errdata)=p.communicate(input=“to:”+msg[”to“]+”\r\n From:“+msg[”From“]+”\r\n对象:“+subject+“\r\n内容类型:text/html;charset=UTF8\r\n重要性:正常\r\n\r\n”+正文)