E-mail sending with Python and MySQL

0

I'm trying to send emails through Python with data from a database, but this is an error that I can not understand.

The system connects to the bank, sends the first e-mail and when it will send the second e-mail an error.

Can anyone help me with this code please?

Here is the code I have:

    #!/usr/bin/python

    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","intranet" )

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

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

    try:
       # executa o SQL
       cursor.execute(sql)
       # lista a base.
       results = cursor.fetchall()
       for row in results:
            #id = row[0]
            email_destino = row[1]
            titulo = row[2]
            mensagem = row[3]
            #email_respondepara = row[4]

            time.sleep(40)
            smtp.login(email,senha)

            de = '[email protected]'
            para = [email_destino]

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

            smtp.sendmail(de, para, msg)
            smtp.quit()
    except:
       print "Error"

    # desconecta do servidor
    db.close()
    
asked by anonymous 05.04.2018 / 22:28

1 answer

0

After the guidance of Andrey and Miguel I got the code and it looked like this:

    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","intranet" )

    # prepare a cursor object using cursor() method
    cursor = 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.execute(sql)
    # lista a base.
    results = cursor.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 20 segundo para enviar o proximo email
        time.sleep(20)

        de = email
        para = [email_destino]

        msg = '''Subject: %s \n
        %s''' % (titulo, ' ' + mensagem)
        #envia o e-mail
        smtp.sendmail(de, para, msg)
    #desconecta do SMTP
    smtp.quit()

    # desconecta do servidor
    db.close()
    
06.04.2018 / 14:00