import re


def formatRFC822Headers(headers):

    """ Convert the key-value pairs in 'headers' to valid RFC822-style
        headers, including adding leading whitespace to elements which
        contain newlines in order to preserve continuation-line semantics.
    """
    munged = []
    linesplit = re.compile(r'[\n\r]+?')

    for key, value in headers:

        vallines = linesplit.split(value)
        while vallines:
            if vallines[-1].rstrip() == '':
                vallines = vallines[:-1]
            else:
                break
        munged.append('%s: %s' % (key, '\r\n  '.join(vallines)))

    return '\r\n'.join(munged)