使用子进程模块在python中发送电子邮件

おおさ*_*おさま 5 python subprocess postfix-mta

我写了一个脚本来从网站上检索天气报告,并在早上将其发送给我的女朋友。

使用 Gmail。当然,我可以使用我的 Postfix 服务器发送它。这是脚本。

什么我不知道是如何使用POPEN()函数的情况有这么多的争论。

我可以使用命令发送邮件。

$ mail -s "??????????" abc@gmail.com < foo

#!/usr/bin/env python
# -*- coding: utf-8 -*-
from bs4 import BeautifulSoup
import urllib2
import subprocess

weather_url = "http://www.weather.com.cn/weather/101020100.shtml"
f=urllib2.urlopen(weather_url)
html = f.read()
soup = BeautifulSoup(html)

content = soup.title.string

with open("foo","w") as mail:
    mail.write(content.encode('utf-8'))

command_line = 'mail -s "??????????" abc@gmail.com < foo'

li = command_line.split()

process = subprocess.Popen(li, shell=True)

returncode = process.wait()
Run Code Online (Sandbox Code Playgroud)

天气报告的内容在foo文件中。有人能告诉我如何使用Popen()这么多参数吗?

我尝试了很多。

这个脚本似乎不起作用。

Inb*_*ose 0

使用时不需要传递参数列表,只需shell=True传递参数字符串即可...

\n\n
command_line = \'mail -s "\xe3\x81\x8a\xe3\x81\x8a\xe6\xa7\x98\xe3\x81\x8b\xe3\x82\x89\xe3\x81\xae\xe5\xa4\xa9\xe6\xb0\x97\xe4\xba\x88\xe5\xa0\xb1" abc@gmail.com < foo\'\nprocess = subprocess.Popen(command_line, shell=True)\n
Run Code Online (Sandbox Code Playgroud)\n\n

或者..您不能使用 shell 来解释您的参数并传递列表...

\n\n
command_line = \'mail -s "\xe3\x81\x8a\xe3\x81\x8a\xe6\xa7\x98\xe3\x81\x8b\xe3\x82\x89\xe3\x81\xae\xe5\xa4\xa9\xe6\xb0\x97\xe4\xba\x88\xe5\xa0\xb1" abc@gmail.com < foo\'\nli = command_line.split()\nprocess = subprocess.Popen(li)\n
Run Code Online (Sandbox Code Playgroud)\n\n

但是您不能传递参数列表使用 shell 来解释它。

\n\n

根据命令的性质,我建议将字符串传递给 shell 进行解释。(第一个选项)

\n