Skip to main content
 首页 » 编程设计

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

2025年05月04日30zhenyulu

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