本人代码小白,基础几乎为零。在网上和chatgpt上查到了一些关于自动收发邮件的代码,想上手试试。使用QQ邮箱作为收发邮箱的时候可以运行代码,但使用163邮箱后遇到了问题。在站内搜索相应解决办法但奈何才疏学浅,看不太懂。在站内也搜了其他抓取163邮箱的代码,同样无法运行。想求助各位大佬看如何解决。代码及对应报错如下:
1.chatgpt写的代码:
import os
import imaplib
import email
from email.header import decode_header
import time
# 邮箱登录信息
email_address = "xxx@163.com"
password = "xxx"
# 登录邮箱
mail = imaplib.IMAP4_SSL("imap.163.com")
mail.login(email_address, password)
# 切换到收件箱文件夹
mail.select("inbox")
# 搜索未读邮件
result, data = mail.search(None, "UNSEEN")
if result == "OK":
for num in data[0].split():
result, data = mail.fetch(num, "(RFC822)")
raw_email = data[0][1]
msg = email.message_from_bytes(raw_email)
# 解析邮件中的附件
for part in msg.walk():
if part.get_content_maintype() == "multipart":
continue
if part.get("Content-Disposition") is None:
continue
filename = part.get_filename()
if filename:
# 解码文件名
filename = decode_header(filename)[0][0].decode()
print("Downloading:", filename)
# 创建保存附件的文件夹
attachment_folder = "D:/Email_Attachments"
if not os.path.isdir(attachment_folder):
os.mkdir(attachment_folder)
# 保存附件到指定文件夹
filepath = os.path.join(attachment_folder, filename)
with open(filepath, "wb") as f:
f.write(part.get_payload(decode=True))
print("Saved to:", filepath)
# 关闭邮箱连接
mail.logout()
此段代码运行报错为:
imaplib.IMAP4.error: command SEARCH illegal in state AUTH, only allowed in states SELECTED
2.我从站内一个大佬那找的代码。大佬自己做了一个叫poemail的库,具体代码如下:
import os
key = 'xxx'
msg_from = "xxx@163.com"
msg_to = "xx@qq.com"
msg_subject = '邮件主题'
content = ('111')
#pip install poemail
import poemail
poemail.receive.receive_email(key=key,
msg_from=msg_from,
msg_to='1',
output_path=r'D:\批量下载附件',
status="unseen")
此段代码运行报错为:
raise SMTPServerDisconnected("Connection unexpectedly closed")
smtplib.SMTPServerDisconnected: Connection unexpectedly closed
目前找了好多教程,都不太能解决我的问题。想求助站内大佬,看怎么修改或有什么解决办法。我的邮箱是mr0rabbits@163.com,希望能有大佬留言或联系我。万分感谢。