Jeff Pang Jeff Pang - 20 days ago 5
PHP Question

How to email multiple receiver with python?

I have a php script to fetch user email address from my wordpress site database.
The php script as follow

$sql = "SELECT user_email FROM wp_users";
$addr = mysqli_query($conn,$sql);

while ($row = mysqli_fetch_assoc($addr)){
printf ("%s\n", $row["user_email"]);
}


The output will look like this


abcd@gmail.com

ggyy@gmail.com


In my python code i use
urllib2
to read the php and the python snippet look like this

response = urllib2.urlopen('http://192.168.0.168/useremail.php')
status = response.read()

fromaddr = "testing123@gmail.com"
toaddr = status
server.sendmail(fromaddr, toaddr)


In this case, the email always sent to the first email address only despite there are several email address retrieve from the php script.
Please help me to solve this problem.
Sorry to say that I am a beginner in programming.

Answer

sendmail() needs a list of mail addresses. So, you'll need to build that list with the response of urllib2.

Use splitlines() to return a list of the lines in the string.

i.e. :

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)

Hope it helps.

Comments