如何用python发送电子邮件给多个接收器


How to email multiple receiver with python?

我有一个php脚本从我的wordpress网站数据库获取用户电子邮件地址。php脚本如下

$sql = "SELECT user_email FROM wp_users";
$addr = mysqli_query($conn,$sql);
while ($row = mysqli_fetch_assoc($addr)){
        printf ("%s'n", $row["user_email"]);
}

输出如下所示

abcd@gmail.com

ggyy@gmail.com

在我的python代码中,我使用urllib2来读取php, python代码片段看起来像这样

response = urllib2.urlopen('http://192.168.0.168/useremail.php')
status = response.read()
fromaddr = "testing123@gmail.com"
toaddr = status
server.sendmail(fromaddr, toaddr)

在这种情况下,电子邮件总是发送到第一个电子邮件地址,尽管有几个电子邮件地址从php脚本检索。请帮我解决这个问题。很抱歉,我是个编程初学者。

sendmail()需要一个邮件地址列表。因此,您需要使用urllib2的响应来构建该列表。

使用splitlines()返回字符串中的行列表。

。:

import urllib2
response = urllib2.urlopen('http://192.168.0.168/useremail.php')
status = response.read()
mail_list = status.splitlines() # split the response in a list 
print mail_list
# ['john@doe.tld', 'smyth@noon.tld', 'arthur@excalibur.tld', 'george@dada.tld']
# then send the mails    
fromaddr = "testing123@gmail.com"
server.sendmail(fromaddr, mail_list)

希望能有所帮助。