我正在尝试编写一个Python类,它将使用Python的smtplib
库发送电子邮件。我让它与标准Gmail一起使用,但我无法让配置与其他帐户一起使用。
Emailer Class配置和发送方法:
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'
和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:
谁能告诉我为什么它会被困在这里?
答案 0 :(得分:3)
所以事实证明问题是我需要使用SMTP_SSL
而不是SMTP
因为我的服务器上的安全设置。
答案 1 :(得分:0)
这可能是连接问题。使用telnet检查访问权限并检查服务器答案。
telnet smtp.gmail.com 587
Trying 64.233.186.109...
Connected to smtp.gmail.com.
Escape character is '^]'.
220 smtp.gmail.com ESMTP f103sm809119qkh.38 - gsmtp
答案 2 :(得分:0)
为您的服务器尝试telnet测试,描述的python错误是连接问题。例如,尝试telnet mail.myserver.edu 465
。