python读取163邮箱失败,求助

本人代码小白,基础几乎为零。在网上和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,希望能有大佬留言或联系我。万分感谢。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值