Skip to content
Advertisement

ValueError: There may be at most 1 To headers in a message

I am trying to write a very basic email sending script. Here is my code ..

import smtplib
from email.message import EmailMessage

msg = EmailMessage()
msg.set_content("Test message.")
msg['Subject'] = "Test Subject!!!"
msg['From'] = "myemail@gmail.com"

email_list = ["xyz@gmail.com", "abc@gmail.com"]

for email in email_list:
    msg['To'] = email
    server = smtplib.SMTP(host='smtp.gmail.com', port=587)
    server.starttls()
    server.login("myemail@gmail.com", "mypassword")
    server.send_message(msg)
    server.quit()

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.

Traceback (most recent call last):
  File "exp.py", line 66, in <module>
    msg['To'] = email
  File "/usr/lib/python3.8/email/message.py", line 407, in __setitem__
    raise ValueError("There may be at most {} {} headers "
ValueError: There may be at most 1 To headers in a message

How do I solve ? Please help. Thank you..

Advertisement

Answer

Clean the ‘To’ property of the message.

for email in email_list:
    msg['To'] = email
    server = smtplib.SMTP(host='smtp.gmail.com', port=587)
    server.starttls()
    server.login("myemail@gmail.com", "mypassword")
    server.send_message(msg)
    server.quit()
    del msg['To]

Below is the code that throws the exception: (Python385Libemailmessage.py)

def __setitem__(self, name, val):
    """Set the value of a header.

    Note: this does not overwrite an existing header with the same field
    name.  Use __delitem__() first to delete any existing headers.
    """
    max_count = self.policy.header_max_count(name)
    if max_count:
        lname = name.lower()
        found = 0
        for k, v in self._headers:
            if k.lower() == lname:
                found += 1
                if found >= max_count:
                    raise ValueError("There may be at most {} {} headers "
                                     "in a message".format(max_count, name))
    self._headers.append(self.policy.header_store_parse(name, val))
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement