使用Python访问自己的Gmail邮箱

如何使用Python访问Gmail邮箱

在本教程中,我们将详细介绍如何使用Python访问Gmail邮箱。通过本教程,你将学会如何设置Gmail API、编写Python代码以及获取邮件信息。

目录

  1. 准备工作
  2. 设置Gmail API
  3. 安装Python库
  4. 编写Python代码
  5. 运行代码
  6. 常见问题及解决方法
  7. 总结

准备工作

在开始之前,你需要确保以下几点:

  • 拥有一个Google账户。
  • 安装了Python 3.6或更高版本。
  • 安装了pip包管理工具。

设置Gmail API

1. 创建Google Cloud项目

  1. 访问 Google Cloud Console
  2. 点击“创建项目”按钮,输入项目名称,然后点击“创建”。

2. 启用Gmail API

  1. 在Google Cloud Console中,导航到“API和服务” > “库”。
  2. 在搜索框中输入“Gmail API”,然后点击“Gmail API”。
  3. 点击“启用”按钮以启用Gmail API。

3. 配置OAuth同意屏幕

  1. 在Google Cloud Console中,导航到“API和服务” > “OAuth同意”。
  2. 选择“外部”作为用户类型,然后点击“创建”。
  3. 填写应用名称、用户支持邮箱、开发者联系信息等必填字段。
  4. 在“测试用户”部分,添加你的Google账户邮箱地址。
  5. 点击“保存并继续”完成配置。

4. 创建OAuth 2.0凭据

  1. 在Google Cloud Console中,导航到“API和服务” > “凭据”。
  2. 点击“创建凭据”按钮,选择“OAuth客户端ID”。
  3. 选择“桌面应用”作为应用类型,然后点击“创建”。
  4. 下载凭据文件(credentials.json)并保存到你的项目目录中。

安装Python库

你需要安装以下Python库来访问Gmail API:

pip install --upgrade google-auth google-auth-oauthlib google-auth-httplib2 google-api-python-client

编写Python代码

以下是一个示例代码,用于获取Gmail邮箱中的前10封邮件:

import os.path
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build

# 如果修改了SCOPES,请删除token.json文件。
SCOPES = ['https://www.googleapis.com/auth/gmail.readonly']

def get_credentials():
    """获取并保存用户凭据。"""
    creds = None
    if os.path.exists('token.json'):
        creds = Credentials.from_authorized_user_file('token.json', SCOPES)
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
        with open('token.json', 'w') as token:
            token.write(creds.to_json())
    return creds

def list_messages(service, user_id='me', max_results=10):
    """列出用户邮箱中的邮件。"""
    results = service.users().messages().list(userId=user_id, maxResults=max_results).execute()
    messages = results.get('messages', [])
    return messages

def get_message(service, user_id, msg_id):
    """获取邮件内容。"""
    message = service.users().messages().get(userId=user_id, id=msg_id, format='full').execute()
    return message

def main():
    creds = get_credentials()
    service = build('gmail', 'v1', credentials=creds)

    messages = list_messages(service)
    for msg in messages:
        message = get_message(service, 'me', msg['id'])
        print(f"Message ID: {message['id']}")
        print(f"Snippet: {message['snippet']}")
        print('-' * 50)

if __name__ == '__main__':
    main()

运行代码

将代码保存为gmail.py,然后运行它:

python gmail.py

首次运行时,系统会提示你授权访问Gmail账户。授权后,程序将输出前10封邮件的ID和摘要。

常见问题及解决方法

1. 403: access_denied

  • 原因:通常是由于OAuth同意屏幕配置问题或未启用Gmail API。
  • 解决方法
    • 确保已在Google Cloud Console中启用Gmail API。
    • 确保OAuth同意屏幕已正确配置,并添加了测试用户。
    • 删除token.json文件并重新运行代码以重新授权。

2. 重定向URI不匹配

  • 原因:Google Cloud Console中配置的重定向URI与代码中使用的URI不匹配。
  • 解决方法:确保重定向URI已正确配置。

3. 访问令牌过期

  • 原因token.json文件中的访问令牌已过期。
  • 解决方法:删除token.json文件并重新运行代码以重新授权。

总结

通过本教程,你学会了如何使用Python访问Gmail邮箱。我们详细介绍了如何设置Gmail API、安装Python库、编写代码以及解决常见问题。如果验证成功,但是卡住,看看你是否启用了终端代理。

### 使用Python通过SMTP发送Gmail电子邮件 为了使用Python发送Gmail邮件,需要利用`smtplib`库连接Google的SMTP服务器并调用相应的方法完成邮件的构建与发送过程[^1]。 #### 设置环境变量 在开始之前,确保已开启Gmail账户的安全访问权限。如果启用了两步验证,则需生成应用专用密码,并将其作为登录凭证的一部分。 #### 导入必要的模块 ```python import smtplib from email.mime.text import MIMEText from email.header import Header ``` #### 创建SMTP会话实例 建立到Gmail SMTP服务器的安全链接,通常端口号为587或465分别对应TLS/SSL加密模式。 ```python server = smtplib.SMTP('smtp.gmail.com', 587) # 或者使用 'smtp.gmail.com' 和 465 对于 SSL 连接 server.starttls() # 启动 TLS 加密 ``` #### 登录邮箱账号 提供有效的用户名(通常是完整的电子邮箱地址)以及对应的密码或者早先准备的应用程序特定密码。 ```python sender_email = "your.email@gmail.com" password = "your_password_or_app_specific_password" server.login(sender_email, password) ``` #### 构建邮件内容 定义收件人列表、主题和正文部分;这里采用MIME格式来构造更复杂的邮件体,比如HTML样式的内容。 ```python receiver_emails = ["recipient@example.com"] message = MIMEText("这是一封测试邮件", 'plain', 'utf-8') message['From'] = Header("发件人名称", 'utf-8') message['To'] = Header("收件人名称", 'utf-8') subject = '来自Python脚本的问候' message['Subject'] = Header(subject, 'utf-8') ``` #### 发送邮件 最后一步就是实际执行发送操作了,指定好寄件方、收件方及消息主体即可。 ```python try: server.sendmail( sender_email, receiver_emails, message.as_string() ) except Exception as e: print(f"发生错误: {e}") finally: server.quit() ``` 以上代码展示了如何配置基本参数并通过Gmail的服务成功发出一封简单的纯文本形式的通知类邮件[^2]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值