Ejemplo n.º 1
0
    def recv_mail(self):
        if not self.downloader:
            slog.warning("downloader not login")
            return False

        self.downloader.select()  # Select inbox or default namespace
        (retcode, messages) = self.downloader.search(None, '(UNSEEN)')
        if retcode != 'OK':
            slog.warning("read mail from server failed")
            return False

        if not os.path.exists("./downmail"):
            os.mkdir("./downmail")

        for num in messages[0].split():
            slog.info('Processing: {0}'.format(num))
            typ, data = self.downloader.fetch(num.decode('utf-8'), '(RFC822)')
            # 标记已读
            sr = self.downloader.store(num, '+FLAGS', '\Seen')
            # 标记删除
            #sr = downloader.store(num, '+FLAGS', '\\Deleted')
            email_message = email.message_from_string(
                data[0][1].decode('utf-8'))

            # mail to string
            fp = StringIO()
            g = generator.Generator(fp, mangle_from_=True, maxheaderlen=60)
            g.flatten(email_message)
            email_text = fp.getvalue()

            # mail_string to json_string
            pmail = mailparser.parse_from_string(email_text)
            email_json = pmail.mail_json
            # mail to json obj
            email_data = json.loads(email_json)

            # 处理邮件
            self.handle_mail(email_data)

            subject = email_data.get('subject')
            body = email_data.get('body')
            slog.info("get mail: subject[{0}] body.size[{1}]".format(
                subject, len(body)))

            filename = './downmail/{0}.eml'.format(subject)
            with open(filename, 'w') as fout:
                gr = generator.Generator(fout)
                gr.flatten(email_message)
                #fout.write(email_text)
                fout.close()

            filename_j = './downmail/{0}.json'.format(subject)
            with open(filename_j, 'w') as fjout:
                fjout.write(
                    json.dumps(email_data, indent=4, ensure_ascii=False))
                fjout.close()

            slog.info("save {0} ok,\n".format(filename))

        return True
Ejemplo n.º 2
0
    def save_eml(self):
        header, msg = [], ''
        header.append(self.subject.text())
        header.append(self.recipient_name.text())
        header.append(self.recipient.text())
        header.append('*****@*****.**')
        annex_file = self.annex_file.text().split(',')
        html = self.textEdit.toPlainText()

        if self.current_eml_file:
            msg = ''
            try:
                msg = gm.update_eml(self.current_eml_file, header[3], html,
                                    [header[1], header[2]])
                if self.annex_checkBox.checkState():
                    gm.msg_add_annex(msg, annex_file)
            except:
                msg = gm.gen_eml(header, html, annex_file)

            with open(self.current_eml_file + '.new', 'w') as outfile:
                gen = generator.Generator(outfile)
                gen.flatten(msg)
        else:
            if self.annex_checkBox.checkState():
                msg = gm.gen_eml(header, html, annex_file)
            else:
                msg = gm.gen_eml(header, html)

            directory = QFileDialog.getExistingDirectory(self, "選取資料夾", "./")
            with open(directory + '/' + header[0] + '.eml', 'w') as outfile:
                gen = generator.Generator(outfile)
                gen.flatten(msg)
Ejemplo n.º 3
0
    def __ConfigureMultipartRequest(self, http_request):
        """Configure http_request as a multipart request for this upload."""
        # This is a multipart/related upload.
        msg_root = mime_multipart.MIMEMultipart('related')
        # msg_root should not write out its own headers
        setattr(msg_root, '_write_headers', lambda self: None)

        # attach the body as one part
        msg = mime_nonmultipart.MIMENonMultipart(
            *http_request.headers['content-type'].split('/'))
        msg.set_payload(http_request.body)
        msg_root.attach(msg)

        # attach the media as the second part
        msg = mime_nonmultipart.MIMENonMultipart(*self.mime_type.split('/'))
        msg['Content-Transfer-Encoding'] = 'binary'
        msg.set_payload(self.stream.read())
        msg_root.attach(msg)

        # encode the body: note that we can't use `as_string`, because
        # it plays games with `From ` lines.
        fp = StringIO.StringIO()
        g = email_generator.Generator(fp, mangle_from_=False)
        g.flatten(msg_root, unixfrom=False)
        http_request.body = fp.getvalue()

        multipart_boundary = msg_root.get_boundary()
        http_request.headers['content-type'] = (
            'multipart/related; boundary=%r' % multipart_boundary)
Ejemplo n.º 4
0
  def GenerateMIMEMessageString(self,
                                form,
                                boundary=None,
                                max_bytes_per_blob=None,
                                max_bytes_total=None,
                                bucket_name=None):
    """Generate a new post string from original form.

    Args:
      form: Instance of cgi.FieldStorage representing the whole form
        derived from original post data.
      boundary: Boundary to use for resulting form.  Used only in tests so
        that the boundary is always consistent.
      max_bytes_per_blob: The maximum size in bytes that any single blob
        in the form is allowed to be.
      max_bytes_total: The maximum size in bytes that the total of all blobs
        in the form is allowed to be.
      bucket_name: The name of the Google Storage bucket to uplad the file.

    Returns:
      A string rendering of a MIMEMultipart instance.
    """
    message = self._GenerateMIMEMessage(form,
                                        boundary=boundary,
                                        max_bytes_per_blob=max_bytes_per_blob,
                                        max_bytes_total=max_bytes_total,
                                        bucket_name=bucket_name)
    message_out = cStringIO.StringIO()
    gen = generator.Generator(message_out, maxheaderlen=0)
    gen.flatten(message, unixfrom=False)
    return message_out.getvalue()
Ejemplo n.º 5
0
def generate_email(msg):
    html_data = """ <html><head></head><body>{}</body></html>""".format(msg)

    msg = MIMEMultipart('alternative')
    msg['Subject'] = ""
    msg['From'] = ""
    msg['To'] = ""
    msg['Cc'] = ""
    msg['Bcc'] = ""
    """
    headers = ... dict of header key / value pairs ...
    for key in headers:
        value = headers[key]
        if value and not isinstance(value, basestring):
            value = str(value)
        msg[key] = value
    """
    part = MIMEText(html_data, 'html')
    msg.attach(part)

    #outfile_name = os.path.join("/", "temp", "email_sample.eml")
    outfile_name = "temp_email.eml"
    with open(outfile_name, 'w') as outfile:
        gen = generator.Generator(outfile)
        gen.flatten(msg)  
    return outfile_name  
Ejemplo n.º 6
0
def generate_email(msg):
    """
        Take the html data generated from smartsheet data and create an email
        file to be sent out as a .eml attachment
        return the temp name of the email file which right now is hardcoded
        and re-writen everytime the function is called
    """

    html_data = """ <html><head></head><body>{}</body></html>""".format(msg)

    msg = MIMEMultipart('alternative')
    msg['Subject'] = ""
    msg['From'] = ""
    msg['To'] = ""
    msg['Cc'] = ""
    msg['Bcc'] = ""

    part = MIMEText(html_data, 'html')
    msg.attach(part)

    outfile_name = "events_email.eml"
    with open(outfile_name, 'w') as outfile:
        gen = generator.Generator(outfile)
        gen.flatten(msg)
    return outfile_name
Ejemplo n.º 7
0
def mime_to_string(msg, header_len):
    fp = StringIO()
    g = email_generator.Generator(fp,
                                  mangle_from_=False,
                                  maxheaderlen=header_len)
    g.flatten(msg)
    return fp.getvalue()
Ejemplo n.º 8
0
def GenerateEmailBlob(fromadd, to, subject, cc, bcc, *attachments):
    html_data = """
            <html>
                <head></head>
                <body>
                    <p> hello world </p>
                </body>
            </html>
            """

    msg = MIMEMultipart('alternative')
    msg['Subject'] = subject

    msg['From'] = '"hello world!," <' + fromadd + '>'
    # +re.findall(r"^[^@]+", From)+
    msg['To'] = to
    msg['Cc'] = cc
    msg['Bcc'] = bcc
    msg['Date'] = str(datetime.datetime.now())
    part = MIMEText(html_data, 'html')
    msg.attach(part)

    for file in attachments:
        part = MIMEBase('application', "octet-stream")
        part.set_payload(open(file, "rb").read())
        Encoders.encode_base64(part)
        part.add_header('Content-Disposition', 'attachment; filename=' + file)
        msg.attach(part)

    outfile_name = ("eml/" + fromadd)
    with open(outfile_name, 'w') as outfile:
        gen = generator.Generator(outfile)
        gen.flatten(msg)

    return outfile_name
Ejemplo n.º 9
0
def messageToFile(message):
    """
    Flattens a message into a file-like object.
    """
    outFile = StringIO()
    messageGenerator = generator.Generator(outFile, False)
    messageGenerator.flatten(message)
    outFile.seek(0, 0)
    return outFile
Ejemplo n.º 10
0
def downloadMail(email_message, sender):

    # create directory if not exist
    filePath = os.path.join(directoryName, sender)
    if not os.path.exists(filePath):
        os.makedirs(filePath)

    for part in email_message.walk():

        # extract and format date
        date = email_message['Date']
        date_time_obj = ''
        try:
            date_time_obj = parse(date)
        except:
            print(date)

        # extract subject and dir name
        file_storage = str(date_time_obj.year) + str(
            date_time_obj.strftime('%m')) + str(date_time_obj.strftime('%d'))
        subject = re.sub(r"[^a-zA-Z0-9]+", ' ',
                         email_message['subject']).strip()

        file_path_subject = filePath + "/" + file_storage

        if not os.path.exists(file_path_subject):
            os.makedirs(file_path_subject)

        if not os.path.isfile(file_path_subject):

            # download email text into eml format
            o_file_name = subject + '.eml'
            output_file = os.path.join(file_path_subject, o_file_name)
            with open(output_file, 'w') as outfile:
                try:
                    gen = generator.Generator(outfile)
                    gen.flatten(email_message)
                except:
                    continue

        # checking if data is available
        if part.get_content_maintype() == 'multipart':
            continue
        if part.get('Content-Disposition') is None:
            continue
        filename = part.get_filename()
        data = part.get_payload(decode=True)
        if not data:
            continue
        if filename is None:
            continue
        try:
            attachment = open(os.path.join(file_path_subject, filename), 'wb')
            attachment.write(data)
            attachment.close()
        except:
            continue
Ejemplo n.º 11
0
def main():
    outfile_name = 'QuarterlyReportEmail.eml'

    #----- CLI parsing section <start>-----------------------------
    parser = GooeyParser(description="ETA Prototype")
    parser.add_argument('eml', type=str, widget='FileChooser', help='The eml to scan')
    args = parser.parse_args()
    #----- CLI parsing section <end>-------------------------------

    #----- CSV extraction section <start>--------------------------
    with open(args.eml, 'r') as f:
        mess = message_from_file(f)
    payloads = mess.get_payload()
    payload_types = [p.get_content_type() for p in payloads]

    csv_payloads_indexes = [i for i in range(len(payloads)) if payload_types[i]=='text/csv']
    csv_attachments_as_strings = [payloads[i].get_payload(decode=True).decode('UTF-8') for i in csv_payloads_indexes]
    #----- CSV extraction section <end>----------------------------

    #----- CSV processing section <start>--------------------------
    reports = []
    safe_csvs = []
    for index,attachment in enumerate(csv_attachments_as_strings):
        formulae_occurances = scan_csv.detect_formulae(attachment) # TODO: find how to auto-detect delimiter
        malicious_cells = scan_csv.detect_malicious_cells(formulae_occurances)
        report = scan_csv.generate_report(formulae_occurances, malicious_cells)
        safe_csv = scan_csv.generate_protected_csv(attachment, malicious_cells)
        if report is not None:
            reports.append("ProofPoint has noticed that attachment {} is suspicious:\r\n{}".format(payloads[index].get_filename(), report))
        if len(formulae_occurances) > 0:
            safe_csvs.append(safe_csv)
    #----- CSV processing section <end>----------------------------

    #----- Reports + safe CSV into email section <start>-----------
    with open(args.eml, 'r') as f:
        mess = message_from_file(f)

    for index, report in enumerate(reports):
        tempfile_report = StringIO(report)
        tempfile_csv = StringIO(safe_csvs[index])
        report_message = MIMEApplication(tempfile_report.read(), Name='ProofPoint_Warning_{}.txt'.format(index+1))
        report_message['Content-Disposition'] = 'attachment; filename="ProofPoint_Warning_{}.txt"'.format(index+1)
        safe_csv = MIMEApplication(tempfile_csv.read(), Name='ProofPoint_Secured_{}.csv'.format(index+1))
        safe_csv['Content-Disposition'] = 'attachment; filename="ProofPoint_Secured_{}.csv"'.format(index+1)
        mess.attach(report_message)
        mess.attach(safe_csv)

    if len(reports) > 0:
        warning = MIMEText(StringIO('<H2 style="color:red">ProofPoint has detected potential threats in an attachment to this email,<br/> see the ProofPoint_Warning attachments for more details</H2>').read())
        warning.set_default_type('text/html')
        mess.attach(warning)

    with open(outfile_name, 'w') as outfile:
            gen = generator.Generator(outfile)
            gen.flatten(mess)
Ejemplo n.º 12
0
 def as_string(self, unixfrom=False, linesep='\n'):
     """Return the entire formatted message as a string.
     Optional `unixfrom' when True, means include the Unix From_ envelope
     header.
     This overrides the default as_string() implementation to not mangle
     lines that begin with 'From '. See bug #13433 for details.
     """
     fp = StringIO()
     g = generator.Generator(fp, mangle_from_=False)
     g.flatten(self, unixfrom=unixfrom)
     return fp.getvalue()
Ejemplo n.º 13
0
def save_webex_email(site,
                     addr_to,
                     addr_from,
                     subject,
                     content,
                     where_to_save='sent-webex',
                     others=None):
    """
    Save webex email on disk.
    `addr_to` is a list; if there is more than one recipient,
    adds a 'To' header with each email address.

    """
    save_path = get_log_dir(site)
    join = os.path.join
    filename = None

    if save_path:
        save_path = join(save_path, where_to_save)
        if not os.path.exists(save_path):
            os.makedirs(save_path)

        # Generate email filename according to zope.sendmail.maildir
        # but instead of hostname use site_id
        randmax = 0x7fffffff
        timestamp = int(time.time())
        unique = '%d.%d.%s.%d' % (timestamp, os.getpid(), site.getId(),
                                  random.randrange(randmax))
        filename = join(save_path, unique)
        message_file = os.open(filename, os.O_CREAT | os.O_EXCL | os.O_WRONLY,
                               0600)
        generator = email_generator.Generator(os.fdopen(message_file, 'w'))

        # Add multiple 'To' headers if there is more than one recipient
        if len(addr_to) > 1:
            email_message = create_message(content, addr_to[0], addr_from,
                                           subject)
            addr_to.remove(addr_to[0])
            for mail in addr_to:
                email_message['To'] = mail
        else:
            email_message = create_message(content, addr_to, addr_from,
                                           subject)
        # hide meeting info in header field
        email_message['X-Accept-Webex-Data'] = json.dumps(others)

        # Save email in specified file
        generator.flatten(email_message)
    else:
        mail_logger.warning("The webex email could not be saved on the disk."
                            "There is missing configuration(SITES_LOG_PATH)."
                            "Please contact the platform maintainers.")
    return filename
Ejemplo n.º 14
0
def save_bulk_email(site,
                    addr_to,
                    addr_from,
                    subject,
                    content,
                    where_to_save='sent-bulk',
                    addr_cc=[]):
    """
    Save bulk email on disk.
    `addr_to` is a list; if there is more than one recipient,
    adds a 'To' header with each email address.

    """
    save_path = get_log_dir(site)
    join = os.path.join
    filename = None

    if save_path:
        save_path = join(save_path, where_to_save)
        if not os.path.exists(save_path):
            os.makedirs(save_path)

        # Generate email filename according to zope.sendmail.maildir
        # but instead of hostname use site_id
        randmax = 0x7fffffff
        timestamp = int(time.time())
        unique = '%d.%d.%s.%d' % (timestamp, os.getpid(), site.getId(),
                                  random.randrange(randmax))
        filename = join(save_path, unique)
        message_file = os.open(filename, os.O_CREAT | os.O_EXCL | os.O_WRONLY,
                               0600)
        generator = email_generator.Generator(os.fdopen(message_file, 'w'))

        # Add multiple 'To' headers if there is more one receipent
        if len(addr_to) > 1:
            email_message = create_message(content, addr_to[0], addr_from,
                                           subject)
            addr_to.remove(addr_to[0])
            for mail in addr_to:
                email_message['To'] = mail
        else:
            email_message = create_message(content, addr_to, addr_from,
                                           subject)
        for mail in addr_cc:
            email_message['Cc'] = mail
        # Save email in specified file
        generator.flatten(email_message)
    else:
        mail_logger.warning("The bulk email could not be saved on the disk."
                            " Missing configuration for SITES_LOG_PATH?")
    return filename
Ejemplo n.º 15
0
def create_eml(send_from, send_to, subject, message):
    msg = MIMEMultipart()
    msg['From'] = send_from
    msg['To'] = send_to
    msg['Date'] = formatdate(localtime=True)
    msg['Subject'] = subject
    msg['Message-ID'] = "#MessageID"

    msg.attach(MIMEText(message))
    msg.attach(MIMEMultipart())

    with open("email.eml", 'w') as outfile:
        gen = generator.Generator(outfile)
        gen.flatten(msg)
Ejemplo n.º 16
0
    def recv_mail_weibo(self, subject_pattern, from_email_pattern):
        if not self.downloader:
            slog.warning("downloader not login")
            if not self.login():
                return

        self.downloader.select()  # Select inbox or default namespace
        (retcode, messages) = self.downloader.search(None, '(UNSEEN)')
        if retcode != 'OK':
            slog.warning("read mail from server failed")
            return False

        for num in messages[0].split():
            slog.info('Processing: {0}'.format(num))
            typ, data = self.downloader.fetch(num.decode('utf-8'), '(RFC822)')
            email_message = email.message_from_string(
                data[0][1].decode('utf-8'))

            # mail to string
            fp = StringIO()
            g = generator.Generator(fp, mangle_from_=True, maxheaderlen=60)
            g.flatten(email_message)
            email_text = fp.getvalue()

            # mail_string to json_string
            pmail = mailparser.parse_from_string(email_text)
            email_json = pmail.mail_json
            # mail to json obj
            email_data = json.loads(email_json)
            subject = email_data.get('subject')
            if subject.find(subject_pattern) == -1:
                continue
            from_email = email_data.get('from')[0]  # list
            if from_email_pattern not in from_email:
                continue

            # 标记已读
            sr = self.downloader.store(num, '+FLAGS', '\Seen')
            # 标记删除
            #sr = downloader.store(num, '+FLAGS', '\\Deleted')

            # find target email
            body = email_data.get('body')
            slog.info("read email: subject:{0} body size:{1}".format(
                subject, len(body)))
            vcode = body.split('\n')[0]
            return vcode

        return ''
Ejemplo n.º 17
0
    def as_string(self, unixfrom=False):
        """Return the entire formatted message as a string.
        Optional `unixfrom' when True, means include the Unix From_ envelope
        header.

        This overrides the default as_string() implementation to not mangle
        lines that begin with 'From '. See bug #13433 for details.
        """
        fp = six.StringIO()
        g = generator.Generator(fp, mangle_from_=False)
        if sys.version_info < (2, 6, 6) and isinstance(self._payload,
                                                       six.text_type):
            self._payload = self._payload.encode(self._charset.output_charset)
        g.flatten(self, unixfrom=unixfrom)
        return fp.getvalue()
Ejemplo n.º 18
0
    def _SerializeRequest(self, request):
        """Convert a http_wrapper.Request object into a string.

        Args:
          request: A http_wrapper.Request to serialize.

        Returns:
          The request as a string in application/http format.
        """
        # Construct status line
        parsed = urllib_parse.urlsplit(request.url)
        request_line = urllib_parse.urlunsplit(
            (None, None, parsed.path, parsed.query, None))
        status_line = u' '.join((
            request.http_method,
            request_line.decode('utf-8'),
            u'HTTP/1.1\n'
        ))
        major, minor = request.headers.get(
            'content-type', 'application/json').split('/')
        msg = mime_nonmultipart.MIMENonMultipart(major, minor)

        # MIMENonMultipart adds its own Content-Type header.
        # Keep all of the other headers in `request.headers`.
        for key, value in request.headers.items():
            if key == 'content-type':
                continue
            msg[key] = value

        msg['Host'] = parsed.netloc
        msg.set_unixfrom(None)

        if request.body is not None:
            msg.set_payload(request.body)

        # Serialize the mime message.
        str_io = six.StringIO()
        # maxheaderlen=0 means don't line wrap headers.
        gen = generator.Generator(str_io, maxheaderlen=0)
        gen.flatten(msg, unixfrom=False)
        body = str_io.getvalue()

        # Strip off the \n\n that the MIME lib tacks onto the end of the
        # payload.
        if request.body is None:
            body = body[:-2]

        return status_line + body
Ejemplo n.º 19
0
def gen_eml(frm, subj, text, attch):

    html_data = text

    msg = MIMEMultipart('mixed')
    msg['Subject'] = subj
    msg['From'] = formataddr((frm, gen_email_addr(frm)))
    msg['To'] = emlto
    #msg['Reply-To'] = formataddr((frm,gen_email_addr(frm)))

    part = MIMEText(html_data, 'plain')
    msg.attach(part)

    # open the file to be sent
    filename = attch
    #flnmencdd = encode("MIME-Q",filename)
    attachment = open(attch, "rb")

    # instance of MIMEBase and named as p
    p = MIMEBase('application', 'binary')  #; name= % filename

    # To change the payload into encoded form
    p.set_payload((attachment).read())

    # encode into base64
    encoders.encode_base64(p)

    #FILENAME=FILENAME WO BRACKETS OR OTHER SIGNS AND THEY ARE DIFFERENT FILENAMES!
    p.add_header('Content-Disposition', 'attachment', filename=filename)

    # attach the instance 'p' to instance 'msg'
    msg.attach(p)

    if sendmsg:
        server = smtplib.SMTP_SSL(smtp_creds[0].rstrip(), 465)
        server.login(smtp_creds[1].rstrip(), smtp_creds[2].rstrip())
        server.set_debuglevel(0)
        server.sendmail(formataddr((frm, gen_email_addr(frm))), emlto,
                        msg.as_string())
        server.quit()

    if genfile:
        cwd = os.getcwd()
        msgnm = "tstmsg" + f'{random.randrange(100,999999,1)}' + ".eml"
        outfile_name = os.path.join(cwd, msgnm)
        with open(outfile_name, 'w') as outfile:
            gen = generator.Generator(outfile)
            gen.write(msg.as_string())
Ejemplo n.º 20
0
    def GenerateMIMEMessageString(self, form, boundary=None):
        """Generate a new post string from original form.

    Args:
      form: Instance of cgi.FieldStorage representing the whole form
        derived from original post data.
      boundary: Boundary to use for resulting form.  Used only in tests so
        that the boundary is always consistent.

    Returns:
      A string rendering of a MIMEMultipart instance.
    """
        message = self._GenerateMIMEMessage(form, boundary=boundary)
        message_out = cStringIO.StringIO()
        gen = generator.Generator(message_out, maxheaderlen=0)
        gen.flatten(message, unixfrom=False)
        return message_out.getvalue()
Ejemplo n.º 21
0
 def saveToFile(self):
     name = self.a_data["Your name"].split(" ")
     module = self.a_data["Module Code"].replace(" ", "").upper()[:8]
     ts = int(time.time())
     filename = ""
     for n in name:
         filename += n.capitalize()
         filename += "_"
     filename += str(module)
     filename += "_"
     filename += str(ts)
     with open('email/{0}/{1}.eml'.format(self.dirname, filename),
               'w') as outfile:
         gen = generator.Generator(outfile)
         gen.flatten(self.msg)
         print('Saving "email/{0}/{1}.eml to file'.format(
             self.dirname, filename))
Ejemplo n.º 22
0
    def save_message_to_client(mailfrom, rcp, data):
        client_name = rcp.split('@')[0]
        client_path = os.getcwd() + '\\Clients\\' + client_name
        if not os.path.exists(client_path):
            os.makedirs(client_path)

        msg = email.message_from_string(data)

        t_stamp = str(time.time()).replace('.', '')

        f_name = client_path + '\\' + t_stamp + '.elm'

        with open(f_name, 'w') as out:
            gen = g.Generator(out)
            gen.flatten(msg)

        return
Ejemplo n.º 23
0
    def mk_eml(self, filename):
        from email import generator
        from email.mime.multipart import MIMEMultipart
        from email.mime.text import MIMEText

        ## Get the header information
        mail = MIMEMultipart('alternative')
        mail['Subject'] = 'A Test of file conversion'
        mail['From'] = filename + '@email.com'
        mail['To'] = '*****@*****.**'
        ## Create the body of the email
        body = MIMEText(self.html_data(), 'html')
        mail.attach(body)
        ## Save the file
        with open("../New_Files/" + filename + '.eml', 'w+') as eml_file:
            out = generator.Generator(eml_file)
            out.flatten(mail)
        print("Succesfully Created", '../New_Files/' + filename + '.eml')
def write_message(output_dir: str,
                  transaction_id: str,
                  message: MIMEMessage,
                  suffix: str = "") -> None:
    """Write a message to an EML file in a given location.

    This is useful for if you want to open a reconstructed email in outlook.

    Args:
        output_dir (str): The directory to write the file to.
        transaction_id (str): The transaction ID of the email.
        message (MIMEMessage): The parsed MIME message to write.
        suffix (str): The suffix to add to the filename.
    """
    filename = transaction_id + suffix + ".eml"
    logging.info(f"    Writing message '{filename}'")
    with open(join(output_dir, filename), "w") as eml_file:
        gen = generator.Generator(eml_file)
        gen.flatten(message)
Ejemplo n.º 25
0
def sendLog():
    config.logger.info("util:sendLog()")
    from email import encoders, generator
    from email.mime.base import MIMEBase
    from email.mime.multipart import MIMEMultipart
    from email.mime.text import MIMEText
    message = MIMEMultipart()
    if config.app_window.plus_email is not None:
        message['From'] = config.app_window.plus_email
    message["To"] = "{}@{}".format(config.log_file_account,
                                   config.log_file_domain)
    message["Subject"] = "artisan.plus client log"
    message["X-Unsent"] = "1"
    #message["X-Uniform-Type-Identifier"] = "com.apple.mail-draft"
    message.attach(
        MIMEText(
            "Please find attached the artisan.plus log file written by Artisan!\nPlease forward this email to {}\n--\n"
            .format(message["To"]), "plain"))
    with open(config.log_file_path, "rb") as attachment:
        # Add file as application/octet-stream
        # Email client can usually download this automatically as attachment
        part = MIMEBase("application", "octet-stream")
        part.set_payload(attachment.read())
    # Encode file in ASCII characters to send by email
    encoders.encode_base64(part)
    # Add header as key/value pair to attachment part
    part.add_header(
        "Content-Disposition",
        "attachment; filename= {}{}".format(config.log_file, ".log"))
    # Add attachment to message and convert message to string
    message.attach(part)
    # Save message to file tmp file
    tmpfile = QDir(QDir.tempPath()).filePath("plus-log.eml")
    try:
        os.remove(tmpfile)
    except OSError:
        pass
    with open(tmpfile, 'w') as outfile:
        gen = generator.Generator(outfile)
        gen.flatten(message)
    QDesktopServices.openUrl(QUrl.fromLocalFile(tmpfile))
Ejemplo n.º 26
0
def create_mail(
    is_from='*****@*****.**',
    to='',
    cc='',
    bcc='',
    subject='',
    text='',
    attachments=[],
    output_file='mail.eml',
):

    # Creating `eml` file
    #
    # Adding message header
    mail = MIMEMultipart()
    mail['Subject'] = subject
    mail['To'] = to
    mail['From'] = is_from
    mail['Cc'] = cc
    mail['Bcc'] = bcc
    mail['Date'] = get_rfc2822_date()

    # Adding message text
    data = ('<html><head></head><body>' + example.text + '<p>' + text +
            '</p>' + example.signature + '</body></html>')
    body = MIMEText(data, 'html', 'utf-8')
    mail.attach(body)

    # Adding message attachments
    if attachments:
        for attachment in attachments:
            attachment = add_attachment(attachment)
            mail.attach(attachment)

    # Writing message to disk
    with open(output_file, 'w') as file:
        output = generator.Generator(file)
        output.flatten(mail)

    return True
    def eml_save(self):
        header, msg = [], ''
        header.append(self.in_edit_subject.text())
        header.append(self.in_edit_sender_name.text())
        header.append(self.in_edit_sender.text())
        header.append('*****@*****.**')
        annex_file = self.in_edit_annex.text().split(',')
        html = self.in_edit_html.toPlainText()

        if not any(header[:3]) or not html:
            return

        try:        
            msg = gm.gen_eml(header, html, annex_file) if self.cb_edit_annex.isChecked() else gm.gen_eml(header, html)

            file_path, _ = QFileDialog.getSaveFileName(self, '另存為...', './', 'Excel Files (*.eml)')
            with open(file_path, 'w') as outfile:
                gen = generator.Generator(outfile)
                gen.flatten(msg)
            
            QMessageBox.information(self, 'Success!', '儲存成功!', QMessageBox.Ok)
        except:
            QMessageBox.warning(self, 'Failed!', '儲存失敗!', QMessageBox.Ok)
Ejemplo n.º 28
0
 def save_as_eml(self):
     if self.path is None:
         raise Exception("read msg first")
     msg = MIMEMultipart()
     msg["Subject"] = self.subject
     msg["From"] = self.sender
     msg["To"] = self.recipients_to
     msg["Cc"] = self.recipients_cc
     msg["Date"] = self.date_exp
     msg.attach(MIMEText(self.body, self.bodyformat))
     i = 1
     for a in self.attachments:
         path = self._attachment_filepath(a, i)
         if self._ignore_attachment(path):
             log.warning(f"Attachment file '{path.name}' is ignored.")
             continue
         log.debug(f"save_as_eml() Save '{path}'")
         a.SaveAsFile(str(path))
         msg.attach(self._read_attachment(path, a.filename))
         i += 1
     with open(str(self.path), "w") as f:
         gen = generator.Generator(f)
         gen.flatten(msg)
Ejemplo n.º 29
0
    def __ConfigureMultipartRequest(self, http_request):
        """Configure http_request as a multipart request for this upload."""
        # This is a multipart/related upload.
        msg_root = mime_multipart.MIMEMultipart('related')
        # msg_root should not write out its own headers
        setattr(msg_root, '_write_headers', lambda self: None)

        # attach the body as one part
        msg = mime_nonmultipart.MIMENonMultipart(
            *http_request.headers['content-type'].split('/'))
        msg.set_payload(http_request.body)
        msg_root.attach(msg)

        # attach the media as the second part
        msg = mime_nonmultipart.MIMENonMultipart(*self.mime_type.split('/'))
        msg['Content-Transfer-Encoding'] = 'binary'
        msg.set_payload(self.stream.read())
        msg_root.attach(msg)

        # NOTE: We encode the body, but can't use
        #       `email.message.Message.as_string` because it prepends
        #       `> ` to `From ` lines.
        # NOTE: We must use six.StringIO() instead of io.StringIO() since the
        #       `email` library uses cStringIO in Py2 and io.StringIO in Py3.
        fp = six.StringIO()
        g = email_generator.Generator(fp, mangle_from_=False)
        g.flatten(msg_root, unixfrom=False)
        http_request.body = fp.getvalue()

        multipart_boundary = msg_root.get_boundary()
        http_request.headers['content-type'] = (
            'multipart/related; boundary=%r' % multipart_boundary)

        body_components = http_request.body.split(multipart_boundary)
        headers, _, _ = body_components[-2].partition('\n\n')
        body_components[-2] = '\n\n'.join([headers, '<media body>\n\n--'])
        http_request.loggable_body = multipart_boundary.join(body_components)
Ejemplo n.º 30
0
def create_mail(
    is_from='',
    goes_to='',
    cc='',
    bcc='',
    subject='',
    text='',
    attachments=[],
    output_path='mail.eml',
):
    # Create `eml` file
    # (1) Add message header
    mail = MIMEMultipart()
    mail['Subject'] = subject
    mail['To'] = goes_to
    mail['From'] = is_from
    mail['Cc'] = cc
    mail['Bcc'] = bcc
    mail['Date'] = get_rfc2822_date()

    # (2) Add message body
    body = MIMEText(text, 'html', 'utf-8')
    mail.attach(body)

    # (3) Add attachments
    if attachments:
        for attachment in attachments:
            attachment = add_attachment(attachment)

            if attachment:
                mail.attach(attachment)

    # (4) Write contents
    with open(output_path, 'w') as file:
        output_path = generator.Generator(file)
        output_path.flatten(mail)