我想寫一個Python類,它將使用Python的smtplib
庫發送電子郵件。我將它與標準的Gmail一起使用,但無法使配置與其他帳戶配合使用。Python的電子郵件不工作
的emailer類配置和發送方法:在使用本資料
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="[email protected]", toAddr=["[email protected]"])
emailer.send()
我在其他郵件客戶端成功地建立了我的電子郵件帳戶(如Outlook),以及:
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
的emailer試驗方法當我使用serverHost = 'smtp.gmail.com'
和serverPort = 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:
誰能告訴我,爲什麼它變得被困在這兒了?
您收到的實際異常消息是什麼? –
我沒有收到消息,因爲我不得不每次都控制+ c。它似乎陷入了一個無限循環。 – kdubs
你可以發佈更多的Emailer類嗎?特別是'send()'函數? –