1
0
Fork 0
gnuviechadmin-historic/gnuviechadmin/util/gpgmail.py
Jan Dittberner 222b35b033 add PasteDeploy dependency, remove pudge dependency
* upgrade migrate repository structure (fixes #32, #27)
 * switch to PasteDeploy (fixes #31)
 * update for SQLAlchemy 0.5 compatibility
 * add python-gnutls dependency (addresses #35)
2009-08-01 17:20:39 +02:00

89 lines
2.7 KiB
Python

# -*- coding: utf-8 -*-
#
# Copyright (C) 2007, 2008, 2009 by Jan Dittberner.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
# USA.
#
# Version: $Id$
"""GPG mail handling.
This module provides functionallity for sending signed and encrypted
email using GnuPG.
"""
import smtplib
from email.MIMEText import MIMEText
from pyme import core
from pyme.constants.sig import mode
def send_mail(config, subject, text):
"""Send a signed and possibly encrypted mail.
This method sends a mail with the given text and subject and signs
it using GnuPG. If a public key of the recipient is available the
mail is encrypted. The sender and recipient addresses are taken
from the configuration (section: common, properties: mailfrom,
mailto)
Arguments:
subject -- mail subject
text -- mail text
"""
if not text.__class__.__name__ == 'str':
text = text.encode('ascii', 'replace')
plain = core.Data(text)
cipher = core.Data()
c = core.Context()
c.set_armor(1)
signer = config['mailfrom']
rcpt = config['mailto']
c.signers_clear()
for sigkey in [x for x in c.op_keylist_all(signer, 1)]:
if sigkey.can_sign:
c.signers_add(sigkey)
if not c.signers_enum(0):
raise Exception("No secret keys for signing available for %s." % (
signer))
keylist = []
for key in c.op_keylist_all(rcpt, 0):
valid = 0
for subkey in key.subkeys:
keyid = subkey.keyid
if keyid == None:
break
can_encrypt = subkey.can_encrypt
valid += can_encrypt
if valid:
keylist.append(key)
if keylist:
c.op_encrypt_sign(keylist, 1, plain, cipher)
else:
c.op_sign(plain, cipher, mode.CLEAR)
cipher.seek(0, 0)
msg = MIMEText(cipher.read())
if keylist:
msg.set_param("x-action", "pgp-encrypted")
msg['Subject'] = subject
msg['From'] = signer
msg['To'] = rcpt
s = smtplib.SMTP()
s.connect()
s.sendmail(signer, [rcpt], msg.as_string())
s.close()