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

时间:2013-08-24 02:12:10

标签: 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['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()

1 个答案:

答案 0 :(得分: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()