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

时间:2018-08-12 20:00:09

标签: python python-3.x email pymysql

我正在创建一个脚本,该脚本从数据库中获取一些数据,然后通过邮件发送。不幸的是,我坚持似乎很容易做的事情。

如果数据库中只有一个条目,则可以很好地运行(例如:18/10/18-做数学练习),但是如果没有出现多个条目,我考虑过使用while循环,但是我必须将所有条目保留在同一变量中,以使其无法正常工作。我分享以下代码:

# 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()

在此先感谢您的帮助,

1 个答案:

答案 0 :(得分:1)

您正在遍历结果,并在循环内分配值datatasca。循环完成后,这两个变量将只包含最后一个已打印的每个值。

检查:

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

如果要打印所有值,则必须将它们存储在某个地方。

您可能想要类似的东西

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

...然后再在代码中

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

如果您希望这些值在电子邮件中彼此相邻打印,则收集循环应该看起来像这样

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

然后在body分配中,从data_tasca收集行,类似于上面从datastascas收集的值。

顺便说一句,您可能应该将不使用cursor的代码移到with子句的外部,即,将代码移到cursor.fetchall()之后。