Example #1
0
import imaplib
import time

# We can check only that it successfully produces a result,
# not the correctness of the result itself, since the result
# depends on the timezone the machine is in.

timevalues = [
    2000000000, 2000000000.0,
    time.localtime(2000000000), '"18-May-2033 05:33:20 +0200"'
]

for t in timevalues:
    imaplib.Time2Internaldate(t)
Example #2
0
 def test_that_Time2Internaldate_returns_a_result(self):
     # Without tzset, we can check only that it successfully
     # produces a result, not the correctness of the result itself,
     # since the result depends on the timezone the machine is in.
     for t in self.timevalues():
         imaplib.Time2Internaldate(t)
Example #3
0
        part = MIMEApplication(
            fil.read(),
            Name=basename(fileAttach)
        )
    # After the file is closed
    part['Content-Disposition'] = 'attachment; filename="%s"' % basename(
        fileAttach)
    msg.attach(part)
    text = msg.as_string()
    try:
        s.sendmail(loginID, msg["To"], text)
        print('Mail sent to ', msg["To"])
        sheet.cell(column=13, row=i).value = 'sent;'

        writer.writerow({'email': recipient, 'status': 'sent'})

        imap = imaplib.IMAP4_SSL(mail_host, 993)
        imap.login(loginID, loginPass)
        imap.append('HackOLatte', '\\Seen', imaplib.Time2Internaldate(
            time.time()), text.encode('utf8'))

    except Exception as e:
        print('Error {0} wile sending mail to {1}'.format(e, recipient))
        sheet.cell(column=13, row=i).value = 'not sent;'

        writer.writerow({'email': recipient, 'status': 'not sent'})

wb.save(filename=loc)
csvfile.close()
s.quit()
 def test_that_Time2Internaldate_returns_a_result(self):
     for t in self.timevalues():
         imaplib.Time2Internaldate(t)
Example #5
0
    def main(self):
        """This executes the things described in the class description.

        First of all, Rekrybot loops through all found messages, and
        tries to form a summary line about the job posting, such as:

        2: Company name: Some junior position - DL: 15.11.

        It appends these to the beginning of the newsletter, followed by
        all the message bodies of the individual recruitment messages.

        Finally, it creates a blank email message, sets it header data
        accordingly (subject, sender, recipient) and appends the
        previously created content to the message body.
        """

        body = ""
        lines = ""
        contents = ""

        # Index is for tl;dr numbering, thus starting from 1
        index = 1

        # Go through each item in messages and append to mail body
        for i in self.messages:

            # Mail subject
            subject_line = self.parser.strip_string(i[0], self.whitespacechars,
                                                    self.tag_regex,
                                                    self.filler_regex,
                                                    self.symbol_regex)

            if not subject_line:
                subject_line = "Deleted whole subjectline"

            # Form the summary line
            line = self.parser.create_line(index, subject_line,
                                           "DL: " + self.get_deadline(i[1]))

            lines += line

            # Append a recruitment message's body to the contents with
            # the oneliner in the beginning and some whitespace in the end
            contents += line + "\n\n" + i[1] + "\n\n\n\n----\n"

            # Increment index by one and start over
            index += 1

        # Form the email body
        body += lines + "\n\n-----\n" + contents

        # Initialize a new message
        msg = EmailMessage()

        # Set email header
        msg['Subject'] = 'Recruitment mail'
        msg['From'] = '*****@*****.**'
        msg['To'] = '*****@*****.**'

        # Append TL;DR:
        msg.set_content(body)

        # Append the message to drafts
        self.connection.append('Drafts', '',
                               imaplib.Time2Internaldate(time.time()),
                               str(msg).encode('UTF-8'))

        # Select all messages in recruitment
        typ, [response] = self.connection.search(None, 'All')

        # If something goes wrong, abort mission
        if typ != 'OK':
            raise RuntimeError(response)

        msg_ids = ','.join(response.decode('utf-8').split(' '))

        # Create a timestamp for archive creation
        timestamp = datetime.date.today().isoformat()

        # Create a new arhive mailbox for the messages
        mailboxname = 'Recruitment/archive/' + timestamp
        typ, response = self.connection.create(mailboxname)

        # Copy the messages over to the archive
        self.connection.copy(msg_ids, mailboxname)

        # Close connection, we're done here
        self.connection.close()
Example #6
0
 def __init__(self, func, mdb):
     date = imaplib.Time2Internaldate(time.time())[1:-1]
     IMAPMessage.__init__(self, date, mdb)
     self.func = func
     self.load()
Example #7
0
    def onRetr(self, command, args, response):
        """Classifies the message.  If the result is ham, then simply
        pass it through.  If the result is an unsure or spam, move it
        to the appropriate IMAP folder."""
        # XXX This is all almost from sb_server!  We could just
        # XXX extract that out into a function and call it here.

        # Use '\n\r?\n' to detect the end of the headers in case of
        # broken emails that don't use the proper line separators.
        if re.search(r'\n\r?\n', response):
            # Remove the trailing .\r\n before passing to the email parser.
            # Thanks to Scott Schlesier for this fix.
            terminatingDotPresent = (response[-4:] == '\n.\r\n')
            if terminatingDotPresent:
                response = response[:-3]

            # Break off the first line, which will be '+OK'.
            ok, messageText = response.split('\n', 1)

            try:
                msg = email.message_from_string(messageText,
                                                _class=message.SBHeaderMessage)
                # Now find the spam disposition and add the header.
                (prob, clues) = state.bayes.spamprob(msg.tokenize(),
                                                     evidence=True)

                # Note that the X-SpamBayes-MailID header will be worthless
                # because we don't know the message id at this point.  It's
                # not necessary for anything anyway, so just don't set the
                # [Headers] add_unique_id option.
                msg.addSBHeaders(prob, clues)

                # Check for "RETR" or "TOP N 99999999" - fetchmail without
                # the 'fetchall' option uses the latter to retrieve messages.
                if (command == 'RETR' or
                    (command == 'TOP' and
                     len(args) == 2 and args[1] == '99999999')):
                    cls = msg.GetClassification()
                    dest_folder = None
                    if cls == options["Headers", "header_ham_string"]:
                        state.numHams += 1
                        headers = []
                        for name, value in msg.items():
                            header = "%s: %s" % (name, value)
                            headers.append(re.sub(r'\r?\n', '\r\n', header))
                        body = re.split(r'\n\r?\n', messageText, 1)[1]
                        messageText = "\r\n".join(headers) + "\r\n\r\n" + body
                    elif prob > options["Categorization", "spam_cutoff"]:
                        dest_folder = self.spam_folder
                        state.numSpams += 1
                    else:
                        dest_folder = self.unsure_folder
                        state.numUnsure += 1
                    if dest_folder:
                        msg = StringIO.StringIO(msg.as_string())
                        date = imaplib.Time2Internaldate(time.time())[1:-1]
                        dest_folder.addMessage(msg, (), date)

                        # We have to return something, because the client
                        # is expecting us to.  We return a short message
                        # indicating that a message was intercepted.
                        messageText = self.intercept_message % (prob,)
            except:
                messageText, details = \
                             message.insert_exception_header(messageText)

                # Print the exception and a traceback.
                print >> sys.stderr, details
            retval = ok + "\n" + messageText
            if terminatingDotPresent:
                retval += '.\r\n'
            return retval
        else:
            # Must be an error response.
            return response
                    result = m.uid("COPY", msg_uid, "zzzz_toArchive")
                    if result[0] == "OK":
                        mov, data = m.uid("STORE", msg_uid, "+FLAGS",
                                          "(Deleted)")
                        m.expunge()
                        results_string += " - SUCCESS\n"
                    else:
                        results_string += " - %s  (%s)\n" % (FAIL_STRING,
                                                             str(result))
                else:
                    results_string += ("UNABLE TO MOVE/COPY... [" +
                                       str(mail["From"]) + "] :" +
                                       str(mail["Subject"]))
            results_string += "------------Done\n"
            print results_string
            new_message = email.message.Message()
            new_message["From"] = cred["from_address"]
            new_message["Subject"] = "Messages moved from trash to archive"
            new_message.set_payload(results_string)
            m.append("INBOX", "", imaplib.Time2Internaldate(time.time()),
                     str(new_message))
        except ValueError as exc:
            print("Caught exception: %s" % str(exc))
            print(ERROR_STRING)
        finally:
            if ERROR_STRING in results_string or FAIL_STRING in results_string:
                sys.exit(1)
            else:
                sys.exit(0)
Example #9
0
def send_message(request):
    if request.is_ajax():
        # Get the mailbox you want to record this in

        # Message form values
        subject = request.POST.get('subject', '')
        folder_id = request.POST.get('folder_id', '')
        folder_id = '"{}"'.format(folder_id)

        message = request.POST.get('message', '').encode("utf-8")
        message_id = request.POST.get('message_id', '')
        recipents = request.POST.get('to', '')
        attachments = request.POST.getlist('attachments[]')
        cc_recipents = request.POST.get('CC', '')
        bcc_recipents = request.POST.get('BCC', '')
        compose = request.POST.get('compose', '')

        # Split into recipents array
        recipents = recipents.split(",")
        cc_recipents = cc_recipents.split(",") or None
        bcc_recipents = bcc_recipents.split(",") or None

        # Create a new cnnection
        conn = UserMailbox.objects.get_mailbox(user=request.user)
        connection = conn.get_SMTP_connection()

        matachments = MessageAttachment.objects.filter(pk__in=attachments)

        # Create an e-mail
        email_message = EmailMultiAlternatives(
            subject=subject,
            body=message,
            from_email=conn.username,
            to=recipents,
            bcc=bcc_recipents,  # ['*****@*****.**'],
            cc=cc_recipents,
            headers={'Reply-To': request.user.person.email},
            connection=connection
        )

        email_message.attach_alternative(message, "text/html")

        for a in matachments:
            email_message.attach(a.name, a.document.read())

        if conn.imap_server.use_ssl:
            m = imaplib.IMAP4_SSL(conn.imap_server.host)
        else:
            m = imaplib.IMAP4(conn.imap_server.host)

        m.login(conn.username, conn.password)

        recipents_str = ','.join(recipents)

        if compose == "forward":
            m.select(folder_id)
            status, data = m.fetch(message_id, "(RFC822)")
            email_data = data[0][1]
            m.close()
            m.logout()

            # create a Message instance from the email data
            message = email.message_from_string(email_data)

            # replace headers (could do other processing here)
            message.replace_header("From", conn.username)
            message.replace_header("To", recipents_str)

            # open authenticated SMTP connection and send message with
            # specified envelope from and to addresses
            smtp = smtplib.SMTP_SSL(conn.smtp_server.host, conn.smtp_server.port)
            smtp.login(conn.username, conn.password)
            smtp.sendmail(conn.username, recipents_str, message.as_string())
            smtp.quit()

        if compose == "send":

            email_message.send()

            # Here we have to use plain imaplib :(

            # create the message
            msg = email.message.Message()
            msg['Subject'] = subject
            msg['From'] = conn.username
            msg['To'] = recipents_str
            msg.set_payload(message)

            m.append("INBOX.Sent",
                     'Seen',
                     imaplib.Time2Internaldate(time.time()),
                     str(msg)
                     )

        elif compose == "draft":

            # Here we have to use plain imaplib :(
            if conn.imap_server.use_ssl:
                m = imaplib.IMAP4_SSL(conn.imap_server.host)
            else:
                m = imaplib.IMAP4(conn.imap_server.host)

            m.login(conn.username, conn.password)

            recipents_str = ','.join(recipents)
            # create the message
            msg = email.message.Message()
            msg['Subject'] = subject
            msg['From'] = conn.username
            msg['To'] = recipents_str
            msg.set_payload(message)

            m.append("INBOX.Drafts",
                     '(\Draft)',
                     imaplib.Time2Internaldate(time.time()),
                     str(msg)
                     )


        elif compose == "reply":

            pass

    matachments.delete()
    return HttpResponse('[]', status=200)
 def testDate(self):
     date = imaplib.Time2Internaldate(time.time())[1:-1]
     self.assertEqual(self.msg.date, date)
Example #11
0
def _save_note_to_server(imap, msg):
    """Send msg to server via open IMAP connection imap"""
    # todo: test the \\Seen flag below
    imap.append('Notes', '\\Seen', imaplib.Time2Internaldate(time.time()), str.encode(str(msg)))
Example #12
0
def send(sender, recipient, subject, body, contenttype, datetime, extraheaders=None, mailserver=None, folder=None):
    """Send an email.
    
    All arguments should be Unicode strings (plain ASCII works as well).
    
    Only the real name part of sender and recipient addresses may contain
    non-ASCII characters.
    
    The email will be properly MIME encoded and delivered though SMTP to
    localhost port 25.  This is easy to change if you want something different.
    
    The charset of the email will be the first one out of the list
    that can represent all the characters occurring in the email.
    """

    # Header class is smart enough to try US-ASCII, then the charset we
    # provide, then fall back to UTF-8.
    header_charset = 'ISO-8859-1'
    
    # We must choose the body charset manually
    for body_charset in CHARSET_LIST:
        try:
            body.encode(body_charset)
        except (UnicodeError, LookupError):
            pass
        else:
            break

    # Split real name (which is optional) and email address parts
    sender_name, sender_addr = parseaddr(sender)
    recipient_name, recipient_addr = parseaddr(recipient)
    
    # We must always pass Unicode strings to Header, otherwise it will
    # use RFC 2047 encoding even on plain ASCII strings.
    sender_name = str(Header(unicode(sender_name), header_charset))
    recipient_name = str(Header(unicode(recipient_name), header_charset))
    
    # Make sure email addresses do not contain non-ASCII characters
    sender_addr = sender_addr.encode('ascii')
    recipient_addr = recipient_addr.encode('ascii')
    
    # Create the message ('plain' stands for Content-Type: text/plain)
    msg = MIMEText(body.encode(body_charset), contenttype, body_charset)
    if IMAP_OVERRIDE_TO:
        msg['To'] = IMAP_OVERRIDE_TO
    else:
        msg['To'] = formataddr((recipient_name, recipient_addr))
    msg['Subject'] = Header(unicode(subject), header_charset)
    for hdr in extraheaders.keys():
        try:
            msg[hdr] = Header(unicode(extraheaders[hdr], header_charset))
        except:
            msg[hdr] = Header(extraheaders[hdr])
        
    fromhdr = formataddr((sender_name, sender_addr))
    if IMAP_MUNGE_FROM:
        msg['From'] = extraheaders['X-MUNGED-FROM']
    else:
        msg['From'] = fromhdr

    msg_as_string = msg.as_string()

    if IMAP_SEND:
        if not mailserver:
            try:
                (host,port) = IMAP_SERVER.split(':',1)
            except ValueError:
                host = IMAP_SERVER
                port = 993 if IMAP_SSL else 143
            try:
                if IMAP_SSL:
                    mailserver = imaplib.IMAP4_SSL(host, port)
                else:
                    mailserver = imaplib.IMAP4(host, port)
                # speed up interactions on TCP connections using small packets
                mailserver.sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
                mailserver.login(IMAP_USER, IMAP_PASS)
            except KeyboardInterrupt:
                raise
            except Exception, e:
                print >>warn, ""
                print >>warn, ('Fatal error: could not connect to mail server "%s"' % IMAP_SERVER)
                print >>warn, ('Check your config.py file to confirm that IMAP_SERVER and other mail server settings are configured properly')
                if hasattr(e, 'reason'):
                    print >>warn, "Reason:", e.reason
                sys.exit(1)
        if not folder:
            folder = DEFAULT_IMAP_FOLDER
        #mailserver.debug = 4
        if mailserver.select(folder)[0] == 'NO':
            print >>warn, ("%s does not exist, creating" % folder)
            mailserver.create(folder)
            mailserver.subscribe(folder)
        mailserver.append(folder,'',imaplib.Time2Internaldate(datetime), msg_as_string)
        return mailserver
Example #13
0
 def add_email(self, new_message, mailbox='INBOX'):
     self.conn.append(mailbox, '', imaplib.Time2Internaldate(time.time()),
                      str(new_message))
Example #14
0
 def backupMessage(self,sms,flags,sms_time):
     return self.imapser.append(self.mailbox,flags,imaplib.Time2Internaldate(sms_time),str(sms))
Example #15
0
 def _append_to_mailbox(self, mailbox, message):
     res, _query_ret  = self._call('append',
              mailbox, "", imaplib.Time2Internaldate(time.time()),
             message.as_string())
     return res == self._positive_response_code
Example #16
0
 def test_extract_time_no_date(self):
     date = self.msg.extractTime()
     self.assertEqual(date, imaplib.Time2Internaldate(time.time()))
Example #17
0
def qiyiold(*argv):
    uid_temp_list = []
    mailbox_temp = ""
    try:
        M = imaplib.IMAP4(argv[0])
        M.login(argv[1], argv[2])
        N = imaplib.IMAP4(argv[3])
        N.login(argv[4], argv[5])
        maildir_l = mail_dir(M.list())
        userNumMail = 0
        userAllMail = 0
        M.noop()
        N.noop()
        for mailbox in maildir_l:
            userNumMail = int(M.select(mailbox)[1][0])
            userAllMail += userNumMail
            print '<%s> <%s> <%s>' % (argv[1], mailbox, userNumMail)
        print 'User: <%s> EmailNum: <%s>.' % (argv[1], userAllMail)

        print 'Start qianyi mail....'

        for mailbox in maildir_l:
            # print mailbox
            M.select(mailbox)
            if N.select(mailbox)[0] <> 'OK':
                print 'Not mailbox <%s>, Create mailbox <%s>.' % (
                    mailbox, N.create(mailbox)[1])
                N.select(mailbox)
            # N.select(mailbox)
            #
            # 此步更新于20140813
            old_typ_n, old_data_n = N.search(None, 'ALL')
            oldmailid_n = old_data_n[0].split()
            userNumMail = int(M.select(mailbox)[1][0])
            uidlist = panDuanUserBox(argv[0], argv[1], mailbox)
            uid_temp_list = uidlist
            typ, data = M.search(None, 'SEEN')
            #print 'seen-------'
            for num in data[0].split():
                # print num
                typ, datauid = M.fetch(num, 'UID')
                uid = datauid[0].split(' ')[2][0:-1]
                if (uid in uidlist):
                    continue
                else:
                    print 'Start downloading...<%s><%s>' % (mailbox, num)
                    #实现无痕取信,不影响原来服务器上面邮箱中邮件的状态
                    typ, mdata = M.fetch(num, '(UID BODY.PEEK[])')
                    print 'download success...'
                    print 'Start upload...'
                    # print '01'
                    if len(mdata[0][1]) < 1:
                        print '<%s> mailbox,num <%s> len=0,continue.' % (
                            mailbox, num)
                        continue
                    try:
                        # print mailbox
                        # print '03'
                        N.select(mailbox)
                    except Exception, ex:
                        print '<%s><%s><%s>email error!!!' % (argv[0], mailbox,
                                                              num)
                        N = imaplib.IMAP4(argv[3])
                        N.login(argv[4], argv[5])
                        N.select(mailbox)
                    # print '02'
                    try:
                        N.append(mailbox, '',
                                 imaplib.Time2Internaldate(time.time()),
                                 mdata[0][1])
                    except Exception, ex:
                        print 'upload error:<%s><%s><%s><%s>' % (
                            argv[1], mailbox, num, ex)
                    uidlist.append(uid)
                    uid_temp_list = uidlist

            #此步更新于20140813
            new_typ_n, new_data_n = N.search(None, 'ALL')
            newmailid_n = new_data_n[0].split()
            datalist = list(set(oldmailid_n) ^ set(newmailid_n))
            #

            #typ,data=N.search(None,'ALL')
            # for num in data[0].split():
            for num in datalist:
                N.store(num, '+FLAGS', '\SEEN')
            typ, data = M.search(None, 'UNSEEN')
            # print 'unseen--------'
            # for num in data[0].split():
            # print num
            # typ,mdata=M.fetch(num,'(UID BODY.PEEK[])')
            # N.append(mailbox,'',imaplib.Time2Internaldate(time.time()),mdata[0][1])

            for num in data[0].split():
                # print num
                typ, datauid = M.fetch(num, 'UID')
                uid = datauid[0].split(' ')[2][0:-1]
                if (uid in uidlist):
                    continue
                else:
                    print 'Start downloading...<%s><%s>' % (mailbox, num)
                    typ, mdata = M.fetch(num, '(UID BODY.PEEK[])')
                    print 'download success...'
                    print 'Start upload...'
                    if len(data[0][1]) < 1:
                        print '<%s> mailbox,num <%s> len=0,continue.' % (
                            mailbox, num)
                        continue
                    try:
                        N.select(mailbox)
                    except Exception, ex:
                        print '<%s><%s><%s>email error!!!' % (argv[0], mailbox,
                                                              num)
                        N = imaplib.IMAP4(argv[3])
                        N.login(argv[4], argv[5])
                        N.select(mailbox)
                    try:
                        N.append(mailbox, '',
                                 imaplib.Time2Internaldate(time.time()),
                                 mdata[0][1])
                    except Exception, ex:
                        print 'upload error:<%s><%s><%s><%s>' % (
                            argv[1], mailbox, num, ex)
                    uidlist.append(uid)
                    uid_temp_list = uidlist
Example #18
0
 def test_extract_time_bad_date(self):
     self.msg["Date"] = "Mon, 06 May 0102 10:51:16 -0100"
     date = self.msg.extractTime()
     self.assertEqual(date, imaplib.Time2Internaldate(time.time()))
Example #19
0
 def __init__(self, file_name=None, directory=None, mdb=None):
     """Constructor(message file name, corpus directory name)."""
     date = imaplib.Time2Internaldate(time.time())[1:-1]
     IMAPMessage.__init__(self, date, mdb)
     FileCorpus.FileMessage.__init__(self, file_name, directory)
     self.id = file_name
Example #20
0
 def push_mail(self, folder, msg):
     now = imaplib.Time2Internaldate(time.time())
     msg = bytes(msg) if six.PY3 else str(msg)
     self.m.append(self._encode_mbox_name(folder), r'(\Seen)', now, msg)
Example #21
0
import email.message
import imaplib_connect

new_message = email.message.Message()
new_message.set_unixfrom('pymotw')
new_message['Subject'] = 'subject goes here'
new_message['From'] = '*****@*****.**'
new_message['To'] = '*****@*****.**'
new_message.set_payload('This is the body of the message.\n')

print new_message

c = imaplib_connect.open_connection()
try:
    c.append('INBOX', '',
             imaplib.Time2Internaldate(time.time()),
             str(new_message))

    # Show the headers for all messages in the mailbox
    c.select('INBOX')
    typ, [msg_ids] = c.search(None, 'ALL')
    for num in msg_ids.split():
        typ, msg_data = c.fetch(num, '(BODY.PEEK[HEADER])')
        for response_part in msg_data:
            if isinstance(response_part, tuple):
                print '\n%s:' % num
                print response_part[1]
        
finally:
    try:
        c.close()
Example #22
0
    def savemessage(self, uid, content, flags, rtime):
        imapobj = self.imapserver.acquireconnection()
        ui = UIBase.getglobalui()
        ui.debug('imap', 'savemessage: called')
        try:
            try:
                imapobj.select(self.getfullname()) # Needed for search
            except imapobj.readonly:
                ui.msgtoreadonly(self, uid, content, flags)
                # Return indicating message taken, but no UID assigned.
                # Fudge it.
                return 0
            
            # This backend always assigns a new uid, so the uid arg is ignored.
            # In order to get the new uid, we need to save off the message ID.

            message = rfc822.Message(StringIO(content))
            datetuple_msg = rfc822.parsedate(message.getheader('Date'))
            # Will be None if missing or not in a valid format.

            # If time isn't known
            if rtime == None and datetuple_msg == None:
                datetuple = time.localtime()
            elif rtime == None:
                datetuple = datetuple_msg
            else:
                datetuple = time.localtime(rtime)

            try:
                if datetuple[0] < 1981:
                    raise ValueError

                # Check for invalid date
                datetuple_check = time.localtime(time.mktime(datetuple))
                if datetuple[:2] != datetuple_check[:2]:
                    raise ValueError

                # This could raise a value error if it's not a valid format.
                date = imaplib.Time2Internaldate(datetuple) 
            except (ValueError, OverflowError):
                # Argh, sometimes it's a valid format but year is 0102
                # or something.  Argh.  It seems that Time2Internaldate
                # will rause a ValueError if the year is 0102 but not 1902,
                # but some IMAP servers nonetheless choke on 1902.
                date = imaplib.Time2Internaldate(time.localtime())

            ui.debug('imap', 'savemessage: using date ' + str(date))
            content = re.sub("(?<!\r)\n", "\r\n", content)
            ui.debug('imap', 'savemessage: initial content is: ' + repr(content))

            (headername, headervalue) = self.savemessage_getnewheader(content)
            ui.debug('imap', 'savemessage: new headers are: %s: %s' % \
                     (headername, headervalue))
            content = self.savemessage_addheader(content, headername,
                                                 headervalue)
            ui.debug('imap', 'savemessage: new content is: ' + repr(content))
            ui.debug('imap', 'savemessage: new content length is ' + \
                     str(len(content)))

            assert(imapobj.append(self.getfullname(),
                                       imaputil.flagsmaildir2imap(flags),
                                       date, content)[0] == 'OK')

            # Checkpoint.  Let it write out the messages, etc.
            assert(imapobj.check()[0] == 'OK')

            # Keep trying until we get the UID.
            ui.debug('imap', 'savemessage: first attempt to get new UID')
            uid = self.savemessage_searchforheader(imapobj, headername,
                                                   headervalue)
            # See docs for savemessage in Base.py for explanation of this and other return values
            if uid <= 0:
                ui.debug('imap', 'savemessage: first attempt to get new UID failed.  Going to run a NOOP and try again.')
                assert(imapobj.noop()[0] == 'OK')
                uid = self.savemessage_searchforheader(imapobj, headername,
                                                       headervalue)
        finally:
            self.imapserver.releaseconnection(imapobj)

        if uid: # avoid UID FETCH 0 crash happening later on
            self.messagelist[uid] = {'uid': uid, 'flags': flags}

        ui.debug('imap', 'savemessage: returning %d' % uid)
        return uid
Example #23
0
 def send(self, message):
     self._imap.append(self._mailbox, '', imaplib.Time2Internaldate(time.time()), message.message().as_bytes())
Example #24
0
def _getMailIMAPDate(mail):
    msg = email.message_from_string(mail)
    d = imaplib.Time2Internaldate(_parseMsgDate(msg))
    return d
Example #25
0
    def test_Time2Internaldate(self):
        expected = '"18-May-2033 05:33:20 +0200"'

        for t in self.timevalues():
            internal = imaplib.Time2Internaldate(t)
            self.assertEqual(internal, expected)
Example #26
0
def _convertTime(t):
    t = time.mktime(time.strptime(t, '%Y%m%d'))
    return imaplib.Time2Internaldate(t)
Example #27
0
def main():

    # create an IMAP4 class with SSL
    imap = imaplib.IMAP4_SSL(json_data["server_in"])
    # authenticate
    imap.login(json_data["username"], json_data["password"])
    status, messages = imap.select("INBOX")
    # search for messages that has the word remittance in subject
    typ, msg_ids = imap.search(None, '(SUBJECT "Remittance Advice")')
    print(f'Status: {status} Typ: {typ} Messages: {msg_ids}')
    # msg_ids is byte -> convert to string and split the string by whitespace
    for msg_id in msg_ids[0].decode().split():
        # print(type(msg_id))
        typ, msg_data = imap.fetch(msg_id, '(BODY.PEEK[TEXT] FLAGS)')
        # print(msg_data)

        msg_str = str(msg_data[0][1]).lower()  # For better readibility
        print(msg_str)
        # read the html tables from the document with pandas:
        tables_html = pd.read_html(msg_str, skiprows=1)
        payment_n = tables_html[0][1][2]
        payment_d = tables_html[0][1][3]
        supplier_site = tables_html[0][1][1]
        print(f'#### Start {payment_n} ###')
        # convert format 01-Sep-2020 to 2020-09-01
        payment_d = str(
            datetime.datetime.strptime(payment_d,
                                       '%d-%b-%Y').strftime('%Y-%m-%d'))

        # check if file A-2020-09-01-remittance number exists
        if not os.path.exists(json_data["pwd"] + 'A-' + payment_d + '-' +
                              payment_n + '.pdf'):
            pdfkit.from_string(
                msg_data[0][1].decode(),
                json_data["pwd"] + 'A-' + payment_d + '-' + payment_n + '.pdf')
            print(
                f'[++] The pdf file for remittance {payment_n} has been created'
            )
        else:
            print(
                f'[++] The pdf file for remittance {payment_n} does already exists'
            )

        # print(payment_n)
        # print(payment_d)
        # print(type(payment_d))
        # Get the files of working dic

        # list for existing invoices
        list_success = ['A-' + payment_d + '-' + payment_n + '.pdf']

        # list for missing invoices
        list_missing = []

        file_list = os.listdir(json_data['pwd'])

        # hol die RGnr der 2. Tabelle und pack sie in die Liste and check if exists locall

        for inv_nr in tables_html[1][0]:
            i = 0
            for fn in file_list:
                if (str(inv_nr).upper() in fn):
                    list_success.append(fn)
                    try:
                        list_missing.remove(inv_nr)
                    except:
                        pass
                    i += i
                else:
                    if (i == 0):
                        list_missing.append(inv_nr)
                        i = i + 1
            # create list with needed invoices

        # check if missing invoices exists
        print(f'[--] MISSING {payment_n} {list_missing}')
        print(f'[++] SUCCESS {payment_n} {list_success}')
        if len(list_missing) > 0:
            new_message = email.message.Message()
            new_message["From"] = "*****@*****.**"
            new_message["Subject"] = json_data['email_subject'] + \
                payment_n + supplier_site
            new_message.set_payload(','.join(map(str, list_missing)))
            imap.append('INBOX', '', imaplib.Time2Internaldate(time.time()),
                        str(new_message).encode('utf-8'))

        else:
            if not os.path.exists(json_data["pwd"] + "A-AMZ-" + payment_d +
                                  "-" + payment_n + ".pdf"):
                # create invoice with pdftk and store it
                # Call the PdfFileMerger
                mergedObject = PdfFileMerger(strict=False)
                for list_item in list_success:
                    mergedObject.append(
                        PdfFileReader(json_data["pwd"] + list_item, 'rb'))

                # Write all the files into a file which is named as shown below
                mergedObject.write(json_data["pwd"] + "A-AMZ-" + payment_d +
                                   "-" + payment_n + ".pdf")

                # delete email

                imap.store(msg_id, '+FLAGS', '\\Deleted')
                imap.expunge()

                # delete files
                for del_item in list_success:
                    if os.path.exists(json_data["pwd"] + del_item):
                        os.remove(json_data["pwd"] + del_item)
        print(f'#### END {payment_n} ###\n')

    try:
        imap.close()
    except:
        pass
    imap.logout()

    return 0
Example #28
0
import time
import email.message
import imaplib_connect

new_message = email.message.Message()
new_message.set_unixfrom('pymotw')
new_message['Subject'] = 'subject goes here'
new_message['From'] = '*****@*****.**'
new_message['To'] = '*****@*****.**'
new_message.set_payload('This is the body of the message.\n')

print new_message

c = imaplib_connect.open_connection()
try:
    c.append('INBOX', '', imaplib.Time2Internaldate(time.time()),
             str(new_message))

    # Show the headers for all messages in the mailbox
    c.select('INBOX')
    typ, [msg_ids] = c.search(None, 'ALL')
    for num in msg_ids.split():
        typ, msg_data = c.fetch(num, '(BODY.PEEK[HEADER])')
        for response_part in msg_data:
            if isinstance(response_part, tuple):
                print '\n%s:' % num
                print response_part[1]

finally:
    try:
        c.close()
Example #29
0
 def push_mail(self, folder, msg):
     now = imaplib.Time2Internaldate(time.time())
     self.m.append(self._encode_mbox_name(folder), r'(\Seen)', now,
                   str(msg))
Example #30
0
                'name'              : os.path.basename(filename),
                'x-apple-part-url'  : cid,
            }
            attachment = MIMEImage(data, **img_t)
            attachment.add_header('Content-ID', "<%s>" % cid)
            attachment.add_header('Content-Disposition', 'inline', filename=os.path.basename(filename))
            msg.attach(attachment)


    return msg

if __name__ == '__main__':
    if len(sys.argv) < 3:
        print "Usage: %s subject bodytext [imagefile ...]" % sys.argv[0]
        sys.exit(1)

    subject = sys.argv[1]
    body = sys.argv[2]
    files = sys.argv[3:]

    msg = new_message(subject, body, files)

    c = imap_open(verbose=True)

    try:
        c.select('Notes')
        c.append('Notes', '', imaplib.Time2Internaldate(time.time()), str(msg))
    finally:
        c.close()
        c.logout()