Skip to content

Instantly share code, notes, and snippets.

@oskar456
Created January 4, 2018 14:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save oskar456/5d69f54a957bf9fddbb080416ba80ef7 to your computer and use it in GitHub Desktop.
Save oskar456/5d69f54a957bf9fddbb080416ba80ef7 to your computer and use it in GitHub Desktop.
Milter to fix badly formatted MIME messages
#!/usr/bin/env python3
import email
from email.mime.multipart import MIMEMultipart
import sys
from subprocess import Popen, PIPE
def reformat(msg):
"""Reformat the MIME parts of the message to a sane one."""
newmsg = MIMEMultipart()
for name, value in msg.items():
if name not in ['Content-Type', 'MIME-Version',
'Content-Length', 'Lines']:
newmsg.add_header(name, value)
textpart = None
htmlpart = None
attachments = []
for part in msg.walk():
if part.get_filename():
attachments.append(part)
elif part.get_content_type() == 'text/plain':
textpart = part
elif part.get_content_type() == 'text/html':
htmlpart = part
content = MIMEMultipart('alternative')
if textpart:
content.attach(textpart)
if htmlpart:
content.attach(htmlpart)
newmsg.attach(content)
for a in attachments:
newmsg.attach(a)
return newmsg
def main():
with sys.stdin:
oldmsg = email.message_from_file(sys.stdin)
assert oldmsg.is_multipart()
newmsg = reformat(oldmsg)
print(newmsg.as_string())
def content_filter():
with sys.stdin:
oldmsg = email.message_from_file(sys.stdin)
newmsg = reformat(oldmsg)
p = Popen(["/usr/sbin/sendmail", "-G", "-i"] + sys.argv[1:],
stdin=PIPE)
p.communicate(newmsg.as_string().encode('utf-8'))
if __name__ == '__main__':
content_filter()
smtpd_sender_restrictions = check_sender_access hash:/etc/postfix/sender_access
local_header_rewrite_clients = permit_mynetworks
fixmime unix - n n - 10 pipe
flags=Rq user=nobody null_sender=
argv=/usr/local/bin/fixmime.py -f ${sender} -- ${recipient}
from.address.of.misbehaving.appliance@domain.org FILTER fixmime:dummy
@oskar456
Copy link
Author

oskar456 commented Jan 4, 2018

This was written some time ago to fix e-mail reports generated by Vmware vSphere Data Protection Appliance. It's authors ignored MIME standards, which resulted in:

  • Date header missing (this can be fixed in MTA)
  • Text and HTML parts are being sent in wrong order, so proper MUA always renders plaintext version only
  • Optional CSV attachment is attached as third alternative body, rendering it instead HTML or text content

As far as I know this appliance is now discontinued. But there may be others that would get use of such milter.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment