错误“电子邮件没有属性编码”在python中发送电子邮件

时间:2020-07-20 14:51:21

标签: python email mime

我正在尝试在Python中使用MIME发送电子邮件。下面是我正在使用的代码:

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))

但是它给了我以下错误:

module email has no attribute encode

在线:

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

我不明白为什么会出现此错误。我尝试仅使用msg而不是msg.as_bytes(),但仍然相同。任何人都可以在代码中指出问题。谢谢

1 个答案:

答案 0 :(得分:1)

对我来说像错字。

调用email时,您已经分配了模块msg['To'] = email。该模块必须已从共享代码之外导入(检查您的导入,可能在这里!)。 msg.as_string()只是在解析模块对象时遇到麻烦(因为模块没有encode属性)。

相关问题