Search code examples
pythonpython-3.xemailutf-8smtplib

TypeError: 'utf8' is an invalid keyword argument for Compat32 smtplib email error message


I have been able to send personalized emails using the script below before, but all of a sudden I am getting the following error.

I am trying to read names and email ID's from a file and send a personalized email to each person. It picks a random subject from the list of subjects and uses a random delay. It worked fine until now but it won't now.

*Traceback (most recent call last):
  File "C:/myprojects/normal_email.py", line 64, in <module>
    main()
  File "C:/myprojects/normal_email.py", line 57, in main
    smtp.send_message(msg)
  File "C:\Python\lib\smtplib.py", line 964, in send_message
    bytesmsg, policy=msg.policy.clone(utf8=True))
  File "C:\Python\lib\email\_policybase.py", line 72, in clone
    raise TypeError(
TypeError: 'utf8' is an invalid keyword argument for Compat32*

import csv
from string import Template
import smtplib
import random
import time
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart




template_file = r'C:\Users\91880\Desktop\template.txt'
filename = r'C:\Users\91880\Downloads\2307.csv'


#  reads the file and returns the names, emails in a list
def get_contacts(file):
    names_list = []
    emails_list = []
    with open(file, 'r') as mail_data:
        data = csv.reader(mail_data)
        for details in data:
            names_list.append(details[0])
            emails_list.append(details[1])
    return names_list, emails_list


# reads the template from a text file and returns
def get_template(file):
    with open(file, 'r') as template_info:
        template_data = template_info.read()
    return Template(template_data)


def main():
    email_user = 'myemail@mail.com'
    password = 'mypassword'

    subs = ['Hi', 'Hello']

    names, emails = get_contacts(filename)
    template = get_template(template_file)

    with smtplib.SMTP('smtp.office365.com', '587') as smtp:
        smtp.ehlo()
        smtp.starttls()
        smtp.ehlo()
        smtp.login(email_user, password)
        for name, email in zip(names, emails):
            subject = random.choice(subs)
            number = random.randint(10, 30)
            msg = MIMEMultipart()
            message = template.substitute(name=name.title())
            msg['From'] = email_user
            msg['To'] = email
            msg['Subject'] = subject
            msg.attach(MIMEText(message, 'html'))
            smtp.send_message(msg)
            print(f'sent email to {name} at {email}')
            del msg
            time.sleep(number)


if __name__ == '__main__':
    main()

Solution

  • This error occurs because there is at least one non-ascii character in one of the "to" or "from" addresses. It should be possible to fix it by setting the policy on the message to email.policy.default:

    from email import policy
    
    ...
    
    msg = MIMEMultipart(policy=policy.default)
    

    The newer EmailMessage/EmailPolicy API is preferred over the old email.mime tools since Python 3.6. Using the preferred tools, the code would look like this:

    from email.message import EmailMessage
    from email import policy
    
    ...
    
                msg = EmailMessage(policy=policy.default)
                message = template.substitute(name=name.title())
                msg['From'] = email_user
                msg['To'] = email
                msg['Subject'] = subject
                msg.set_content(message, subtype='html')
                smtp.send_message(msg)
    

    For absolute RFC compatibility, you might consider setting the policy to SMTP, to generate \r\n line endings.