Skip to content
Advertisement

Error “email has no attribute encode” sending email in python

I am trying to send an email using MIME in python. Below is the code I am using :

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

try:
    raw_data = request.get_json()
    pwd_email_id = raw_data['email']
    log.error("Sending email to {}".format(pwd_email_id))
    recipients = pwd_email_id

    msg = MIMEMultipart()

    msg['Subject'] = 'App Registered'
    msg['From'] = 'xyz@gmail.com'
    msg['To'] = email

    message_text = "Dear " + pwd_email_id + "rnrnYour app has been registered successfully.rnBelow are the " 
                   "details:rnrnrn1.App Name: " + "app_name" + "rn2.App Key: " + "app_key" + "rn3.Registered Date: " + "registered_date" + "rn4.Expiry Date: " + "expiry_date" + "rnrnrnUse app name and app key as headers to make calls to  services. " 
                                                                                                                                                                                             "Do not share your app key with anyone.rnLet us know if you face any issues.rnrnThanks "
    text = MIMEText(message_text)
    msg.attach(text)

    s = smtplib.SMTP('smtp.gmail.com', 587)
    s.ehlo()
    s.starttls()
    s.ehlo()
    s.login('xyz@gmail.com', '<password>')
    s.sendmail("xyz@gmail.com", recipients, msg.as_string())
    s.quit()
except Exception as e:
    log.error("Exception in sending  email {}".format(e))

but its giving me the below error:

module email has no attribute encode

at line:

s.sendmail("xyz@gmail.com", recipients, msg.as_bytes())

I am not able to understand why its giving this error. I have tried only using msg instead of msg.as_bytes() but its still the same. Can anyone please point out the issue in the code. Thanks

Advertisement

Answer

Looks like a typo to me.

You have assigned the module email when calling msg['To'] = email. That module must have been imported outside of the shared code (check your imports, it’s probably there!). msg.as_string() is simply having trouble parsing the module object (since modules don’t have the encode attribute).

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement