A mailgate for Postfix to encrypt incoming and outgoing email with S/MIME and/or OpenPGP and decrypting OpenPGP encrypted emails https://lacre.io
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

82 lines
2.5 KiB

13 years ago
from ConfigParser import RawConfigParser
import email
import GnuPG
import smtplib
import sys
# Read configuration from /etc/gpg-mailgate.conf
_cfg = RawConfigParser()
cfg = dict()
for sect in _cfg.sections():
cfg[sect] = dict()
for (name, value) in _cfg.items(sect):
cfg[sect][name] = value
# Read e-mail from stdin
raw = sys.stdin.read()
raw_message = email.message_from_string( raw )
from_addr = raw_message['From']
if raw_message.has_key('To'):
to_addrs = map(lambda x: x.strip(), raw_message['To'].split(','))
13 years ago
if raw_message.has_key('Cc'):
to_addrs.extend( map(lambda x: x.strip(), raw_message['Cc'].split(',')))
if raw_message.has_key('Bcc'):
to_addrs.extend( map(lambda x: x.strip(), raw_message['Bcc'].split(',')))
def send_msg( message, recipients = None ):
if recipients == None:
recipients = to_addrs
relay = (cfg['relay']['host'], int(cfg['relay']['port']))
smtp = smtplib.SMTP(relay[0], relay[1])
smtp.sendmail( from_addr, recipients, message.as_string() )
gpg_to = list()
13 years ago
ungpg_to = list()
13 years ago
keys = GnuPG.public_keys( cfg['gpg']['keyhome'] )
for to in to_addrs:
domain = to.split('@')[1]
if domain in cfg['default']['domains'].split(','):
if to in keys:
gpg_to.append( (to, to) )
elif cfg.has_key('keymap') and cfg['keymap'].has_key(to):
gpg_to.append( (to, cfg['keymap'][to]) )
13 years ago
13 years ago
if gpg_to == list():
if cfg['default'].has_key('add_header') and cfg['default']['add_header'] == 'yes':
raw_message['X-GPG-Mailgate'] = 'Not encrypted, public key not found'
send_msg( raw_message )
13 years ago
if ungpg_to != list():
send_msg( raw_message, ungpg_to )
13 years ago
if raw_message.is_multipart():
payload = list()
for part in raw_message.get_payload():
if part.get_content_type() == "text/plain":
raw_message.set_payload( payload )
if cfg.has_key('logging') and cfg['logging'].has_key('file'):
log = open(cfg['logging']['file'], 'a')
log.write("Encrypting email to: %s\n" % ' '.join( map(lambda x: x[0], gpg_to) ))
if cfg['default'].has_key('add_header') and cfg['default']['add_header'] == 'yes':
raw_message['X-GPG-Mailgate'] = 'Encrypted by GPG Mailgate 0.1'
13 years ago
gpg_to_cmdline = list()
gpg_to_smtp = list()
for rcpt in gpg_to:
gpg = GnuPG.GPGEncryptor( cfg['gpg']['keyhome'], gpg_to_cmdline )
13 years ago
gpg.update( raw_message.get_payload() )
raw_message.set_payload( gpg.encrypt() )
13 years ago
send_msg( raw_message, gpg_to_smtp )