I am trying to send an email using MIME
in python. Below is the code I am using :
JavaScript
x
31
31
1
from email.mime.text import MIMEText
2
from email.mime.multipart import MIMEMultipart
3
4
try:
5
raw_data = request.get_json()
6
pwd_email_id = raw_data['email']
7
log.error("Sending email to {}".format(pwd_email_id))
8
recipients = pwd_email_id
9
10
msg = MIMEMultipart()
11
12
msg['Subject'] = 'App Registered'
13
msg['From'] = 'xyz@gmail.com'
14
msg['To'] = email
15
16
message_text = "Dear " + pwd_email_id + "rnrnYour app has been registered successfully.rnBelow are the "
17
"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. "
18
"Do not share your app key with anyone.rnLet us know if you face any issues.rnrnThanks "
19
text = MIMEText(message_text)
20
msg.attach(text)
21
22
s = smtplib.SMTP('smtp.gmail.com', 587)
23
s.ehlo()
24
s.starttls()
25
s.ehlo()
26
s.login('xyz@gmail.com', '<password>')
27
s.sendmail("xyz@gmail.com", recipients, msg.as_string())
28
s.quit()
29
except Exception as e:
30
log.error("Exception in sending email {}".format(e))
31
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).