I am trying to write a very basic email sending script. Here is my code ..
JavaScript
x
18
18
1
import smtplib
2
from email.message import EmailMessage
3
4
msg = EmailMessage()
5
msg.set_content("Test message.")
6
msg['Subject'] = "Test Subject!!!"
7
msg['From'] = "myemail@gmail.com"
8
9
email_list = ["xyz@gmail.com", "abc@gmail.com"]
10
11
for email in email_list:
12
msg['To'] = email
13
server = smtplib.SMTP(host='smtp.gmail.com', port=587)
14
server.starttls()
15
server.login("myemail@gmail.com", "mypassword")
16
server.send_message(msg)
17
server.quit()
18
the script should send mail to multiple recipients so, I need to change the msg['To']
field when iterating through loop But I get the following error in traceback bellow.
JavaScript
1
7
1
Traceback (most recent call last):
2
File "exp.py", line 66, in <module>
3
msg['To'] = email
4
File "/usr/lib/python3.8/email/message.py", line 407, in __setitem__
5
raise ValueError("There may be at most {} {} headers "
6
ValueError: There may be at most 1 To headers in a message
7
How do I solve ? Please help. Thank you..
Advertisement
Answer
Clean the ‘To’ property of the message.
JavaScript
1
9
1
for email in email_list:
2
msg['To'] = email
3
server = smtplib.SMTP(host='smtp.gmail.com', port=587)
4
server.starttls()
5
server.login("myemail@gmail.com", "mypassword")
6
server.send_message(msg)
7
server.quit()
8
del msg['To]
9
Below is the code that throws the exception: (Python385Libemailmessage.py)
JavaScript
1
18
18
1
def __setitem__(self, name, val):
2
"""Set the value of a header.
3
4
Note: this does not overwrite an existing header with the same field
5
name. Use __delitem__() first to delete any existing headers.
6
"""
7
max_count = self.policy.header_max_count(name)
8
if max_count:
9
lname = name.lower()
10
found = 0
11
for k, v in self._headers:
12
if k.lower() == lname:
13
found += 1
14
if found >= max_count:
15
raise ValueError("There may be at most {} {} headers "
16
"in a message".format(max_count, name))
17
self._headers.append(self.policy.header_store_parse(name, val))
18