不知道为什么我的电子邮件脚本不发送电子邮件

时间:2019-05-06 21:28:36

标签: python-2.7

它正在工作,但是更新我的Raspberry Pi之后,我发送电子邮件的python脚本未发送,我不确定为什么。它似乎只是挂起而没有引发任何错误消息,每次都必须按Ctrl + C停止它,否则它将无限期地坐在那里。

这是我的代码...

import smtplib, datetime

from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders

email_send = [sender email]
email_receive = [my email]
password = [password]
subject = 'Test Subject'
#sYMD = datetime.date.today().strftime('%y%m%d')
#lpath = 'C:/Path/to/files/'
files = ['log1.txt', 'log2.txt']

msg = MIMEMultipart()
msg['From'] = email_send
msg['To'] = email_receive
msg['Subject'] = subject
body = """\
Test Message."""

msg.attach(MIMEText(body, 'plain'))

#filename = x.strftime("%y%m%d")+'_log.txt'

for file in files:
    part = MIMEBase('application', "octet-stream")
    part.set_payload(open(file, "rb").read())
    encoders.encode_base64(part)
    part.add_header('Content-Disposition',
                    'attachment; filename="%s"' % file)
    msg.attach(part)

text = msg.as_string()

server = smtplib.SMTP('smtp.office365.com', 587)
server.starttls()
server.login(email_send, password)

server.sendmail(email_send, email_receive, text)
server.quit()

这是我运行脚本时正在做的事情...

pi@raspberrypi: python send_email.py
^CTraceback (most recent call last):
  File "send_email.py", line 36, in <module>
    server = smtplib.SMTP('smtp.office365.com', 587)
  File "/usr/lib/python2.7/smtplib.py", line 265, in __init__
    (code, msg) = self.connect(host, port)
  File "/usr/lib/python2.7/smtplib.py", line 317, in connect
    (code, msg) = self.getreply()
  File "/usr/lib/python2.7/smtplib.py", line 361, in getreply
    line = self.file.readline(_MAXLINE + 1)
  File "/usr/lib/python2.7/socket.py", line 480, in readline
    data = self._sock.recv(self._rbufsize)
KeyboardInterrupt

感谢您提供的任何帮助。

1 个答案:

答案 0 :(得分:0)

嗯,好像连接超时了。客户端是否可能无法连接到指定的服务器和端口?尝试直接与nctelnet连接以确认。

您还可以在几秒钟内将timeout值传递给SMTP呼叫:

server = smtplib.SMTP('smtp.office365.com', 587, timeout=5)