最近需要用到微软收件,翻遍了论坛都没有能用的
于是一不做二不休,上谷歌翻了很多,copy出一下代码,也能将就用了。
import imaplib import email from email.header import decode_header # 登录信息 username = " [email protected]" password = "xxx" imap_server = "outlook.office365.com" # 连接到IMAP服务器 imap = imaplib. IMAP4_SSL (imap_server )imap. login (username, password ) # 选择INBOX文件夹或其他文件夹 # imap. select ("INBOX" ) # 如果要读取垃圾邮件文件夹,使用 imap. select ("Junk" )imap. select ("Junk" ) # 获取所有邮件ID status, messages = imap. search (None, messages = messages [0 ]. split () # 要读取的最新邮件数量 N = 3 # 遍历最近的N封邮件 for i in messages [-N: ]: res, msg = imap. fetch (i, " (RFC822 )" )for response in msg: if isinstance (response, tuple ): # 获取原始邮件数据 msg = email. message_from_bytes (response [1 ]) # 解码邮件的主题 subject, encoding = decode_header (msg ["Subject" ])[0 ]if isinstance (subject, bytes ): # 如果主题是字节类型,解码为字符串 subject = subject. decode (encoding if encoding else print ("Subject:", subject ) # 获取发件人信息 from_ = msg. get ("From" )print ("From:", from_ ) # 如果邮件是多部分的 if msg. is_multipart (): # 遍历邮件的各个部分 for part in msg. walk (): # 检查内容类型 content_type = part. get_content_type ()content_disposition = str (part. get ("Content-Disposition" )) # 获取邮件正文 if "attachment" not in content_disposition: # 如果是邮件的正文 if content_type == "text/plain" or content_type == "text/html": payload = part. get_payload (decode=True )charset = part. get_content_charset () # 获取字符集 if charset: payload = payload. decode (charset )if content_type == "text/plain": print ("Text content:", payload )elif content_type == "text/html": print ("HTML content:", payload )else: # 如果邮件不是多部分的(即只有一部分) content_type = msg. get_content_type ()payload = msg. get_payload (decode=True )charset = msg. get_content_charset ()if charset: payload = payload. decode (charset )if content_type == "text/plain": print ("Text content:", payload )elif content_type == "text/html": print ("HTML content:", payload ) # 关闭IMAP连接 imap. close ()imap. logout ()
|