通过Python 2.6发送电子邮件(Gmail)时出错

时间:2013-11-29 23:55:52

标签: python email cron smtp gmail

这个让我困惑了一段时间。谁能看到我哪里出错?这段代码在Python 2.7中运行良好;但是,它在通过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')

通过cron产生了这个错误:

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')

感谢您的时间。任何帮助将不胜感激。

萨姆。

1 个答案:

答案 0 :(得分:1)

我终于得到了它的工作。事实证明我只需要添加几行:

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

因此,最终的脚本是:

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')