在 python 中发送电子邮件时出错 "email has no attribute encode"

Error "email has no attribute encode" sending email in python

我正尝试在 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() 但它仍然是一样的。谁能指出代码中的问题。谢谢

我觉得是打字错误。

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

我刚遇到同样的问题。这个错误是因为在msg['To']中输入的是变量email,而你并没有创建这个变量。 OBS:var email 需要有你想发送消息的人的电子邮件。这样,就可以将消息从您的电子邮件发送到其他人的电子邮件中。