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 + "\r\n\r\nYour app has been registered successfully.\r\nBelow are the " \
"details:\r\n\r\n\r\n1.App Name: " + "app_name" + "\r\n2.App Key: " + "app_key" + "\r\n3.Registered Date: " + "registered_date" + "\r\n4.Expiry Date: " + "expiry_date" + "\r\n\r\n\r\nUse app name and app key as headers to make calls to services. " \
"Do not share your app key with anyone.\r\nLet us know if you face any issues.\r\n\r\nThanks "
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
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).