#!/usr/bin/python # -*- coding: utf-8 -*- import urllib, json, subprocess, argparse, re, sys import [...] from M2Crypto import BIO, Rand, SMIME from [...] [...] ssl_key = '/etc/ssl/private/mailcert-vpn.charite.de.key' ssl_cert = '/etc/ssl/certs/mailcert-vpn.charite.de.crt' def send_mail_ssl(sender, to, subject, text, files=[], attachments={}, bcc=[]): """ Sends SSL signed mail [...] """ if isinstance(to, str): to = [to] # create multipart message msg = MIMEMultipart() # attach message text as first attachment msg.attach( MIMEText(text, "plain", "utf-8") ) # attach files to be read from file system for file in files: part = MIMEBase('application', "octet-stream") part.set_payload( open(file,"rb").read() ) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(file)) msg.attach(part) # attach files read from dictionary for name in attachments: part = MIMEBase('application', "octet-stream") part.set_payload(attachments[name]) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % name) msg.attach(part) # put message with attachments into into SSL' I/O buffer msg_str = msg.as_string() buf = BIO.MemoryBuffer(msg_str) # load seed file for PRNG Rand.load_file('/tmp/randpool.dat', -1) smime = SMIME.SMIME() # load certificate smime.load_key(ssl_key, ssl_cert) # sign whole message p7 = smime.sign(buf, SMIME.PKCS7_DETACHED) # create buffer for final mail and write header out = BIO.MemoryBuffer() out.write('From: %s\n' % sender) out.write('To: %s\n' % COMMASPACE.join(to)) out.write('Date: %s\n' % formatdate(localtime=True)) out.write('Subject: %s\n' % subject) out.write('Auto-Submitted: %s\n' % 'auto-generated') out.write('X-Auto-Response-Suppress: %s\n' % 'OOF') # convert message back into string buf = BIO.MemoryBuffer(msg_str) # append signed message and original message to mail header smime.write(out, p7, buf) # load save seed file for PRNG Rand.save_file('/tmp/randpool.dat') # extend list of recipents with bcc addresses to.extend(bcc) # finally send mail p = Popen(["/usr/sbin/sendmail", "-fvpn@charite.de", "-oi", COMMASPACE.join(to)], stdin=PIPE, universal_newlines=True) p.communicate(out.read())