python 云函数:如何将提取的BigQuery数据作为. csv附件添加到日常电子邮件中?

gmxoilav  于 2023-02-21  发布在  Python
关注(0)|答案(1)|浏览(127)

我是GCP云功能和云调度程序的新手,我想在特定时间发送每日电子邮件,这将发送BigQuery表提取-作为. csv文件附加到电子邮件中。
我已经编写了Python代码来查询数据并发送电子邮件,但我不确定如何将提取的数据作为.csv文件附件添加到电子邮件中。
到目前为止,我已经编写了下面的Python函数,该函数查询数据并发送电子邮件,但我不知道如何实际编写代码来将数据作为.csv附加到电子邮件中:

def send_email_attachment(request):
    
    project_id = '[MY-PROJECT-ID]'
    credentials = service_account.Credentials.from_service_account_file('[SERVICE-ACCOUNT-KEY]')

    client = bigquery.Client(project=project_id, credentials=credentials)

    query = '''
        SELECT *
        FROM `PROJECT_ID.DATASET.TABLE`
    '''

    results = client.query(query).result()

    message = Mail(
        to_emails="person@email.com",
        from_email=Email('steve-h@example.com', "Steve H."),
        subject="This is the data extract - attached",
        html_content=html_content
    )
    message.add_bcc("steve-h@example.com")

    try:
        sg = SendGridAPIClient('[API-KEY]')
        response = sg.send(message)
        return f"Email sent at {datetime.now()} with status code {response.status_code}"
    except HTTPError as e:
        return e.message

我觉得我已经完成了75%的工作,但是如果有人能帮我的话,那将是一个很大的帮助。
谢谢!

dojqjjoe

dojqjjoe1#

下面是一个示例代码,应该会对你有所帮助。只是需要注意一点:该代码读取打开csv文件,然后附加它。

data = open(file_name, 'rb').read()
        base64_encoded_excel = base64.b64encode(data).decode('UTF-8')
        attachment = Attachment()
        attachment.file_content = base64_encoded_excel
        attachment.file_name = file_name.split("/")[-1]
        mail = Mail(from_email, to_email, subject, html_content=html_content)
        mail.add_attachment(attachment)

相关问题