import mimetypes


def get_or_gen_filename(part, idx=0):
    """
    Get the filename from given MIME `part` data or generate filename to be
    used to save its payload later.

    :param part: :class:`email.mime.base.MIMEBase` object
    :return: A filename as a string
    """
    filename = part.get_filename()
    if not filename:
        fileext = mimetypes.guess_extension(part.get_content_type())
        if not fileext:
            fileext = ".bin"
        filename = "part-%03d%s" % (idx, fileext)

    return filename