简体   繁体   中英

Python: can't get email to send to multiple recipients

I've got a script that gets some data from my website and emails me once a day. I'm trying to get this to send to more than one recipient, I've adapted the script with some code that I've found on here (in more than one solution) but I'm finding that it only sends an email to the first recipient on the list.

Here's an excerpt of what I'm using (bear in mind that the full version works 100% correctly when sending to one recipient)...

addr_to   = ['me@icloud.com', 'me2@icloud.com']
addr_from = 'darren@website.co.uk'

smtp_server = 'mail.com'
smtp_user   = 'darren@website.co.uk'
smtp_pass   = 'password'

msg = MIMEMultipart('alternative')
msg['To'] = " ,".join(addr_to)
msg['From'] = addr_from
msg['Subject'] = " Automated email"

When I send this to two of my own email addresses or if I put the same email address in twice, I only receive one email - the received email shows both email addresses in the 'to' field.

How do I get this to work properly?

msg['To'] needs to be a string while the recipients in sendmail(sender, recipients, message) needs to be a list:

s = smtplib.SMTP('servername')
addr_to   = ['me@icloud.com', 'me2@icloud.com']
addr_from = 'darren@website.co.uk'

msg = MIMEMultipart('alternative')
msg['Subject'] = "Automated email"
msg['From'] = addr_from
msg['To'] = ", ".join(addr_to)
s.sendmail(addr_from, addr_to, "bla")

I'd suggest to have a look at yagmail .

To send to multiple email addresses you can use the following:

import yagmail
yag = yagmail.SMTP()
yag.send(['me@icloud.com', 'me2@icloud.com'], "subject", "contents")

Problem solved!! USER ERROR!

Both email addresses were coming into my iCloud account, for some reason, my iPad chooses to only show me one email....not one thread with two identical emails in it, just one email! I tried again with one of the email addresses going to a completely separate account and it works fine!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM