Error Sending Email (Gmail) Via Python 2.6

2019-07-19 13:53发布

This one has been baffling me for a while. Can anyone see where i'm going wrong? This code works fine in Python 2.7; however, it breaks when running through a cron (Python 2.6).

def send_email (message, status):
    fromaddr = 'sam@gmail.com'
    toaddrs = 'sam@gmail.com'
    server = SMTP('smtp.gmail.com', 587)
    server.starttls()
    server.login('username-example', 'password-example')
    server.sendmail(fromaddr, toaddrs, 'Subject: %s\r\n%s' % (status, message))
    server.quit()

send_email('message text','subject text')

Through the cron it produces this error:

Traceback (most recent call last):
  File "/home/user/weather-script.py", line 30, in <module>
    send_email('message text', 'subject text')
  File "/home/user/weather-script.py", line 11, in send_email
    server.login('username-example', 'password-example')
  File "/usr/lib64/python2.6/smtplib.py", line 589, in login
    raise SMTPAuthenticationError(code, resp)
smtplib.SMTPAuthenticationError: (534, '5.7.14 <https://accounts.google.com    /ContinueSignIn?sarp=1&scc=1&plt=AKgnsbsZn\n5.7.14 KZ5OF6iSxSCasonEce6H27TM-l4ithBaTtxpg8GbcEzJ522-_MUlYZJWIbc-ZwVnuslJOQ\n5.7.14 _Fu7bpO9-xOfqDi-eiSAPRw8_QLth-Z9ytfeWYIJi0Ez8F_p5joplfR7IoXw4V8VisI7pq\n5.7.14 8NTPoVFqvUEldEI5wL8AukhoPpVfDiX25557ky_W7N6UZLb3efGuvnbhrBsmg5gvlzj1DG\n5.7.14 1GchFIA> Please log in via your web browser and then try again.\n5.7.14 Learn more at https://support.google.com/mail/bin/answer.py?answer=787\n5.7.14 54 xv2sm104667531pbb.39 - gsmtp')

Thanks for your time. Any help will be greatly appreciated.

Sam.

1条回答
我想做一个坏孩纸
2楼-- · 2019-07-19 14:20

I've finally got it to work. It turns out I just needed to add a couple of extra lines:

server.ehlo()
server.starttls()
server.ehlo()

Therefore, the final script goes:

def send_email (message, status):
    fromaddr = 'sam@gmail.com'
    toaddrs = 'sam@gmail.com'
    server = SMTP('smtp.gmail.com', 587)
    server.ehlo()
    server.starttls()
    server.ehlo()
    server.login('username-example', 'password-example')
    server.sendmail(fromaddr, toaddrs, 'Subject: %s\r\n%s' % (status, message))
    server.quit()

send_email('message text','subject text')
查看更多
登录 后发表回答