我正在尝试创建一个电子邮件机器人,它将从文件夹中随机向我发送一个pdf文件。虽然我的代码没有显示任何错误,但我没有收到任何邮件。如果你能告诉我哪里出了问题,我该怎么办,那会很有帮助。谢谢。
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
import os
import random
def send():
body = ""
sender_email = "email"
password = "my_password"
receiver_email = "email"
msg = MIMEMultipart()
msg['Subject'] = '[Email Test]'
msg['From'] = sender_email
msg['To'] = receiver_email
msg.attach(MIMEText(body, 'plain'))
path = "C:/Users/Asus/PycharmProjects/messenger_bot/files"
files = os.listdir(path)
index = random.randrange(0, len(files))
print(files[index])
attachment = open(os.path.join(path, random.choice(files)), 'rb')
payload = MIMEBase('application', 'octate-stream')
# payload = MIMEBase('application', 'pdf', Name=pdfname)
payload.set_payload(attachment.read())
# enconding the binary into base64
encoders.encode_base64(payload)
# add header with pdf name
payload.add_header('Content-Decomposition', 'attachment', filename=files)
msg.attach(payload)
# use gmail with port
session = smtplib.SMTP('smtp.gmail.com', 587)
# enable security
session.starttls()
# login with mail_id and password
session.login(sender_email, password)
text = msg.as_string()
session.sendmail(sender_email, receiver_email, text)
session.quit()
print('Mail Sent')
您确定发件人的电子邮件是正确的吗?将sender_ email从";电子邮件";到你的实际电子邮件,它应该工作
根据我从官方文档中收集的信息。您遇到的问题是,starttls将一个密钥文件和一个证书文件放在一起,或者单独使用一个上下文,而您没有给出。
尝试添加以下内容:
context = ssl.create_default_context()
然后将starttls((调用更改为
starttls(context=context)