当我运行脚本时发送电子邮件不起作用,但是一行一行地工作,为什么? [英] Sending email does not work when I run the script, but line by line, it works, why?

查看:199
本文介绍了当我运行脚本时发送电子邮件不起作用,但是一行一行地工作,为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个简单的脚本,用于在服务器上发送自己的电子邮件地址。它运行,它不给我任何错误,但我没有收到任何电子邮件,谷歌发送的文件夹中没有电子邮件。但是,如果我将每一行逐行复制并粘贴到shell中的python中,它确实会发送电子邮件并工作。在任何地方都没有错误。我甚至获得了Google的认可。

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.

更新:我可能会将样本中的代码剪掉,并且i变量被意外取出。我又添加了它。当我将每行粘贴到python cmd行时,该脚本就可以工作。

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"


推荐答案

<$ c未定义$ c> i 。如果你没有包装 try 和一个空的,除了,你会看到 NameError code>围绕一切。至少应该在 try 块中尽可能少。你也可以将特定的错误作为e 来捕获。这也将打印错误,以便您可以了解问题所在。

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

这篇关于当我运行脚本时发送电子邮件不起作用,但是一行一行地工作,为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆