【问题标题】:Python module smtplib doesn't send mailPython 模块 smtplib 不发送邮件
【发布时间】:2020-04-14 10:03:25
【问题描述】:

我正在尝试编写一个使用 Gmail id 登录并向提供的 id 发送邮件的程序。

import smtplib

email = input('Enter your email\n')
password = input('Enter your password\n')
reciever = input("To whom you want to send?\n")
content = input("Enter content below:\n")




mail= smtplib.SMTP('smtp.gmail.com',587)
mail.ehlo()
mail.starttls()
mail.login(email,password)
mail.send_message(email,reciever,content)

但是当我执行程序时,我得到了这个错误......

Enter your email
soham.nandy2006@gmail.com
Enter your password
x
To whom you want to send?
soham.nandy@outlook.com
Enter content below:
HELLOOOO
Traceback (most recent call last):
  File "c:/Users/soham/Desktop/Python Crack/main.py", line 15, in <module>
    mail.send_message(email,reciever,content)
  File "C:\Users\soham\AppData\Local\Programs\Python\Python38-32\lib\smtplib.py", line 928, in send_message
    resent = msg.get_all('Resent-Date')
AttributeError: 'str' object has no attribute 'get_all'
PS C:\Users\soham\Desktop\Python Crack> 

P.S-出于安全问题,我写的是 x 而不是我的密码(在程序中密码是正确的)

【问题讨论】:

标签: python python-3.x


【解决方案1】:

当你使用send_message时,你需要传递MIMEMultipart对象,而不是字符串:

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

# collect data from user
email = input('Enter your email\n')
password = input('Enter your password\n')
reciever = input("To whom you want to send?\n")
content = input("Enter content below:\n")

# set up a server
mail = smtplib.SMTP('smtp.gmail.com', 587)
mail.ehlo()
mail.starttls()
mail.login(email, password)

# create and specify parts of the email
msg = MIMEMultipart()
msg['From'] = email
msg['To'] = reciever
msg['Subject'] = 'sample subject' # maybe you want to collect it as well?

msg.attach(MIMEText(content, 'plain'))

mail.send_message(msg)
mail.quit()

【讨论】:

  • msg = MIMEMultipart() 未定义
  • from email.mime.multipart import MIMEMultipartfrom email.mime.text import MIMEText。答案已编辑。
  • Traceback(最近一次调用最后一次):文件“c:/Users/soham/Desktop/Python Crack/main.py”,第 20 行,在 msg['Subject'] = subject # 也许你也想收集它? NameError: 名称“主题”未定义 PS C:\Users\soham>
  • 嗯,这是对您的建议,主题与邮件中的相关性非常高......删除此行或将其更改为:msg['Subject'] = 'test subject'
  • 哦,我后来想通了,非常感谢。感谢您的帮助。
【解决方案2】:

您使用了错误的功能来发送您的电子邮件。您应该使用mail.sendmail() 而不是mail.send_message()。不同之处在于争论的顺序,在第一个函数中,消息是一个字符串,在第二个函数中是一个Message 对象。

https://docs.python.org/3/library/smtplib.html#smtplib.SMTP.sendmail

【讨论】:

    猜你喜欢
    • 2021-04-26
    • 2022-07-21
    • 2021-01-20
    • 2019-11-01
    • 2011-11-06
    • 2013-11-05
    • 1970-01-01
    • 2010-10-07
    • 2023-03-10
    相关资源
    最近更新 更多