Python script send out more emails that it supposed to send

Multi tool use


Python script send out more emails that it supposed to send
I tried the solution for the post here, but it didn't help.
Part of my python script sends out email to recipients. When I run the code in my Pycharm it sends out exactly 3 emails which is the number of email addresses for my test case and the number which it suppose to send out. However, when I try to run it on my raspberry pi it randomly sends out the emails and I cannot find a pattern of the difference number of emails that it sends out.
So, there is a list called 'toAddrs' which saves the email address of recipients. I tried the following to ways once using a for loop and once without a for loop. But both of these send an arbitrary number of emails.
#subject, fromAddr, mainbody and password are already defined
msg = MIMEMultipart('')
msg.attach(MIMEText(mainbody, 'plain'))
msg['Subject'] = subject
msg['From'] = fromAddr
msg['To'] = toAddrs
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(fromAddr, password)
for i in range(len(toAddrs)):
server.sendmail(fromAddr, toAddrs[i], msg.as_string())
server.quit()
and another one is:
#subject, fromAddr, mainbody and password are already defined
msg = MIMEMultipart('')
msg.attach(MIMEText(mainbody, 'plain'))
msg['Subject'] = subject
msg['From'] = fromAddr
msg['To'] = ' ,'.join(toAddrs)
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(fromAddr, password)
server.sendmail(fromAddr, toAddrs, msg.as_string())
server.quit()
I cannot find what might be wrong. I will appreciate any help.
', '.join(toAddress) is a string of the form
In your first example, what exactly does
join(toAddress)
do? You must have defined a join
function somewhere in your code, or else you would be getting a NameError
– Joel
2 days ago
join(toAddress)
join
NameError
Possible duplicate of Python SMTP: emails being combined into one
– snakecharmerb
2 days ago
Try calling
print(', '.join(toAddress))
and you'll see what I mean.– Joel
yesterday
print(', '.join(toAddress))
@Joel so you're saying if there is n recipients, so there is going to be n^2 emails send out altogether? If so, do you know how to fix it?
– Luna2
yesterday
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
In your second example,
', '.join(toAddress) is a string of the form
'email1@website.com, email2@website.com, ..., emailn@website.com'`, where there are n emails in the string. So this just sends the email to everyone every time an email is sent.– Joel
2 days ago