Python脚本无法发送电子邮件,这可能是什么问题?

时间:2018-12-02 02:14:38

标签: python

fileOfEmails='emails.txt'
fileOfsent='sent.txt'
username=""
password=""


html = """\
<html>
  <head></head>
  <body>
  hi
  </body>
</html>
"""


with open(fileOfEmails,'r') as fl:
    content=fl.readlines()

content=[x.strip() for x in content]

with open(fileOfsent,'r') as fl:
    sent=fl.readlines()

sent=[x.strip() for x in sent]

import smtplib
try:

    server = smtplib.SMTP('smtp.gmail.com',587)
    print('Smptp established')
except Exception:

    print('SMTP not ServerProblem')


# log in to the server
try:
    server.login(username ,password)
    print('Login successful')
except Exception:
    print('Login ERORr')

from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

me = username

i=0
aux='random'
for email in content:
    you=aux+str(i)
    i+=1
    if email not in sent:
        try:
            # Create message container - the correct MIME type is multipart/alternative.
            msg = MIMEMultipart('alternative')
            msg['mark'] = "Subject"
            msg['test@gmail.com'] = you
            msg['To'] = email


            part = MIMEText(html, 'html')
            msg.attach(part)

            server.sendmail(you, email, msg.as_string())
            server.quit()
            sent.append(email)
            print('Email sent to : ',email)

        except Exception:
            print('Not sent to: ',email)
            continue

with open(fileOfsent, 'w') as f:
    for item in sent:
        f.write("%s\n" % item)

编译此代码后,这是我的日志。

Smptp established
Login successful
Not sent to:

可能出什么问题了? 有人有主意吗?

我不认为这是服务器问题,因为我也已经测试过gmail smtp 我一直在调试,仍然没有找到解决方案。 请帮忙 我希望它能够发送电子邮件。 有人可以测试此代码,如果可以的话给我反馈。 如果没有,则接受任何可能的解决方案。 谢谢

1 个答案:

答案 0 :(得分:0)

将代码更改为以下代码,您将在错误消息中得到答案:

 except Exception as e:
            print('Not sent to: %s because %s' % (email, e))