Search code examples
python-3.xencode

AttributeError: 'bytes' object has no attribute 'encode' in python 3


email = '[email protected]'
send_email('Happy Hour Update',message,
            from_addr=GMAIL_LOGIN, to_addr=email)

I am getting an error AttributeError: 'bytes' object has no attribute 'encode'

def send_email(subject, message, from_addr=GMAIL_LOGIN, to_addr=GMAIL_LOGIN):
msg = MIMEText(message)
msg['Subject'] = subject
msg['From'] = from_addr
msg['To'] = to_addr
msg['Reply-To'] = '[email protected]'

Above is the send_email function it is referencing to, pointing to msg = MIMEText(message) Please help

if _charset is None:
        try:
            _text.encode('us-ascii')
            _charset = 'us-ascii'
        except UnicodeEncodeError:
            _charset = 'utf-8'

Above is the anaconda3 file it has referenced to in ~\anaconda3\lib\email\mime\text.py in init(self, _text, _subtype, _charset, policy)


Solution

  • The documentation explains charset encoding details: https://docs.python.org/3/library/email.mime.html#email.mime.text.MIMEText

    When adding headers, use e.g. msg.add_header('Subject', subject) rather than msg['Subject'] = subject