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

Google Cloud Function(GCF)中使用Gmail发送邮件的可行方案?

可行解决方案

1. Gmail API + OAuth 2.0授权码流程(用你的个人账户发件)

  • 先在Google Cloud Console创建OAuth客户端ID(选「桌面应用」或「其他」类型),手动走一遍授权流程拿到刷新令牌,然后把客户端ID、客户端密钥、刷新令牌存在Cloud Function的环境变量里。
  • 确保Gmail API已启用,授权时请求https://www.googleapis.com/auth/gmail.send权限,这样就能用API发送邮件,发件人就是你的个人账户。
  • Python代码示例:
import os
from google.oauth2.credentials import Credentials
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError

def send_email(request):
    # 从环境变量读取凭证
    creds = Credentials.from_authorized_user_info({
        "client_id": os.environ.get("CLIENT_ID"),
        "client_secret": os.environ.get("CLIENT_SECRET"),
        "refresh_token": os.environ.get("REFRESH_TOKEN"),
        "token_uri": "https://oauth2.googleapis.com/token"
    }, scopes=["https://www.googleapis.com/auth/gmail.send"])

    try:
        service = build('gmail', 'v1', credentials=creds)
        # 按Gmail API要求构造邮件(需Base64编码)
        message = {
            'raw': '这里替换为Base64编码后的邮件内容'
        }
        send_result = service.users().messages().send(userId="me", body=message).execute()
        return f"邮件发送成功,ID: {send_result['id']}"
    except HttpError as err:
        return f"发送失败: {err}"
  • 提示:刷新令牌长期有效,除非你手动撤销权限或更改账户密码,适合长期运行的Cloud Function。

2. SMTP直接发送(用你的个人账户发件)

  • 利用Gmail的SMTP服务器,结合你的邮箱地址和应用专用密码(如果开了两步验证),把这些信息存在Cloud Function环境变量里,用SMTP库发邮件。
  • Python代码示例:
import os
import smtplib
from email.mime.text import MIMEText

def send_email(request):
    sender = os.environ.get("MY_GMAIL")
    app_pwd = os.environ.get("GMAIL_APP_PASSWORD")
    receiver = "target@example.com"

    # 构造邮件
    msg = MIMEText("这是测试邮件内容")
    msg['Subject'] = "Cloud Function 发送的邮件"
    msg['From'] = sender
    msg['To'] = receiver

    try:
        # 连接Gmail的SMTP SSL服务器
        with smtplib.SMTP_SSL('smtp.gmail.com', 465) as server:
            server.login(sender, app_pwd)
            server.send_message(msg)
        return "邮件发送成功"
    except Exception as e:
        return f"发送失败: {str(e)}"
  • 注意:如果账户开了两步验证,必须用应用专用密码代替普通密码;没开2FA的话可以直接用账户密码,但Google可能会拦截这种登录方式,建议开启2FA并使用应用专用密码。

3. 集成第三方邮件服务

  • 要是不想受Gmail的各种限制,直接用SendGrid、Mailgun这类第三方邮件服务就行。这些服务提供简单的API接口,Cloud Function通过API密钥调用即可发件。
  • 你需要先在第三方服务里验证自己的邮箱作为发件人,之后服务账户就能通过API密钥调用服务发送邮件,不用处理Gmail的OAuth或SMTP配置问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 00:10:52