简体   繁体   English

从数据库检索数据并通过邮件发送

[英]Retrieving data from a DB and send it via mail

I am creating a script that takes some data from a database and then it sends it via mail. 我正在创建一个脚本,该脚本从数据库中获取一些数据,然后通过邮件发送。 Unfortunately, I am stuck with something that seems very easy to do. 不幸的是,我坚持似乎很容易做的事情。

If there is only one entry from the DB it works perfectly (ex: 18/10/18 - Do math exercises) but if there are multiple entries they don't show up, I thought about using a while loop but as I have to keep all the entries in the same variable I can't get it working. 如果数据库中只有一个条目,则可以很好地运行(例如:18/10/18-做数学练习),但是如果没有出现多个条目,我考虑过使用while循环,但是我不得不将所有条目保留在同一个变量中,我无法正常运行。 I share the code below: 我分享以下代码:

# Enviar correu Python 3.6 (NO ANOMENAR EMAIL.PY)
import smtplib, pymysql.cursors, secrets, re, datetime
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from time import strftime

def dbb():
    connection = pymysql.connect(host='X',
                                 user='root',
                                 password='X',
                                 db='deuresc',
                                 charset='utf8mb4',
                                 cursorclass=pymysql.cursors.DictCursor)
    try:
        with connection.cursor() as cursor:
            # Llegim tots els recordatoris
            dataactual = strftime('%Y-%m-%d')
            data = datetime.datetime.strptime(dataactual, "%Y-%m-%d")
            datafinal = data + datetime.timedelta(days=1)
            sql = "SELECT * FROM `deures` WHERE `data`=%s"
            cursor.execute(sql, datafinal)
            resultat = cursor.fetchall()

            for row in resultat:
                data = str(row['data'])
                print(data)
                tasca = str(row['tasca'])
                print(tasca)
                # It prints all the values but it doesn't send them below.
            fromaddr = "X"
            PASSWORD = "X"

            welcome = ['Jefe', 'Gery', 'Boss', 'Gary']

            # Misstage del correu
            SUBJECT = "Recordatori deures " + data
            body = "Bon dia " + secrets.choice(welcome) + ',' +  '\n' + 'Tens les següents tasques programades per demà: ' + '\n' + data + ' ' + tasca
            toaddr = "X"

            try:
                msg = MIMEMultipart()
                msg['From'] = fromaddr
                msg['To'] = toaddr
                msg['Subject'] = SUBJECT

                msg.attach(MIMEText(body, 'plain'))

                # Detalles del servidor de correu (Gmail, SMTP, Port: 587, TLS)
                server = smtplib.SMTP('smtp.gmail.com', 587)
                server.starttls()
                server.login(fromaddr, PASSWORD)
                text = msg.as_string()
                server.sendmail(fromaddr, toaddr, text)
                server.quit()
                print("S'ha enviat el recordatori a '" + toaddr + "' satisfactoriament!")
            except:
                print("S'ha produït un error!")
    finally:
        connection.close()

Thanks in advance for your help, 在此先感谢您的帮助,

You are looping over the results and assigning the values data and tasca inside the loop. 您正在遍历结果并在循环内分配值datatasca When the loop is done, those two variables will only contain the last one which was printed of each respective value. 循环完成后,这两个变量将只包含最后一个已打印的各个值。

Examine: 检查:

>>> for value in range(3):
...    print(value)
...
0
1
2
>>> print(value)
2

If you want to print all values, you have to store them somewhere. 如果要打印所有值,则必须将它们存储在某个位置。

You probably want something like 您可能想要类似

datas = []  # list to remember the data values
tascas = []  # list to remember the tasca values
for row in resultat:
    data = str(row['data'])
    print(data)
    datas.append(data)  # store this data in the list
    tasca = str(row['tasca'])
    print(tasca)
    tascas.append(tasca)  # store this tasca in the list

... and then later on in the code ...然后在代码中

body = "Bon dia " + secrets.choice(welcome) + ',' +  '\n' + \
     'Tens les següents tasques programades per demà: ' + '\n' + \
     '\n'.join(datas) + ' ' + '\n'.join(tascas)

If you expect the values to be printed next to each other in the email message, the collecting loop should probably instead look something like 如果您希望这些值在电子邮件中紧挨着打印,则收集循环应该看起来像

data_tasca = []  # list to remember data/tasca pairs
for row in resultat:
    ...
    data_tasca.append(' '.join([data, tasca]))

and then in the body assignment collect the rows from data_tasca similarly to how the collected values from datas and tascas are collected above. 然后在body分配中,从data_tasca收集行,类似于上面从datastascas收集的值的收集方式。

As an aside, you should probably move the code which doesn't use cursor to be outside the with clause, ie outdent the code after cursor.fetchall() . cursor.fetchall() ,您可能应该将不使用cursor的代码cursor with子句之外,即,将代码cursor.fetchall()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM