首页 > 解决方案 > 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 而不是我的密码(在程序中密码是正确的)

标签: pythonpython-3.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()

推荐阅读