'Loop keys in dictionary to send an email (Python)
I am trying to loop over a key in a dictionary that has 4 items in total. However, it doesn't go through all of them and only shows the key of the last item.
Prueba = {"A":"###@gmail.com",
"B":"###@gmail.com",
"C":"###@gmail.com"}
with smtplib.SMTP('smtp.gmail.com',587) as zero:
zero.ehlo()
zero.starttls()
zero.ehlo()
zero.login(Emaill, Passs)
for keyyy in Prueba.keys():
subject = 'Subject {0}'.format(keyyy)
for keyyy in Prueba.keys():
body = 'Body {0}. Body2 {1}.'.format(keyyy,keyyy)
msg = f'subject: {subject}\n\n{body}'
for keyy in pp.Prueba:
zero.sendmail(Emaill,Prueba[keyy],msg)
When the email is sent. All the emails only show the key of the last item ("C"). I want to show each email with its respective key.
Solution 1:[1]
What you are doing is use one loop for every action you wanna do, instead do one loop for all the actions:
Prueba = {"A":"###@gmail.com",
"B":"###@gmail.com",
"C":"###@gmail.com"}
with smtplib.SMTP('smtp.gmail.com',587) as zero:
zero.ehlo()
zero.starttls()
zero.ehlo()
zero.login(Emaill, Passs)
for keyyy in Prueba.keys():
subject = 'Subject {0}'.format(keyyy)
body = 'Body {0}. Body2 {1}.'.format(keyyy,keyyy)
msg = f'subject: {subject}\n\n{body}'
zero.sendmail(Emaill,Prueba[keyy],msg)
This should have the right subject and body in the right mail. Haven't actually tested the code yet, but that's the way it should work.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | jonii |
