def get_attachment(self, msg, attach_id): "Get and return an attachment" num = 0 attach_id = int(attach_id) for part in msg.walk(): attachment = part.get_param('attachment', NOTFOUND, 'Content-Disposition') if not attachment is NOTFOUND: filename = part.get_filename(None) if filename: filename = filename.replace(' ', '_') num += 1 if attach_id == num: if part.is_multipart(): data = part.as_string() else: data = part.get_payload(decode=True) attachment = StringIO(data) attachment.content_type = part.get_content_type() attachment.size = len(data) attachment.name = filename return attachment return None