qq郵箱操作
// 郵箱配置信息
// 注意:使用QQ郵箱需要先開啟IMAP服務并獲取授權碼
// 設置方法:登錄QQ郵箱 -> 設置 -> 賬戶 -> 開啟IMAP/SMTP服務 -> 生成授權碼
服務器操作
fetchmail 同步QQ郵箱
nginx搭建web顯示本地同步過來的郵箱
ssh端瀏覽郵箱
通過python腳本實現其他用戶登錄可瀏覽郵件
騰訊云
dns轉給cloudflare
cloudflare
信件全局轉發到QQ
AAAA解析到物理機IPV6
演示站點 fengche.site
博客 xoxome.online
下面是ssh端服務器腳本
#!/usr/bin/env python3
# -*- coding: utf-8 -*-import os
import sys
import email
import email.header
import email.utils
import datetime
import subprocess
import tempfile# 郵件目錄
MAIL_DIR = "/home/y/Maildir/INBOX/new/new"def clear_screen():"""清屏"""os.system("clear")def decode_header(header):"""解碼郵件頭部信息"""if not header:return "未知"decoded_header = email.header.decode_header(header)result = ""for text, charset in decoded_header:if isinstance(text, bytes):try:if charset:result += text.decode(charset)else:result += text.decode("utf-8", "replace")except:result += text.decode("utf-8", "replace")else:result += textreturn resultdef get_email_info(mail_file):"""獲取郵件信息"""with open(mail_file, "rb") as f:msg = email.message_from_binary_file(f)from_addr = decode_header(msg.get("From", "未知"))to_addr = decode_header(msg.get("To", "未知"))subject = decode_header(msg.get("Subject", "未知"))date_str = msg.get("Date", "")try:date = email.utils.parsedate_to_datetime(date_str)date_formatted = date.strftime("%Y-%m-%d %H:%M:%S")except:date_formatted = date_strreturn {"from": from_addr,"to": to_addr,"subject": subject,"date": date_formatted}def html_to_text(html_content):"""將HTML轉換為可讀文本"""# 使用臨時文件保存HTML內容with tempfile.NamedTemporaryFile(suffix='.html', delete=False) as f:f.write(html_content.encode('utf-8'))temp_filename = f.nametry:# 嘗試使用w3m將HTML轉換為文本 try:result = subprocess.run(['w3m', '-dump', temp_filename], capture_output=True, text=True, check=True)text = result.stdoutexcept (subprocess.SubprocessError, FileNotFoundError):# 如果w3m不可用,嘗試使用lynxtry:result = subprocess.run(['lynx', '-dump', '-force_html', temp_filename],capture_output=True, text=True, check=True)text = result.stdoutexcept (subprocess.SubprocessError, FileNotFoundError):# 如果lynx也不可用,使用簡單的HTML標簽移除text = html_content# 移除常見HTML標簽tags_to_remove = ['<html>', '</html>', '<body>', '</body>', '<head>', '</head>','<script>', '</script>', '<style>', '</style>']for tag in tags_to_remove:text = text.replace(tag, '')# 將<br>和<p>替換為換行符text = text.replace('<br>', '\n').replace('<p>', '\n').replace('</p>', '\n')# 移除其他HTML標簽in_tag = Falseresult = ""for char in text:if char == '<':in_tag = Trueelif char == '>':in_tag = Falseelif not in_tag:result += chartext = resultreturn textfinally:# 清理臨時文件try:os.unlink(temp_filename)except:passdef extract_email_content(mail_file):"""提取郵件內容"""with open(mail_file, "rb") as f:msg = email.message_from_binary_file(f)content = ""html_content = ""if msg.is_multipart():for part in msg.walk():content_type = part.get_content_type()content_disposition = part.get("Content-Disposition", "")# 忽略附件if "attachment" in content_disposition:continue# 獲取文本內容if content_type == "text/plain" and not content:payload = part.get_payload(decode=True)if payload:charset = part.get_content_charset()try:if charset:content += payload.decode(charset)else:content += payload.decode("utf-8", "replace")except:content += payload.decode("utf-8", "replace")# 獲取HTML內容elif content_type == "text/html" and not html_content:payload = part.get_payload(decode=True)if payload:charset = part.get_content_charset()try:if charset:html_content += payload.decode(charset)else:html_content += payload.decode("utf-8", "replace")except:html_content += payload.decode("utf-8", "replace")else:# 非多部分郵件content_type = msg.get_content_type()payload = msg.get_payload(decode=True)if payload:charset = msg.get_content_charset()try:decoded = payload.decode(charset if charset else "utf-8", "replace")if content_type == "text/plain":content = decodedelif content_type == "text/html":html_content = decodedexcept:content = payload.decode("utf-8", "replace")# 如果有HTML內容但沒有純文本內容,轉換HTML為文本if html_content and not content:content = html_to_text(html_content)# 如果沒有任何內容if not content and not html_content:content = "【無法解析的郵件內容】"return content, html_contentdef list_emails():"""列出郵件"""clear_screen()print("歡迎使用郵件查看系統")print("=======================")print()if not os.path.isdir(MAIL_DIR):print("郵件目錄不存在: " + MAIL_DIR)input("按Enter鍵退出...")sys.exit(1)mail_files = []try:# 獲取所有郵件文件,按修改時間排序mail_files = sorted([f for f in os.listdir(MAIL_DIR) if os.path.isfile(os.path.join(MAIL_DIR, f))],key=lambda x: os.path.getmtime(os.path.join(MAIL_DIR, x)),reverse=True)except Exception as e:print("讀取郵件目錄出錯: " + str(e))input("按Enter鍵退出...")sys.exit(1)if not mail_files:print("沒有新郵件")print("按Enter鍵同步郵件,按q退出:")choice = input().strip()if choice.lower() != "q":sync_mail()return list_emails() # 重新加載郵件列表else:sys.exit(0)print("找到 " + str(len(mail_files)) + " 封新郵件:")print()# 顯示最多5封郵件displayed_files = []for i, mail_file in enumerate(mail_files[:5]):full_path = os.path.join(MAIL_DIR, mail_file)try:info = get_email_info(full_path)displayed_files.append(mail_file)print(str(i+1) + ") " + mail_file)print(" 從: " + info["from"])print(" 主題: " + info["subject"])print(" 日期: " + info["date"])print()except Exception as e:print("讀取郵件 " + mail_file + " 出錯: " + str(e))print()return displayed_filesdef sync_mail():"""同步郵件"""clear_screen()print("正在使用y用戶權限同步郵件...")try:# 使用sudo以y用戶身份運行fetchmailresult = subprocess.run(['sudo', '-u', 'y', 'fetchmail', '-v'], capture_output=True, text=True)output = result.stdouterror = result.stderrif output:print(output)if error:print()print()# 檢查是否成功同步了新郵件if "reading message" in (output or "") or "messages" in (output or ""):print("成功同步了新郵件!")else:print("沒有新郵件或同步失敗。")except Exception as e:print("同步郵件出錯: " + str(e))print()input("按Enter鍵繼續...")def view_email(mail_file):"""查看郵件內容"""clear_screen()full_path = os.path.join(MAIL_DIR, mail_file)try:# 獲取郵件信息info = get_email_info(full_path)print("郵件: " + mail_file)print("=======================")print("從: " + info["from"])print("收件人: " + info["to"])print("主題: " + info["subject"])print("日期: " + info["date"])print("=======================")print()# 提取郵件內容text_content, html_content = extract_email_content(full_path)if html_content:print("郵件內容 (轉換自HTML):")print("=======================")print(text_content)print("=======================")print()print("選項: 1) 返回郵件列表 2) 查看原始HTML 3) 同步郵件 [1-3]:")view_choice = input().strip()if view_choice == "2":# 使用臨時文件顯示HTMLwith tempfile.NamedTemporaryFile(suffix='.html', delete=False) as f:f.write(html_content.encode('utf-8'))temp_filename = f.nametry:# 嘗試使用不同的HTML查看器browsers = [['w3m', temp_filename],['lynx', temp_filename],['less', temp_filename]]for browser in browsers:try:subprocess.run(browser)breakexcept (subprocess.SubprocessError, FileNotFoundError):continuefinally:os.unlink(temp_filename)elif view_choice == "3":sync_mail()else:print("郵件內容:")print("=======================")print(text_content)print("=======================")print()print("選項: 1) 返回郵件列表 2) 同步郵件 [1-2]:")view_choice = input().strip()if view_choice == "2":sync_mail()return Trueexcept Exception as e:print("查看郵件出錯: " + str(e))print()input("按Enter鍵返回...")return Falsedef main():"""主函數"""while True:displayed_files = list_emails()print("輸入郵件編號查看內容,按Enter查看最新郵件,按s同步郵件,按q退出:")choice = input().strip()if choice.lower() == "q":print("謝謝使用,再見!")breakelif choice.lower() == "s":sync_mail()continuemail_to_view = Noneif not choice or choice == "1":# 查看最新郵件if displayed_files:mail_to_view = displayed_files[0]elif choice.isdigit():# 查看選定郵件idx = int(choice) - 1if 0 <= idx < len(displayed_files):mail_to_view = displayed_files[idx]else:print("無效選擇!")input("按Enter鍵繼續...")continueelse:print("無效選擇!")input("按Enter鍵繼續...")continueif mail_to_view:view_email(mail_to_view)if __name__ == "__main__":# 檢查并安裝必要的HTML渲染工具try:for pkg in ['w3m', 'lynx']:try:subprocess.run(['which', pkg], check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)breakexcept:passexcept:passtry:main()except KeyboardInterrupt:print("\n程序已退出")sys.exit(0)except Exception as e:print("程序發生錯誤: " + str(e))input("按Enter鍵退出...")sys.exit(1)