Search code examples
pythonpython-2.7gmailsmtplib

Sending email does not work when I run the script, but line by line, it works, why?


I have this simple script that I use to send myself email with a status on a server. It runs, and it gives me no errors, but I do not receive any email, and there is no email in the sent folder at Google. But if I copy and paste every line by line into python in a shell, it does send email and works. There are no errors anywhere. I even get accepted status from Google.

UPDATE: I might have cut to much code out of the sample, and the i variable was accidentally taken out. I have added it again. When I copy paste each line into python cmd line, the script works. When I just run the script, it reports no errors, but does not send the email.

import smtplib
i = 0
try:
    text = "This is remarkable"
    fromaddr = "<gmail address>"
    toaddr = "<email address>"
    msg = """\
            From: <gmail address>
            To: <email address>
            Subject: Message number %i

            %s
    """ % (i, text)

    server = smtplib.SMTP("smtp.gmail.com:587")
    server.set_debuglevel(1)
    server.ehlo()
    server.starttls()
    server.login("<email>", "<password>")

    ret = server.sendmail(fromaddr, toaddr, msg)
    print "returned : ", ret
    print "message sent"
    i += 1
except:
    print "Now some crazy **** happened"

Solution

  • i is not defined. You would see a NameError if you hadn't wrapped try and a bare except around everything. You should have as little as possible in the try block, at least. Also you can catch the specific error as e. This will print the error also so that you can understand what is the problem.

    So the code should be:

    import smtplib
    
    i = 1
    text = "This is remarkable"
    fromaddr = "<gmail address>"
    toaddr = "<email address>"
    msg = """\
            From: <gmail address>
            To: <email address>
            Subject: Message number %i
    
            %s""" % (i, text)
    
    try: 
        server = smtplib.SMTP("smtp.gmail.com:587")
        server.set_debuglevel(1)
        server.ehlo()
        server.starttls()
        server.login("<email>", "<password>")
        ret = server.sendmail(fromaddr, toaddr, msg)
    except Exception as e:
        print 'some error occured'
        print e
    else:
        print "returned : ", ret
        print "message sent"
        i += 1