Python 电子邮件发送器不工作

kdu*_*ubs 2 python smtplib

我正在尝试编写一个使用 Python 库发送电子邮件的 Python 类smtplib。我让它可以与标准 Gmail 一起使用,但在让配置与其他帐户一起使用时遇到问题。

Emailer类配置和发送方法:

def configure(self,  serverLogin, serverPassword, fromAddr, toAddr, serverHost='mail.myserver.edu', serverPort=465):
    self.server=smtplib.SMTP(serverHost,serverPort) #set the server host/port - currently configured for gmail
    self.server.ehlo()
    self.server.starttls()
    self.server.ehlo()
    self.server.login(serverLogin, serverPassword)  #login to senders email
    self.fromAddr = fromAddr
    self.toAddr = toAddr

def send(self):
    msgText = email.MIMEText.MIMEText("\n".join(self.message))
    self.msg.attach(msgText) 
    print "Sending email to %s " % self.toAddr
    text = self.msg.as_string() #conver the message contents to string format
    self.server.sendmail(self.fromAddr, self.toAddr, text)  #send the email
Run Code Online (Sandbox Code Playgroud)

邮件测试方法:

def test(self):
    message = "Like a boss"  #body message of the email
    attachment = ["/Desktop/testImage2"]    #list of attachments
    image = ["/Desktop/testImage2"]
    emailer = Emailer() 
    emailer.addAttachment(attachment)
    emailer.addToMessage(message,image)
    emailer.setSubject("Python Test")
    emailer.configure(serverLogin="loginname", serverPassword="password", fromAddr="myaddr@myserver.edu", toAddr=["otheraddr@gmail.com"])
    emailer.send()
Run Code Online (Sandbox Code Playgroud)

我使用此信息在其他邮件客户端(如 Outlook)中成功设置了我的电子邮件帐户,并且当我使用serverHost = 'smtp.gmail.com'和时,这些类工作得很好serverPort = 587。但是,当我test()使用非 Gmail 服务器信息在终端中运行该类时,代码似乎挂在了这一点上:

/Users/anaconda/lib/python2.7/smtplib.pyc in __init__(self, host, port, local_hostname, timeout)
254         self.esmtp_features = {}
255         if host:
--> 256             (code, msg) = self.connect(host, port)
257             if code != 220:
258                 raise SMTPConnectError(code, msg)

/Users/anaconda/lib/python2.7/smtplib.pyc in connect(self, host, port)
315             print>>stderr, 'connect:', (host, port)
316         self.sock = self._get_socket(host, port, self.timeout)
--> 317         (code, msg) = self.getreply()
318         if self.debuglevel > 0:
319             print>>stderr, "connect:", msg

/Users/anaconda/lib/python2.7/smtplib.pyc in getreply(self)
359         while 1:
360             try:
--> 361                 line = self.file.readline(_MAXLINE + 1)
362             except socket.error as e:
363                 self.close()

/Users/anaconda/lib/python2.7/socket.pyc in readline(self, size)
474             while True:
475                 try:
--> 476                     data = self._sock.recv(self._rbufsize)
477                 except error, e:
478                     if e.args[0] == EINTR:

KeyboardInterrupt:
Run Code Online (Sandbox Code Playgroud)

谁能告诉我为什么它被困在这里?

kdu*_*ubs 5

所以事实证明问题是我需要使用SMTP_SSL而不是仅仅SMTP因为我的服务器上的安全设置。