无法连接到python上的imap服务器

2024-05-15 01:53:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我是一个网络专业的学生,几乎没有编程经验,我手头有一个简单的项目,我需要做一个简单的通知,当一封电子邮件到达gmail时通知用户。在过去的几周里,我一直在努力让这件事发挥作用,我真的陷入困境,苦苦挣扎。我正在使用下面的代码,我认为问题是身份验证位,我无法连接到服务器。感谢所有的帮助。在

import imaplib
import re
import time
import subprocess

## enter your account details bellow!
imapServer = "imap.gmail.com"
port = "993"
username = "example@gmail.com"
password = "password"

##how often to check ? give interval in seconds! Checking too often might performance and stability.
checkInterval = 120

Mailbox = imaplib.IMAP4_SSL(imapServer, port)
rc,resp = Mailbox.login(username,password)
if rc == 'OK':
    print("Connected to mail-server " + imapServer)
rc, message = Mailbox.status('INBOX', "(UNSEEN)")
unreadCount = int(re.search("UNSEEN (\d+)",str( message[0])).group(1))
oldValue = 0
file = open("%sytemdrive%\Windows\Temp\mailnotify.tmp", "w+")
file.write(str(unreadCount))
file.close
while(1):
    rc, message = Mailbox.status('INBOX', "(UNSEEN)")
unreadCount = int(re.search("UNSEEN (\d+)",str( message[0])).group(1))
file = open("%sytemdrive%\Windows\Temp\mailnotify.tmp", "w+")
oldValue = int(file.readline())
file.close()
if (unreadCount>oldValue):
    subprocess.call(["notify-send", "-u", "low", "low", "t", "5000", "New email!", "New email!",
                     "You have " + str(unreadCount) + " unread " + "emails!" if unreadCount > 1 else "email!",
                     "--icon=email"])
    if oldValue != unreadCount:
        file = open("%sytemdrive%\Windows\Temp\mailnotify.tmp", "w+")
    file.write(str(unreadCount))
    file.close()
    time.sleep(checkInterval)
else :
    print('Fail to connect')
    Mailbox.logout()
    file.remove()

Tags: importremessageifemailpasswordgmailfile

热门问题