Example #1
0
def load_attachment(filename, encoding='us-ascii'):
    mimetype,content_encoding = _mimetypes.guess_type(filename)
    if mimetype is None or content_encoding is not None:
        mimetype = 'application/octet-stream'
    maintype,subtype = mimetype.split('/', 1)
    _pgp_mime.LOG.info('loading attachment {} as {} ({})'.format(
            filename, mimetype, content_encoding))
    if maintype == 'text':
        text = read_file(filename=filename, encoding=encoding)
        attachment = _pgp_mime.encodedMIMEText(text)
        del attachment['content-disposition']
    else:
        data = open(filename, 'rb').read()
        if maintype == 'application':
            attachment = _MIMEApplication(data, subtype)
        elif maintype == 'audio':
            attachment = _MIMEAudio(data)
        elif maintype == 'image':
            attachment = _MIMEImage(data)
        else:
            attachment = _MIMENonMultipary(maintype, subtype)
            attachment.set_payload(data, _encode_base64)
    attachment.add_header(
        'Content-Disposition', 'attachment', filename=filename)
    return attachment
Example #2
0
    def _attach_files(self, outer):
        ''' attach file list '''
        for attachment in self._attachments:
            filename = attachment
            cid = None
            if (isinstance(attachment, list) or isinstance(attachment, tuple)
                    and len(attachment) == 2):
                filename, cid = attachment

            ctype, encoding = mimetypes.guess_type(filename)
            if ctype is None or encoding is not None:
                ctype = 'application/octet-stream'
            maintype, subtype = ctype.split('/', 1)
            fp = open(filename, 'rb')
            if maintype == 'text':
                msg = _MIMEText(fp.read(), _subtype=subtype)
            elif maintype == 'image':
                msg = _MIMEImage(fp.read(), _subtype=subtype)
            elif maintype == 'audio':
                msg = _MIMEAudio(fp.read(), _subtype=subtype)
            else:
                msg = _MIMEBase(maintype, subtype)
                msg.set_payload(fp.read())
                _encoder.encode_base64(msg)
            fp.close()

            if cid:
                msg.add_header('Content-ID', '<%s>' % cid)
                msg.add_header('Content-Disposition', 'inline')
            else:
                msg.add_header('Content-Disposition', 'attachment', filename=os.path.basename(filename))
            outer.attach(msg)
        return
Example #3
0
def load_attachment(filename, encoding='us-ascii'):
    mimetype, content_encoding = _mimetypes.guess_type(filename)
    if mimetype is None or content_encoding is not None:
        mimetype = 'application/octet-stream'
    maintype, subtype = mimetype.split('/', 1)
    _pgp_mime.LOG.info('loading attachment {} as {} ({})'.format(
        filename, mimetype, content_encoding))
    if maintype == 'text':
        text = read_file(filename=filename, encoding=encoding)
        attachment = _pgp_mime.encodedMIMEText(text)
        del attachment['content-disposition']
    else:
        data = open(filename, 'rb').read()
        if maintype == 'application':
            attachment = _MIMEApplication(data, subtype)
        elif maintype == 'audio':
            attachment = _MIMEAudio(data)
        elif maintype == 'image':
            attachment = _MIMEImage(data)
        else:
            attachment = _MIMENonMultipary(maintype, subtype)
            attachment.set_payload(data, _encode_base64)
    attachment.add_header('Content-Disposition',
                          'attachment',
                          filename=filename)
    return attachment
Example #4
0
    def attach(self, file_path: str):
        if not _path.isfile(file_path):
            raise RuntimeError("'{}' is not a file.".format(file_path))

        ctype, encoding = _guess_mime_type(file_path)
        if ctype:
            ctype = ctype.split('/')
            if ctype[0] == 'image':
                with open(file_path, 'rb') as f:
                    attachment = _MIMEImage(f.read(), _subtype=ctype[1])
                    attachment.add_header('Content-Disposition', 'attachment', filename=_path.basename(file_path))
                    self._attachments.append(attachment)
            else:
                raise RuntimeError("Unsupported MIME type '{}', file '{}'.".format(repr(ctype), file_path))
        else:
            raise RuntimeError("Cannot guess MIME type for '{}'.".format(file_path))
Example #5
0
def embed_report(report, file_name='reporty', del_files='no',
                 subject='', sender_name='', rec_name='', text=''):
    """ embeds report in custom email, and attaches html files and pngs

    Args:
        report (str): html code
        filename (str): name of html file (if you entered a custom file name in
        'generate report', you must pass that filename through in this function)
        - default is 'reporty'
        del_files (str): 'yes' will delete files - default is 'no' (keep files)
        subject (str): subject of email - default is '' (no subject)
        sender_name (str): name of sender (will be email name no matter what on
        outlook) - default is '' (will result to email address on all platforms)
        rec_name (str): name of receiver (must be left blank for outlook users)
        - default is '' (will result in no send tag for gmail)
        text (str): any extra text you want to send will appear at start of
        email - default is '' (will result to no extra text)

    Returns:
        encoded multipart message
    """

    # declaring message object
    message = _MIMEMultipart()

    # takes custom file name and adds html file extension
    file_name = file_name + ".html"

    # declaring empty file names list
    file_names = []

    # takes filenames from
    if _os.path.exists("filenames.txt"):
        file = open("filenames.txt", "r")
        filenames = file.read()
        file.close()
        _os.remove("filenames.txt")
        file_names = filenames.strip('][').split(', ')
    else:
        pass

    # adds a sender_name, receiver name, and a subject
    if sender_name == '':
        pass
    else:
        message["From"] = str(sender_name)
    if rec_name == '':
        pass
    else:
        rec_name = (str(rec_name)).replace(" ", "_")
        message["To"] = rec_name
    if subject == '':
        pass
    else:
        message["Subject"] = str(subject)

    # attatches 'text' to message
    message.attach(_MIMEText(text, 'plain'))

    # attatches the html attachment to message
    attachment = _MIMEText(report, "html")
    message.attach(attachment)

    # adds a content id to all matplot pngs and attaches images
    if len(file_names) > 0:
        for i in range(len(file_names)):
            f_p = open(file_names[i], 'rb')
            image = _MIMEImage(f_p.read(), filename=file_names[i])
            _encoders.encode_base64(image)
            f_p.close()
            image.add_header('Content-ID', '<' + file_names[i].replace('.png', '') + '>')
            image.add_header('Content-Disposition', 'inline', filename=file_names[i])
            message.attach(image)
    else:
        pass

    # opens the html file and adds 'payload'
    attach_file = open(file_name, 'rb')
    payload = _MIMEBase('application', 'octate-stream')
    payload.set_payload(attach_file.read())

    # encodes payload
    _encoders.encode_base64(payload)

    # add payload header with filename
    payload.add_header('Content-Disposition', 'attachment', filename=file_name)

    # attatches html file to the email
    message.attach(payload)
    attach_file.close()

    # creates final message (str)
    final_message = message.as_string()

    # deletes extra files if user specifies
    if del_files == 'yes':
        if _os.path.exists(file_name):
            _os.remove(file_name)
        else:
            pass
        for i in range(len(file_names)):
            if _os.path.exists(file_names[i]):
                _os.remove(file_names[i])
    else:
        pass

    # returns the mime multipart message (str)
    return final_message
Example #6
0
                    outer = _MIMEMultipart()
                    outer['Content-Type'] = 'text/plain; charset=utf-8'
                    outer['Subject'] = encode_base64(_settings.EMAIL_SUBJECT)
                    outer['From'] = format_named_address(
                        _settings.EMAIL_FROM_NAME, _settings.EMAIL_FROM_ADR)
                    outer['To'] = format_named_address(name, email)

                    # Get source svg name:
                    source_pdf = _path.join(_settings.DEST_GENERATED_FOLDER,
                                            f"{index}.pdf")

                    # Set the content of the attachment:
                    ctype, encoding = _mimetypes.guess_type(source_pdf)
                    maintype, subtype = ctype.split('/', 1)
                    with open(source_pdf, 'rb') as fp:
                        msg = _MIMEImage(fp.read(), _subtype=subtype)

                    # Set the filename parameter
                    msg.add_header('Content-Disposition',
                                   'attachment',
                                   filename=_settings.EMAIL_PDF)
                    outer.attach(msg)

                    # Add our message:
                    part1 = _MIMEText(body, 'plain', 'UTF-8')
                    outer.attach(part1)

                    # Now send the message
                    try:
                        smtp.sendmail(_settings.SMTP_USER, email,
                                      outer.as_bytes())
Example #7
0
    def send(self,
             receiver,
             cc=None,
             bcc=None,
             subject: str = None,
             message: str = None,
             image: str = None,
             audio: str = None,
             file: str = None):
        """
        :param cc: Email Address as String or List. (Carbon Copy)
        :param bcc: Email Address as String or List. (Blind Carbon Copy)
        :param receiver: Email Address as String or List
        :param subject: Message Title
        :param message: Your Message
        :param image: Image File Name
        :param audio: Audio File Name
        :param file: File Name
        :return: Boolean
        """

        msg = _MIMEMultipart()
        msg['Subject'] = subject
        msg['From'] = self.email

        try:
            if message is not None:
                text = _MIMEText(message)
                msg.attach(text)

            if image is not None:
                image_data = self._file_reader(image)
                image = _MIMEImage(_imagedata=image_data, name=image)
                msg.attach(image)

            if audio is not None:
                audio_data = self._file_reader(audio)
                audio = _MIMEAudio(_audiodata=audio_data,
                                   name=audio,
                                   _subtype='')
                msg.attach(audio)

            if file is not None:
                file_data = self._file_reader(file)
                file = _MIMEApp(_data=file_data, name=file)
                msg.attach(file)
        except Exception:
            print('Error: File Not Found!')
            self.status = False
            return False

        send_info = []
        multi_info = {}

        if 'list' in str(type(receiver)):
            self.count_rec = len(receiver)
            receiver = ','.join(i for i in receiver)

        if 'list' in str(type(cc)):
            self.count_cc = len(cc)
            cc = ','.join(i for i in cc)

        if 'list' in str(type(bcc)):
            self.count_bcc = len(bcc)
            bcc = ','.join(i for i in bcc)

        if self.__login():
            msg['To'] = receiver
            msg['CC'] = cc
            msg['BCC'] = bcc

            if self.multi:
                for _ in range(self.__repeat):
                    try:
                        self.__server.sendmail(from_addr=self.email,
                                               to_addrs=receiver,
                                               msg=msg.as_string())
                    except Exception:
                        if self.__repeat == 1 & self.count_rec == 1:
                            self.status = False
                        else:
                            send_info.append(False)

                    else:
                        if self.__repeat == 1 & self.count_rec == 1:
                            self.status = True
                        else:
                            send_info.append(True)
                            self.status = send_info

                    finally:
                        _sleep(self.__sleep)
            else:
                for rec in receiver.split(','):
                    send_info = []
                    for _ in range(self.__repeat):
                        try:
                            self.__server.sendmail(from_addr=self.email,
                                                   to_addrs=rec,
                                                   msg=msg.as_string())
                        except Exception as e:
                            if self.__repeat == 1 & self.count_rec == 1:
                                self.status = False
                            else:
                                send_info.append(False)

                            if 'OutboundSpamException' in str(e):
                                print(
                                    'Error: Please Login To Your Account And Verify it.'
                                )
                                break

                        else:
                            if self.__repeat == 1 & self.count_rec == 1:
                                self.status = True
                            else:
                                send_info.append(True)
                                self.status = send_info
                                multi_info[rec] = send_info

                        finally:
                            _sleep(self.__sleep)

                    if self.count_rec != 1:
                        self.status = multi_info

        self.__server.close()