Search code examples
pythonsendmailsmtplib

smtplib: Why do the recipients in "To" field receive the mail twice?


I searched about this quite a lot, but could not fix the issue in my script. So finally, I decided to post it here.

Here's the code snippet:

fromaddr = "someValidAddress@xyz.com"
cc = ['SomeEmailAlias@xyz.com']
toaddr = ""
    msg = MIMEMultipart()
    toaddrlist = list(toaddr.split(',')) #As sendmail() accepts the list of recipients only in list form.
    toaddrlist += (cc,)
    msg['From'] = fromaddr
    msg['To'] = toaddr
    msg['Cc'] = ', '.join(cc)
    msg['Date'] = formatdate(localtime=True)
    msgHtml = MIMEText(html, 'html')
    msg.attach(msgHtml)
    msg['Subject'] = "Test mail"
    server = "someMailServer.xyz.com"
    smtp = smtplib.SMTP(server, 25)
    smtp.sendmail(fromaddr, toaddrlist, msg.as_string())
    smtp.close() #Close the SMTP server connection.

I'm aware and I've ensured that msg['To'] accepts a string value (toaddr), whereas toaddrlist in sendmail() should be a list.

Catch: If I remove the line toaddrlist += (cc,), then the mail does not get delivered twice to the recipients in "To" field, but the mail does not get delivered to the Cc alias.

Please help.


Solution

  • When the line toaddrlist += (cc,) is evaluated, the value of toaddrlist in your case is :

    ["", ["SomeEmailAlias@xyz.com"]]
    

    and it's wrong because toaddrlist must be a list of strings not a list containing some lists.

    So the solution is to change :

     toaddrlist += (cc,)
    

    to

    toaddrlist += cc
    

    or the recommended form (the pythonic way) :

    toaddrlist.extend(cc)