E-mail sending with update in the bank

0

I am developing a code for sending e-mails and, in case the e-mail is sent, the system makes an update in the database table. The emails are being sent, but the update does not happen Here is the code I have:

    import MySQLdb
    import smtplib
    import time

    smtp = smtplib.SMTP_SSL('email-ssl.com.br', 465)
    email = '[email protected]'
    senha = '1234'

    # Abre o banco de dados
    db = MySQLdb.connect("localhost","root","1234","tabela" )

    # prepare a cursor object using cursor() method
    cursor_select = db.cursor()

    sql = " SELECT  e.id,e.email_destino,e.titulo,e.mensagem,e.email_respondepara FROM envia_email e WHERE e.enviado = 'F'"

    # executa o SQL
    cursor_select.execute(sql)
    # lista a base.
    results = cursor_select.fetchall()

    #loga no SMTP
    smtp.login(email,senha)

    for row in results:
        id = row[0]
        email_destino = row[1]
        titulo = row[2]
        mensagem = row[3]
        #email_respondepara = row[4]

        #aguarda 10 segundo para enviar o proximo email
        time.sleep(10)

        de = email
        para = [email_destino]

        msg = '''Subject: %s \n
        %s''' % (titulo, ' ' + mensagem)

        #se enviar o email faz update na tabela
        if(smtp.sendmail(de, para, msg)):

            cursor_update = db.cursor()
            sql_update = "UPDATE envia_email SET enviado = 'T' WHERE id = %i" % id
            # executa o SQL
            cursor_update.execute(sql_update)

    #desconecta do SMTP
    smtp.quit()

    # desconecta do servidor
    db.close()
    
asked by anonymous 06.04.2018 / 16:19

1 answer

0

After executing the query, it is necessary to commit to save the data to the database.

sql_update = "UPDATE envia_email SET enviado = 'T' WHERE id = %i" % id

# executa SQL
cursor_update.execute(sql_update)

# grava mudanças no banco de dados
db.commit()
    
07.04.2018 / 18:20