3 # Copyright (C) 2008-2011 W. Trevor King
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation, either version 3 of the License, or
8 # (at your option) any later version.
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
15 # You should have received a copy of the GNU General Public License
16 # along with this program. If not, see <http://www.gnu.org/licenses/>.
18 """LDAP address searches for Mutt.
20 Add :file:`mutt-ldap.py` to your ``PATH`` and add the following line
21 to your :file:`.muttrc`::
23 set query_command = "mutt-ldap.py '%s'"
25 Search for addresses with `^t`, optionally after typing part of the
26 name. Configure your connection by creating :file:`~/.mutt-ldap.py`
27 contaning something like::
30 server = myserver.example.net
31 basedn = ou=people,dc=example,dc=net
33 See the `CONFIG` options for other available settings.
44 CONFIG = ConfigParser.SafeConfigParser()
45 CONFIG.add_section('connection')
46 CONFIG.set('connection', 'server', 'domaincontroller.yourdomain.com')
47 CONFIG.set('connection', 'port', '389') # set to 636 for default over SSL
48 CONFIG.set('connection', 'ssl', 'no')
49 CONFIG.set('connection', 'user', '')
50 CONFIG.set('connection', 'password', '')
51 CONFIG.set('connection', 'basedn', 'ou=x co.,dc=example,dc=net')
52 CONFIG.read(os.path.expanduser('~/.mutt-ldap.rc'))
56 if CONFIG.getboolean('connection', 'ssl'):
58 url = '%s://%s:%s' % (
60 CONFIG.get('connection', 'server'),
61 CONFIG.get('connection', 'port'))
62 connection = ldap.initialize(url)
64 CONFIG.get('connection', 'user'),
65 CONFIG.get('connection', 'password'),
69 def search(query, connection=None):
70 local_connection = False
73 local_connection = True
74 connection = connect()
78 filterstr = '(|%s)' % (
79 u' '.join([u'(%s=*%s%s)' % (field, query, post)
80 for field in ['cn', 'rdn', 'uid', 'mail']]))
81 r = connection.search_s(
82 CONFIG.get('connection', 'basedn'),
84 filterstr.encode('utf-8'))
86 if local_connection and connection:
90 def format_entry(entry):
93 for m in data['mail']:
94 yield email.utils.formataddr((data['cn'][-1], m))
97 if __name__ == '__main__':
100 query = unicode(' '.join(sys.argv[1:]), 'utf-8')
101 entries = search(query)
102 addresses = list(itertools.chain(
103 *[format_entry(e) for e in sorted(entries)]))
104 print '%d addresses found:' % len(addresses)
105 print '\n'.join(addresses)