You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Python3无法获取Gmail邮件,寻求可用实现代码

Fixing Your Gmail POP3 Email Fetching Code

Hey there, let's work through why your current Gmail fetch code isn't working and get it up and running properly! Gmail has specific security hoops to jump through, plus your original code cuts off before fully parsing the emails. Here's the breakdown:

First: Fix Gmail's Security Settings

Your code might fail just because Gmail isn't allowing POP3 access yet. Do these steps first:

  • Open Gmail, go to Settings > See all settings > Forwarding and POP/IMAP
  • Under "POP download", select "Enable POP for all mail" (or the option that fits your needs)
  • Save changes

Authentication Note:

  • If you have 2-Step Verification (2FA) turned on, you can't use your regular password—you need to create an App Password:
    1. Go to your Google Account > Security > App Passwords
    2. Pick "Mail" as the app and your device, then generate the 16-character app password to use in your code
  • If you don't have 2FA enabled, you might need to allow less secure apps (though Google recommends enabling 2FA + App Password instead for better security)

Complete, Working Code

Your original code stops short of parsing the email properly. Here's the full version that fetches, decodes, and displays your Gmail messages:

import poplib
from email import parser
from email.header import decode_header

SERVER = "pop.gmail.com"
USER = "your-email@gmail.com"
PASSWORD = "your-app-password-or-allowed-password"

# Connect to Gmail's POP3 SSL server (explicit port 995 avoids connection issues)
pop_conn = poplib.POP3_SSL(SERVER, 995)
pop_conn.user(USER)
pop_conn.pass_(PASSWORD)

# Get total number of messages
num_messages = len(pop_conn.list()[1])
print(f"Found {num_messages} messages in your inbox")

# Fetch and parse each message
for msg_num in range(1, num_messages + 1):
    # Retrieve message parts from the server
    response, msg_parts, _ = pop_conn.retr(msg_num)
    # Combine parts into a single string (decode bytes to UTF-8)
    msg_content = b"\n".join(msg_parts).decode('utf-8', errors='replace')
    # Parse the raw email content into a readable object
    msg = parser.Parser().parsestr(msg_content)
    
    # Decode the email subject (subjects are often encoded)
    subject, encoding = decode_header(msg['Subject'])[0]
    if isinstance(subject, bytes):
        subject = subject.decode(encoding or 'utf-8')
    
    # Get sender information
    sender = msg['From']
    
    print(f"\n--- Message {msg_num} ---")
    print(f"Subject: {subject}")
    print(f"From: {sender}")
    
    # Extract the plain text body of the email
    if msg.is_multipart():
        # Most emails are multipart—look for the plain text part
        for part in msg.walk():
            if part.get_content_type() == 'text/plain':
                body = part.get_payload(decode=True).decode('utf-8', errors='replace')
                print(f"Body Preview: {body[:200]}...")  # Print first 200 characters
                break
    else:
        # For non-multipart emails, get the payload directly
        body = msg.get_payload(decode=True).decode('utf-8', errors='replace')
        print(f"Body Preview: {body[:200]}...")

# Clean up the connection to the server
pop_conn.quit()

Key Improvements in This Code:

  • Explicitly uses port 995 for POP3 SSL (some connections fail without this)
  • Properly decodes raw byte data from the POP3 server into readable text
  • Handles encoded email subjects (a common source of garbled text)
  • Supports multipart emails (the standard for modern emails with text and HTML versions)
  • Adds proper cleanup with pop_conn.quit() to avoid leaving connections open

Once you've updated your Gmail settings and swapped in your correct credentials, this code should work smoothly!

内容的提问来源于stack exchange,提问作者John Bailey

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 03:47:12