python - Python 模块 smtplib 不发送邮件
问题描述
我正在尝试编写一个使用 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>
PS-出于安全问题,我正在写 x 而不是我的密码(在程序中密码是正确的)
解决方案
使用时需要传递MIMEMultipart
对象,而不是字符串send_message
:
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()
推荐阅读
- javascript - 如何删除使用 jquery 添加的样式属性
- ajax - 来自 API (Ajax) 的 Laravel 消息
- java - 将 Activity ktx 与 viewmodel 和 java 一起使用
- python - 您如何识别用于输出目的的稀疏张量?
- c++ - 这在 C++ 中是什么意思?
- flutter - `didChangeDependencies` 中的提供者不更新数据
- masstransit - 配置更多时,MassTransit 仅批处理 10
- python - python中套接字编程期间的错误
- scala - 为什么 super 的这种用法会产生这个结果
- node.js - 如何在有多个数据库的项目中使用 $lookup?