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

如何通过Python便捷连接谷歌账户收发邮件(替代SMTP/IMAP旧方式)

谷歌账户SMTP/IMAP收发邮件的替代方案

方案一:使用App Passwords(最便捷,限启用2FA的账户)

  • 前提:谷歌账户必须开启两步验证(2FA),未开启的先去账户安全设置里启用
  • 操作步骤:
    1. 登录谷歌账户安全中心,找到「App Passwords」选项(仅开启2FA后可见)
    2. 在「Select app」下拉框选「Mail」,「Select device」选「Other (Custom name)」,输入自定义名称比如「Python Mail Client」
    3. 生成的16位密码即为SMTP/IMAP的登录密码
  • SMTP发邮件代码示例:
import smtplib
from email.mime.text import MIMEText

sender_email = "你的谷歌邮箱@gmail.com"
app_password = "生成的16位App Password"
receiver_email = "收件邮箱@xxx.com"

msg = MIMEText("测试邮件内容")
msg["Subject"] = "测试邮件"
msg["From"] = sender_email
msg["To"] = receiver_email

with smtplib.SMTP_SSL("smtp.gmail.com", 465) as server:
    server.login(sender_email, app_password)
    server.send_message(msg)
  • IMAP收邮件代码示例:
import imaplib

mail = imaplib.IMAP4_SSL("imap.gmail.com")
mail.login("你的谷歌邮箱@gmail.com", "生成的16位App Password")
mail.select("inbox")
# 后续可执行邮件搜索、内容获取等操作

方案二:Google Gmail API(适合企业/批量场景)

前期准备

  1. 登录谷歌云控制台,创建新项目
  2. 在「API和服务」中搜索并启用「Gmail API」
  3. 进入「凭据」页面,创建「OAuth 2.0 客户端ID」,应用类型选「桌面应用」,下载JSON凭据文件并重命名为credentials.json,放在代码目录下
  4. 安装依赖库:pip install google-api-python-client google-auth-httplib2 google-auth-oauthlib

发送邮件代码示例

import os
import base64
from email.mime.text import MIMEText
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 = ["https://www.googleapis.com/auth/gmail.send"]

def get_credentials():
    creds = None
    # token.json会自动生成,用于保存已授权的凭据
    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 send_email():
    creds = get_credentials()
    service = build("gmail", "v1", credentials=creds)

    message = MIMEText("API测试邮件内容")
    message["to"] = "收件邮箱@xxx.com"
    message["subject"] = "Gmail API测试"
    encoded_message = base64.urlsafe_b64encode(message.as_bytes()).decode()

    create_message = {"raw": encoded_message}
    send_message = (service.users().messages().send(userId="me", body=create_message).execute())
    print(f"邮件已发送,ID: {send_message['id']}")

if __name__ == "__main__":
    send_email()

补充说明

  • 首次运行会弹出浏览器窗口,登录谷歌账户完成授权,之后token.json会保存授权信息,后续运行无需重复授权
  • 若需收取邮件,将权限范围改为https://www.googleapis.com/auth/gmail.readonly或https://www.googleapis.com/auth/gmail.modify,调用对应API接口即可实现

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 05:07:11