Example #1
0
    def set_attachment(file_to_attach):
        """
        Sets type and headers of the attachment file
        :param file_to_attach:
        :return: attachment
        """

        try:
            ctype, encoding = mimetypes.guess_type(file_to_attach)
            if ctype is None or encoding is not None:
                ctype = MIMEBase('application', "octet-stream")

            maintype, subtype = ctype.split("/", 1)

            if maintype == "text":
                fp = open(file_to_attach)
                # Note: we should handle calculating the charset
                attachment = MIMEText(fp.read(), _subtype=subtype)
                fp.close()
            elif maintype == "image":
                fp = open(file_to_attach, "rb")
                attachment = MIMEImage(fp.read(), _subtype=subtype)
                fp.close()
            elif maintype == "audio":
                fp = open(file_to_attach, "rb")
                attachment = MIMEAudio(fp.read(), _subtype=subtype)
                fp.close()
            else:
                fp = open(file_to_attach, "rb")
                attachment = MIMEBase(maintype, subtype)
                attachment.set_payload(fp.read())
                fp.close()
                encoders.encode_base64(attachment)
            attachment.add_header("Content-Disposition",
                                  "attachment",
                                  filename=file_to_attach)
        except IOError:
            LOGGER.error("Error opening attachment file %s" % file_to_attach)
            raise Exception("Error opening attachment file %s" %
                            file_to_attach)

        return attachment