Skip to main content
 首页 » 编程设计

Python 电子邮件程序不工作

2024年08月25日32jackei

我正在尝试编写一个 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 

邮件测试方法:

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

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

/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: 

谁能告诉我为什么卡在这里?

请您参考如下方法:

事实证明,由于服务器上的安全设置,我需要使用 SMTP_SSL 而不仅仅是 SMTP。