2

我正在使用以下代码通过电子邮件发送 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()
4

1 回答 1

1

没有发送任何内容的原因是,一旦您打开 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()
于 2013-08-24T03:01:20.847 回答