0
我得到KeyError: 'E-mail'
。但找不到問題。我試過readfp()
以及使用文件的完整路徑。 my_file = (os.path.join(os.getcwd(),'config.ini'))
。但似乎沒有任何工作。Python:ConfigParser.NoSectionError:沒有部分:'電子郵件'
這是代碼。
import configparser
import sys
import xml.etree.ElementTree as ET
import time
import smtplib
import os
def usage(code):
sys.stderr.write("usage:\n")
sys.stderr.write(" " + sys.argv[0] + " <xml file with addresses> <subject> <file with message body>\n")
sys.exit(code)
cfg = configparser.ConfigParser()
cfg.read('config.ini')
server = cfg.get('E-mail', 'server')
login = cfg.get('E-mail', 'login')
from_addr = cfg.get('E-mail', 'from')
password = cfg.get('E-mail', 'password')
if len(sys.argv) < 4:
usage(1)
src_xml = sys.argv[1]
subject = sys.argv[2]
msg_file = sys.argv[3]
server = smtplib.SMTP(server)
server.ehlo()
server.starttls()
server.login(login, password)
with open(msg_file) as f:
msg_text = f.read()
tree = ET.parse(src_xml)
root = tree.getroot()
for p in root:
if 'email' in p.attrib:
to_addr = p.attrib['email']
msg = "\r\n".join([
"From: " + from_addr,
"To: " + to_addr,
"Subject: " + subject,
"",
msg_text
])
server.sendmail(from_addr, to_addr, msg)
server.quit()
這裏是我得到的錯誤。
Traceback (most recent call last):
File "C:\Users\Isuru\AppData\Local\Programs\Python\Python35-32\lib\configparser.py", line 1135, in _unify_values
sectiondict = self._sections[section]
KeyError: 'E-mail'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\Isuru\Desktop\script\MailSender.py", line 17, in <module>
server = cfg.get('E-mail', 'server')
File "C:\Users\Isuru\AppData\Local\Programs\Python\Python35-32\lib\configparser.py", line 778, in get
d = self._unify_values(section, vars)
File "C:\Users\Isuru\AppData\Local\Programs\Python\Python35-32\lib\configparser.py", line 1138, in _unify_values
raise NoSectionError(section)
configparser.NoSectionError: No section: 'E-mail'
這是config.ini文件。
[E-mail]
server=********:465
login=***********.com
[email protected]
password=******
我在StackOverflow中嘗試了很多相同的問題。但沒有運氣。
請刪除腳本中的所有其他代碼,只保留最少的解析部分,然後查看錯誤是否消失。那麼請僅在這裏發佈這個部分。 – moooeeeep
嗯,我試過了。問題在於解析部分。 – Isuru
嘗試沒有破折號。 – PsyKzz