BigQuery for循环结果到Python smtplib消息体

时间:2018-01-28 15:43:07

标签: python google-bigquery smtplib

我想以固定的时间间隔从BigQuery数据库中获取数据,并使用smtplib自动通过电子邮件发送结果。

我有一个例子如下。我可以从BigQuery中提取数据就好了。我可以通过smtplib发送电子邮件就好了。我需要做的就是结合起来。我想将for循环的结果存储到邮件的电子邮件正文中。我相信我通过调用函数来做到这一点。但是,当我这样做。我收到了错误。

  

文件“bqtest5.py”,第52行,在server.sendmail中(login_email,   收件人,query_named_pa​​rams('corpus','min_word_count'))文件   “/usr/lib/python2.7/smtplib.py”,第729行,在sendmail中   esmtp_opts.append(“size =%d”%len(msg))TypeError:类型的对象   'NoneType'没有len()

from google.cloud import bigquery
import smtplib

#Variables
login_email = 'MYEMAIL'
login_pwd = 'MYPASSWORD'
recipients ='EMAILSENDINGTO'


#Create a function
#specifies we are going to add two paramaters
def query_named_params(corpus, min_word_count):
    #Create a Client
    client = bigquery.Client()
    #Define the query
    query = """
        SELECT word, word_count
        FROM `bigquery-public-data.samples.shakespeare`
        WHERE corpus = @corpus
        AND word_count >= @min_word_count
        ORDER BY word_count DESC;
        """
    #Define the paramaters
    query_params = [
        bigquery.ScalarQueryParameter('corpus', 'STRING', 'sonnets'),
        bigquery.ScalarQueryParameter(
            'min_word_count', 'INT64', 10)
    ]
    #Create job configuration
    job_config = bigquery.QueryJobConfig()
    #Add Query paramaters
    job_config.query_parameters = query_params
    #P
    query_job = client.query(query, job_config=job_config)

    # Print the results.
    destination_table_ref = query_job.destination
    table = client.get_table(destination_table_ref)
    resulters = client.list_rows(table)
    for row in resulters:
        print("{} : {} views".format(row.word, row.word_count))

# --------------------EMAIL PORTION -------------#
#)smtplib connection    print('messenger()')
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(login_email, login_pwd)

msg = """

"""
server.sendmail(login_email, recipients, query_named_params('corpus', 
'min_word_count'))
server.quit()


if __name__ == '__main__':
    query_named_params('corpus','min_word_count')

1 个答案:

答案 0 :(得分:0)

您的函数未返回任何导致将空消息发送到server.sendmail的值。

请改为尝试:

def query_named_params(corpus, min_word_count):

    (...)

    query_params = [
        bigquery.ScalarQueryParameter('corpus', 'STRING', corpus),
        bigquery.ScalarQueryParameter(
            'min_word_count', 'INT64', min_word_count)
    ]

    (...)
    s = ""
    for row in resulters:
        s+= "{} : {} views\n".format(row.word, row.word_count))
    return s

(...)
server.sendmail(login_email, recipients, query_named_params('sonnets', 10))

但这可能不会发送非常可读的消息。根据BQ表格结果的复杂程度,我建议使用Jinja2创建HTML模板,然后将其作为邮件正文发送。