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

Cloud Functions:如何每日10点发送含BigQuery表格数据的邮件?

解决方案

一、实现每日10点定时触发

用GCP Cloud Scheduler配合Cloud Functions实现定时执行:

  • 登录GCP控制台,打开Cloud Scheduler页面,创建新任务
  • 填写任务名称(如daily-bq-data-email),频率输入Cron表达式0 10 * * *,时区选择你需要的时区(比如Asia/Shanghai,对应北京时间每日10点)
  • 目标类型选HTTP,粘贴你的Cloud Function触发URL;HTTP方法选POST,身份验证选择OIDC令牌,服务账号选择Cloud Scheduler默认账号,然后给该账号添加Cloud Functions Invoker角色(确保它有权限调用你的函数)
  • 保存任务,到时间就会自动触发你的邮件函数

二、提取BigQuery数据并整合到邮件

1. 添加依赖

在Cloud Functions的requirements.txt文件中添加BigQuery客户端库:

sendgrid>=6.0.0
google-cloud-bigquery>=3.10.0

2. 修改函数代码

整合BQ数据查询、HTML表格生成和邮件发送逻辑:

def email(request):
    import os
    from sendgrid import SendGridAPIClient
    from sendgrid.helpers.mail import Mail, Email
    from python_http_client.exceptions import HTTPError
    from google.cloud import bigquery
    from google.api_core.exceptions import GoogleAPIError

    # 初始化BigQuery客户端
    bq_client = bigquery.Client()
    # 替换为你的BigQuery表查询语句,可按需添加过滤条件
    query = """
        SELECT * FROM `your-gcp-project.your-dataset.your-target-table`
    """

    try:
        # 执行BQ查询
        query_job = bq_client.query(query)
        results = query_job.result()

        # 将查询结果转为HTML表格
        html_content = "<p>以下是今日BigQuery表格数据:</p>"
        html_content += "<table border='1' cellpadding='4' cellspacing='0'>"
        # 添加表头
        html_content += "<tr>"
        for field in results.schema:
            html_content += f"<th>{field.name}</th>"
        html_content += "</tr>"
        # 添加数据行
        for row in results:
            html_content += "<tr>"
            for val in row.values():
                html_content += f"<td>{val}</td>"
            html_content += "</tr>"
        html_content += "</table>"

        # 初始化SendGrid客户端并发送邮件
        sg = SendGridAPIClient(os.environ['EMAIL_API_KEY'])
        message = Mail(
            to_emails="[Destination]@email.com",
            from_email=Email('[YOUR]@gmail.com', "Your name"),
            subject="每日BigQuery数据同步",
            html_content=html_content
        )
        message.add_bcc("[YOUR]@gmail.com")

        response = sg.send(message)
        return f"邮件发送成功,状态码: {response.status_code}"

    except GoogleAPIError as e:
        return f"BigQuery查询出错: {str(e)}"
    except HTTPError as e:
        return f"邮件发送出错: {e.message}"
    except Exception as e:
        return f"未知错误: {str(e)}"

3. 配置权限

确保你的Cloud Function服务账号有BigQuery数据查看者和作业用户角色,能够访问目标BQ表格。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 01:35:15