Skip to main content
 首页 » 编程设计

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

2025年05月04日46zhwl

这个问题让我困惑了一段时间。谁能看到我哪里出错了?此代码在 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') 

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

山姆。

请您参考如下方法:

我终于让它工作了。结果我只需要添加几行:

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