Search code examples
pythonpython-2.7mimemultipartsmtplib

Updating "To:" Email-Header in a while loop in python


Below is a code to send multiple emails to contacts loaded from a text file.

import time
    from time import sleep

    from email.mime.multipart import MIMEMultipart
    from email.mime.text import MIMEText
    import smtplib

    uname = #[email protected]
    name = "KTester"
    password = #password1
    server = smtplib.SMTP('smtp.gmail.com: 587')
    server.starttls()
    server.login(uname, password)
    message="Test"

    msg = MIMEMultipart('Alternative')
    f= open("list.txt","r")clear

    if f.mode == "r":
      cont = f.read().splitlines()
      for x in cont:
        print time.ctime()

        msg['Subject'] = "Test Mail - cripted Sample"
        msg['To'] = x
        msg['From'] = name+"\x0A\x0D"+uname
        msg.attach(MIMEText(message, 'html'))

        print "successfully sent email to %s:" % (msg['To'])

    f.close()
    server.quit()

OUTPUT: enter image description here

In this case, the first compilation is the expected outcome, which we can get if we use print "successfully sent email to %s:" % (x)

The Variable 'x' changes its value at the end of each iteration.

However, msg['To'] = x does not accept value from second iteration of the loop(The second code run above).

Assignment operation does not work on the message object.

Kindly help with whats going wrong. Thanks!


Solution

  • This behaviour is by design.

    Reassigning to msg['to'] doesn't overwrite the existing mail header, it adds another. To send the existing message to a new address you need to delete the 'to' header before setting it.

    del msg['to']
    msg['to'] = '[email protected]'
    

    This applies to other headers too. From the docs for Message.__setitem__:

    Note that this does not overwrite or delete any existing header with the same name. If you want to ensure that the new header is the only one present in the message with field name name, delete the field first, e.g.:

    del msg['subject']

    msg['subject'] = 'Python roolz!'