コード例 #1
0
 if not port:
     port = 110
 ssl = wikipedia.inputChoice('SSL? ', ['no', 'yes'], 
     ['n', 'y'], (port == 995) and 'y' or 'n') == 'y'
 username = wikipedia.input('User?')
 password = wikipedia.input('Password?', True)
 do_delete = wikipedia.inputChoice('Delete confirmed mails?', ['yes', 'no'], ['y', 'n'], 'y') == 'y'
     
 if email:
     preferences.set_all(['wpUserEmail', 'wpEmailFlag', 'wpOpenotifusertalkpages'],
         [email, True, False], verbose = True)
 
 if ssl:
     pop = poplib.POP3_SSL(host, port)
 else:
     pop = poplib.POP3(host, port)
     
 pop.user(username)
 pop.pass_(password)
 wikipedia.output(unicode(pop.getwelcome()))
 messages = [i.split(' ', 1)[0] for i in pop.list()[1]]
 for i in messages:
     msg = pop.retr(i)
     confirmed = False
     for line in msg[1]:
         if r_mail.search(line):
             confirmed = True
             link = r_mail.search(line).group(1)
             wikipedia.output(u'Confirming %s.' % link)
             confirm(link)
             
コード例 #2
0
import poplib
import email
from email.parser import Parser
import imaplib
from email.header import decode_header
from email.utils import parseaddr

# 输入邮件地址, 口令和POP3服务器地址:
email = raw_input('Email: ')
password = raw_input('Password: '******'POP3 server: ')

# 连接到POP3服务器:
server = poplib.POP3(pop3_server)
# 可以打开或关闭调试信息:
# server.set_debuglevel(1)
# 可选:打印POP3服务器的欢迎文字:
print(server.getwelcome())
# 身份认证:
server.user(email)
server.pass_(password)
# stat()返回邮件数量和占用空间:
print('Messages: %s. Size: %s' % server.stat())
# list()返回所有邮件的编号:
resp, mails, octets = server.list()
# 可以查看返回的列表类似['1 82923', '2 2184', ...]
print(mails)
# 获取最新一封邮件, 注意索引号从1开始:
index = len(mails)
resp, lines, octets = server.retr(index)
# lines存储了邮件的原始文本的每一行,
コード例 #3
0
#att1=MIMEText(open('3.txt','rb').read(),'base64','utf-8')
att1 = MIMEApplication(open("3.txt", 'rb').read())
att1.add_header('Content-Disposition', 'attachment', filename="3.txt")
#att1["Content-Type"] = 'application/octet-stream'
#att1["Content-Disposition"] = 'attachment;filename="3.txt"'
message.attach(att1)
try:
	smtpObj =smtplib.SMTP()
	smtpObj.connect(mail_host)
	smtpObj.login(mail_user,mail_pass)
	smtpObj.sendmail(sender,receivers,message.as_string())
	print ("success")
except smtplib.SMTPException:
	print ("false")
'''
pp = poplib.POP3(host)
#pp.set_debuglevel(1)
pp.user(mail_user)
pp.pass_(mail_pass)
ret = pp.stat()
print ret
num = len(pp.list()[1])
print 'num of messages', num

for i in range(1, num):
    #m = M.retr(i+1)
    m = pp.retr(i)

    buf = cStringIO.StringIO()
    buf.seek(0)
    msg = email.message_from_file(buf)
コード例 #4
0
def process_queue(q, logger):
    logger.info("***** %s: Begin processing mail for django-helpdesk" %
                ctime())

    if q.socks_proxy_type and q.socks_proxy_host and q.socks_proxy_port:
        try:
            import socks
        except ImportError:
            no_socks_msg = ("Queue has been configured with proxy settings, "
                            "but no socks library was installed. Try to "
                            "install PySocks via PyPI.")
            logger.error(no_socks_msg)
            raise ImportError(no_socks_msg)

        proxy_type = {
            "socks4": socks.SOCKS4,
            "socks5": socks.SOCKS5
        }.get(q.socks_proxy_type)

        socks.set_default_proxy(proxy_type=proxy_type,
                                addr=q.socks_proxy_host,
                                port=q.socks_proxy_port)
        socket.socket = socks.socksocket
    elif six.PY2:
        socket.socket = socket._socketobject

    email_box_type = settings.QUEUE_EMAIL_BOX_TYPE or q.email_box_type

    if email_box_type == "pop3":
        if q.email_box_ssl or settings.QUEUE_EMAIL_BOX_SSL:
            if not q.email_box_port:
                q.email_box_port = 995
            server = poplib.POP3_SSL(
                q.email_box_host or settings.QUEUE_EMAIL_BOX_HOST,
                int(q.email_box_port))
        else:
            if not q.email_box_port:
                q.email_box_port = 110
            server = poplib.POP3(
                q.email_box_host or settings.QUEUE_EMAIL_BOX_HOST,
                int(q.email_box_port))

        logger.info("Attempting POP3 server login")

        server.getwelcome()
        server.user(q.email_box_user or settings.QUEUE_EMAIL_BOX_USER)
        server.pass_(q.email_box_pass or settings.QUEUE_EMAIL_BOX_PASSWORD)

        messagesInfo = server.list()[1]
        logger.info("Received %d messages from POP3 server" %
                    len(messagesInfo))

        for msgRaw in messagesInfo:
            if six.PY3 and type(msgRaw) is bytes:
                # in py3, msgRaw may be a bytes object, decode to str
                try:
                    msg = msgRaw.decode("utf-8")
                except UnicodeError:
                    # if couldn't decode easily, just leave it raw
                    msg = msgRaw
            else:
                # already a str
                msg = msgRaw
            msgNum = msg.split(" ")[0]
            logger.info("Processing message %s" % msgNum)

            if six.PY2:
                full_message = encoding.force_text("\n".join(
                    server.retr(msgNum)[1]),
                                                   errors="replace")
            else:
                raw_content = server.retr(msgNum)[1]
                if type(raw_content[0]) is bytes:
                    full_message = "\n".join(
                        [elm.decode("utf-8") for elm in raw_content])
                else:
                    full_message = encoding.force_text("\n".join(raw_content),
                                                       errors="replace")
            ticket = ticket_from_message(message=full_message,
                                         queue=q,
                                         logger=logger)

            if ticket:
                server.dele(msgNum)
                logger.info(
                    "Successfully processed message %s, deleted from POP3 server"
                    % msgNum)
            else:
                logger.warn(
                    "Message %s was not successfully processed, and will be left on POP3 server"
                    % msgNum)

        server.quit()

    elif email_box_type == "imap":
        if q.email_box_ssl or settings.QUEUE_EMAIL_BOX_SSL:
            if not q.email_box_port:
                q.email_box_port = 993
            server = imaplib.IMAP4_SSL(
                q.email_box_host or settings.QUEUE_EMAIL_BOX_HOST,
                int(q.email_box_port))
        else:
            if not q.email_box_port:
                q.email_box_port = 143
            server = imaplib.IMAP4(
                q.email_box_host or settings.QUEUE_EMAIL_BOX_HOST,
                int(q.email_box_port))

        logger.info("Attempting IMAP server login")

        try:
            server.login(
                q.email_box_user or settings.QUEUE_EMAIL_BOX_USER,
                q.email_box_pass or settings.QUEUE_EMAIL_BOX_PASSWORD,
            )
            server.select(q.email_box_imap_folder)
        except imaplib.IMAP4.abort:
            logger.error(
                "IMAP login failed. Check that the server is accessible and that the username and password are correct."
            )
            server.logout()
            sys.exit()
        except ssl.SSLError:
            logger.error(
                "IMAP login failed due to SSL error. This is often due to a timeout. Please check your connection and try again."
            )
            server.logout()
            sys.exit()

        try:
            status, data = server.search(None, "NOT", "DELETED")
        except imaplib.IMAP4.error:
            logger.error(
                "IMAP retrieve failed. Is the folder '%s' spelled correctly, and does it exist on the server?"
                % q.email_box_imap_folder)
        if data:
            msgnums = data[0].split()
            logger.info("Received %d messages from IMAP server" % len(msgnums))
            for num in msgnums:
                logger.info("Processing message %s" % num)
                status, data = server.fetch(num, "(RFC822)")
                full_message = encoding.force_text(data[0][1],
                                                   errors="replace")
                try:
                    ticket = ticket_from_message(message=full_message,
                                                 queue=q,
                                                 logger=logger)
                except TypeError:
                    ticket = None  # hotfix. Need to work out WHY.
                if ticket:
                    server.store(num, "+FLAGS", "\\Deleted")
                    logger.info(
                        "Successfully processed message %s, deleted from IMAP server"
                        % num)
                else:
                    logger.warn(
                        "Message %s was not successfully processed, and will be left on IMAP server"
                        % num)

        server.expunge()
        server.close()
        server.logout()

    elif email_box_type == "local":
        mail_dir = q.email_box_local_dir or "/var/lib/mail/helpdesk/"
        mail = [
            join(mail_dir, f) for f in listdir(mail_dir)
            if isfile(join(mail_dir, f))
        ]
        logger.info("Found %d messages in local mailbox directory" % len(mail))

        logger.info("Found %d messages in local mailbox directory" % len(mail))
        for i, m in enumerate(mail, 1):
            logger.info("Processing message %d" % i)
            with open(m, "r") as f:
                full_message = encoding.force_text(f.read(), errors="replace")
                ticket = ticket_from_message(message=full_message,
                                             queue=q,
                                             logger=logger)
            if ticket:
                logger.info(
                    "Successfully processed message %d, ticket/comment created."
                    % i)
                try:
                    unlink(m)  # delete message file if ticket was successful
                except OSError:
                    logger.error("Unable to delete message %d." % i)
                else:
                    logger.info("Successfully deleted message %d." % i)
            else:
                logger.warn(
                    "Message %d was not successfully processed, and will be left in local directory"
                    % i)
コード例 #5
0
#!/usr/bin/env python
import poplib
import sys


mail = poplib.POP3("mail.chandrashekar.info")
mail.user("*****@*****.**")
mail.pass_("pythonista")

response_code, messages, octets = mail.list()
print("Response code:", response_code)

if b"OK" in response_code:
    for msg in messages:
        msg_num, size = (int(x) for x in msg.split())
        code, data, msg_size = mail.retr(msg_num)
        print(f"Msg {msg_num} reponse code: {code}")
        for line in data:
            if line.startswith(b"Subject") or line.startswith(b"From"):
                print(line)
        print("-" * 40)


コード例 #6
0
ファイル: emails.py プロジェクト: ldd9951/remote-shutdown
    def gather_mail(self, email, password, to_addr):
        """
        读取最新邮件

        参数:
            - email:邮箱地址
            - password:授权密码
        """
        pop3_server = 'pop.' + email.split('@')[-1]
        # 开始连接到服务器
        server = poplib.POP3(pop3_server)
        # server.set_debuglevel(1)
        # 认证:
        server.user(email)
        server.pass_(password)
        resp, mails, octets = server.list()
        # 获取最新一封邮件, 注意索引号从1开始:
        resp, lines, octets = server.retr(len(mails))
        # 解析邮件:
        msg_content = b'\r\n'.join(lines).decode()
        msg = Parser().parsestr(text=msg_content)

        # 获取发件人邮箱地址
        value = msg.get("From", '')
        _, addr = parseaddr(value)
        # 只有指定的邮箱发起控制指令才会执行
        if addr != to_addr:
            print("无效邮件不执行")
            return

        # 获取服务收到邮件时间
        received_time = msg.get("Date")
        received_time = received_time[0:received_time.index("+")] + " GMT"
        # 格式时间
        end = datetime.datetime.strptime(received_time, GMT_FORMAT)
        # 获取当前时间
        start = datetime.datetime.now()
        # print (start,"--",end,"**********************",(start-end).seconds)
        if (start - end).seconds > 60 * 2:
            print("当前指令已经过期不会被执行 ", start - end)
            return

        # 检查是否有内容
        if (msg.is_multipart()):
            # 获取内容 内容可能包含两部分
            parts = msg.get_payload()
            # 遍历内容
            for _, part in enumerate(parts):
                # 获取内容类型 text/plain and text/html
                content_type = part.get_content_type()
                # 判断是不是纯本部内容
                if content_type == 'text/plain':
                    content = part.get_payload(decode=True)
                    charset = self.guess_charset(part)
                    if charset:
                        # 取出邮件内容
                        content = content.decode(charset)
                        # 去除空格和换行
                        ctext = content.replace("\n", "").strip()
                        return ctext

        # 慎重:将直接从服务器删除邮件:
        # server.dele(len(mails))
        # 关闭连接:
        server.quit()
コード例 #7
0
try:
    users_list = open(sys.argv[2], "r")
    users = users_list.readlines()
    words_list = open(sys.argv[3], "r")
    words = words_list.readlines()
except (IOError):
    print "[-] Error: 请检查用户名或密码路径及文件\n"
    sys.exit(1)
finally:
    users_list.close()
    words_list.close()

try:
    if sys.argv[1] in ['163', '236']:
        pop = poplib.POP3(server, 110)
    else:
        pop = poplib.POP3_SSL(server, 995)
    welcome = pop.getwelcome()
    print welcome
    pop.quit()
except (poplib.error_proto):
    welcome = "[-] Error: No Response,Something wrong!!!\n"
    sys.exit(1)

print "[+] Server:", server
print "[+] Users Loaded:", len(users)
print "[+] Words Loaded:", len(words)
print "[+] Server response:", welcome, "\n"

コード例 #8
0
def login_mail():
    pop_client = poplib.POP3('pop3.sina.com')
    # pop_client.set_debuglevel(1)
    pop_client.user(cc)
    pop_client.pass_(password)
    return pop_client
コード例 #9
0
ファイル: TLogin.py プロジェクト: chancn/Katana
def tlogin():
    try:
        global defaulthost, defaultport, defaultdat1, defaultdat2
        actions = raw_input(O + "     ktn/mc/tlogin > " + W)
        if actions == "show options":
            print ""
            print "     [" + R + "+" + W + "] options"
            print "     |host           : yes"
            print "     |username       : yes"
            print "     |password       : yes\n"
            print ""
            print "     [" + G + "+" + W + "] options current"
            print "     |host           : ", defaulthost
            print "     |username       : "******"     |password       : "******""
            tlogin()
        elif actions[0:8] == "set host":
            defaulthost = actions[9:]
            print "     host           : " + defaulthost + " " + O + "     Saved!!!" + W
            tlogin()
        elif actions[0:12] == "set username":
            defaultdat1 = actions[13:]
            print "     username       : "******" " + O + "     Saved!!!" + W
            tlogin()
        elif actions[0:12] == "set password":
            defaultdat2 = actions[13:]
            print "     password       : "******" " + O + "     Saved!!!" + W
            tlogin()
        elif actions == "back":
            return
        elif actions == "exit":
            print C + "     GooD" + W + " bye."
            exit()
        elif actions == "help":
            help.help()
        elif actions == "run":
            print("\n     [" + O + "!" + W + "] Checking target")
            print "     [" + G + "+" + W + "] options current"
            print "     host           : ", defaulthost
            print "     username       : "******"     password       : "******""
            print("     [" + G + "+" + W + "] Running")
            try:
                print("     [" + O + "!" + W +
                      "] Testing in MYsql    \t\t\t[3306]")
                MySQLdb.connect(defaulthost, defaultdat1, defaultdat2, '')
                if True:
                    print("     [" + G + "+" + W + "] Logged with " +
                          defaultdat1 + "/" + defaultdat2 + " in Mysql")
            except:
                print("     [" + R + "-" + W + "] Service Off or No Logged.")
            try:
                print("     [" + O + "!" + W +
                      "] Testing in SSH    \t\t\t[20]")
                connect = pxssh.pxssh()
                connect.login(defaulthost, defaultdat1, defaultdat2)
                if True:
                    print("     [" + G + "+" + W + "] Logged with " +
                          defaultdat1 + "/" + defaultdat2 + " in SSH")
            except:
                print "     [" + R + "-" + W + "] Service Off or No Logged."
            try:
                print("     [" + O + "!" + W +
                      "] Testing in FTP    \t\t\t[21]")
                ftp.login(defaultdat1, defaultdat2)
                if True:
                    print("     [" + G + "+" + W + "] Logged with " +
                          defaultdat1 + "/" + defaultdat2 + " in FTP")
            except:
                print "     [" + R + "-" + W + "] Service Off or No Logged."
            try:
                print("     [" + O + "!" + W +
                      "] Testing in POP3    \t\t\t[21]")
                red = poplib.POP3(defaulthost, 110)
                red.user(defaultdat1 + "@" + defaulthost)
                red.pass_(defaultdat2)
                if True:
                    print("     [" + G + "+" + W + "] Logged with " +
                          defaultdat1 + "/" + defaultdat2 + " in POP3")
            except:
                print "     [" + R + "-" + W + "] Service Off or No Logged."
        else:
            print "     [" + O + "!" + W + "] command No Accept" + W
    except (KeyboardInterrupt):
        print("\n     [" + O + "!" + W + "] (Ctrl + C) Detected, System Exit")
        return
    tlogin()
コード例 #10
0
ファイル: check_pop3.py プロジェクト: mjmayer/smtp-toolkit
import getpass
import poplib
import argparse

parser = argparse.ArgumentParser(description="check pop3 mailbox")
parser.add_argument("-u", "--user", help="pop3 username")
parser.add_argument("-p", "--password", help="pop3 Password")
parser.add_argument("--server", help="hostname for pop3 server")
parser.add_argument("--port", default=110, type=int, help="pop3 server port")
args = parser.parse_args()

M = poplib.POP3(args.server, port=args.port)
M.user(args.user)
M.pass_(args.password)
numMessages = len(M.list()[1])
for i in range(numMessages):
    for j in M.retr(i + 1)[1]:
        print(j)
コード例 #11
0
    msg["Subject"] = "{} (自動転送)".format(TARGET_SUBJECT)
    msg["From"] = MAIL["NOTICE"]["ADDRESS"]
    msg["To"] = MAIL["NOTICE"]["ADDRESS"]
    msg.set_content("\n\n\n---\n\n\n".join(warn_msgs))

    smtp = smtplib.SMTP(MAIL["NOTICE"]["HOST"], MAIL["NOTICE"]["SMTP_PORT"])
    smtp.login(MAIL["NOTICE"]["USER"], MAIL["NOTICE"]["PSWD"])
    try:
        smtp.send_message(msg)
    finally:
        smtp.quit()


# [ MAIN ]
# サーバに接続する
cli = poplib.POP3(MAIL["WATCH"]["HOST"])
print("connected.")

# 認証を行う
cli.user(MAIL["WATCH"]["USER"])
cli.pass_(MAIL["WATCH"]["PSWD"])
print("logged in.")

warn_msgs = watch_warn()
if 0 < len(warn_msgs):
    print("{} warnings found.".format(str(len(warn_msgs))))
    notice_warn(warn_msgs)
    print("noticed.")
else:
    print("no warnings found.")
コード例 #12
0
#!/usr/bin/env python
# coding=utf-8
# Python 2.7.3
# 获取邮件内容
import poplib
import os
import sys
from email import parser

host = 'mail.emotibot.com.cn'
username = '******'
password = '******'

#pop_conn = poplib.POP3_SSL(host)
pop_conn = poplib.POP3(host)
pop_conn.user(username)
pop_conn.pass_(password)

#Get messages from server:
# 获得邮件
messages = [pop_conn.retr(i) for i in range(1, len(pop_conn.list()[1]) + 1)]
#print messages

#print "--------------------------------------------------"
# Concat message pieces:
messages = ["\n".join(mssg[1]) for mssg in messages]
#print messages
#sys.exit(0);

#Parse message intom an email object:
# 分析
コード例 #13
0
ファイル: email_domain.py プロジェクト: erpnext-tm/frappe
    def validate(self):
        """Validate email id and check POP3/IMAP and SMTP connections is enabled."""
        logger = frappe.logger()

        if self.email_id:
            validate_email_address(self.email_id, True)

        if frappe.local.flags.in_patch or frappe.local.flags.in_test:
            return

        if not frappe.local.flags.in_install and not frappe.local.flags.in_patch:
            try:
                if self.use_imap:
                    logger.info(
                        "Checking incoming IMAP email server {host}:{port} ssl={ssl}..."
                        .format(host=self.email_server,
                                port=get_port(self),
                                ssl=self.use_ssl))
                    if self.use_ssl:
                        test = imaplib.IMAP4_SSL(self.email_server,
                                                 port=get_port(self))
                    else:
                        test = imaplib.IMAP4(self.email_server,
                                             port=get_port(self))

                else:
                    logger.info(
                        "Checking incoming POP3 email server {host}:{port} ssl={ssl}..."
                        .format(host=self.email_server,
                                port=get_port(self),
                                ssl=self.use_ssl))
                    if self.use_ssl:
                        test = poplib.POP3_SSL(self.email_server,
                                               port=get_port(self))
                    else:
                        test = poplib.POP3(self.email_server,
                                           port=get_port(self))

            except Exception as e:
                logger.warn(
                    'Incoming email account "{host}" not correct'.format(
                        host=self.email_server),
                    exc_info=e)
                frappe.throw(
                    title=_("Incoming email account not correct"),
                    msg='Error connecting IMAP/POP3 "{host}": {e}'.format(
                        host=self.email_server, e=e),
                )

            finally:
                try:
                    if self.use_imap:
                        test.logout()
                    else:
                        test.quit()
                except Exception:
                    pass

            try:
                if self.get("use_ssl_for_outgoing"):
                    if not self.get("smtp_port"):
                        self.smtp_port = 465

                    logger.info(
                        "Checking outgoing SMTPS email server {host}:{port}..."
                        .format(host=self.smtp_server, port=self.smtp_port))
                    sess = smtplib.SMTP_SSL((self.smtp_server
                                             or "").encode("utf-8"),
                                            cint(self.smtp_port) or None)
                else:
                    if self.use_tls and not self.smtp_port:
                        self.smtp_port = 587
                    logger.info(
                        "Checking outgoing SMTP email server {host}:{port} STARTTLS={tls}..."
                        .format(host=self.smtp_server,
                                port=self.get("smtp_port"),
                                tls=self.use_tls))
                    sess = smtplib.SMTP(cstr(self.smtp_server or ""),
                                        cint(self.smtp_port) or None)
                sess.quit()
            except Exception as e:
                logger.warn(
                    'Outgoing email account "{host}" not correct'.format(
                        host=self.smtp_server),
                    exc_info=e)
                frappe.throw(
                    title=_("Outgoing email account not correct"),
                    msg='Error connecting SMTP "{host}": {e}'.format(
                        host=self.smtp_server, e=e),
                )
コード例 #14
0
ファイル: pycmdHome.py プロジェクト: ghimire/pycmdHome
        S.sendmail(fromaddr, [toaddr], HeaderText + sendmsg)
    except:
        pass

    return 1


if (__name__ == "__main__"):
    while (1):
        getcmdoutput = {}
        cmd = ''
        cmdoutput = ''

        S = smtplib.SMTP(SMTPSERVER)
        M = poplib.POP3(POPSERVER)
        M.user(POPUSER)
        M.pass_(POPPASS)

        fd = open(LOGFILE, 'a')

        if M.stat()[1] > 0:
            print WHITE + MAGENTAB + 'You\'ve got ' + CYAN + str(
                len(M.list()[1])) + ENDC + WHITE + MAGENTAB + ' mails!' + ENDC
        else:
            print RED + "No new mails." + ENDC

        print ""

        mailsTotal = len(M.list()[1])
コード例 #15
0
#
import poplib
import sys

target = sys.argv[1]
user = sys.argv[2]

pwdfile = open('pwds_only.txt', 'r')
pwds = pwdfile.readlines()

for pwd in pwds:

    print 'checking user %s with pass %s' % (user, pwd)
    try:
        # target mbox
        mbox = poplib.POP3(target, '110')
        mbox.user(user)
        pwd = pwd.rstrip('\n')
        mbox.pass_(pwd)

        count_msgs = len(mbox.list()[1])

        for i in range(count_msgs):
            for msg in mbox.retr(i + 1)[1]:
                print 'retrived msg:', msg

        mbox.quit()
        pwdfile.close()

    except poplib.error_proto as e:
        print '[-] auth failed :C'
コード例 #16
0
ファイル: mold_remover.py プロジェクト: matthewbauer/osx
localuidldate="/var/mail/.UIDLDate" #mold remover's UIDL datefile

#end of user editable section

readfile=open(localuidlcache, 'r')
datefile=open(localuidldate, 'a+')
tempfile=open("/tmp/uidltmp", 'w+')
popuidllist=[] #list of undeleted uidls on all servers
totnum=0 #number of undeleted messages on all servers
connectedto=-1

#connect to each mailserver get all the new message UIDLs and delete any
#expired messages.

for a in range(len(mailserver)):
    connect=poplib.POP3(mailserver[a])
    connect.user(login[a])
    connect.pass_(password[a])
    connectedto=a
    number,size=connect.stat()
    totnum+=number
    for mesnum in range(number):
        messagedeleted=0
        datefile.seek(0)
        for uidldate in datefile:
            uidldatesplit=uidldate.split(' ')
            if(connectedto==int(uidldatesplit[2])):
                if (time.time()-float(uidldatesplit[1]))>(86400*days[a]-3600):
                    try:
                        recheckuidl=connect.uidl(mesnum+1)
                        recheckuidlsplit=recheckuidl.split(' ')
コード例 #17
0
ファイル: popMail.py プロジェクト: gzgdouru/python_study
import poplib, sys

mailServer = "pop3.163.com"
mailUser = "******"
mailPasswd = "5201314ouru..."

print "connection...."
server = poplib.POP3(mailServer)
server.user(mailUser)
server.pass_(mailPasswd)

try:
    print server.getwelcome()
    msgCount, msgBytes = server.stat()
    print "There are", msgCount, "mail message in", msgBytes, "bytes"
    print server.list()
    print "-" * 80
    raw_input("Press Enter key")
    for i in range(1):
        hdr, message, octest = server.retr(i + 1)
        for line in message:
            print line
        print "-" * 80
finally:
    server.quit()

print "Bye."
コード例 #18
0
ファイル: doorknocker.py プロジェクト: mahdi0011/darkcode
    try:
        words = open('pass.txt', "r").readlines()
    except (IOError):
        print "Error: Check your password file pass.txt\n"
        sys.exit(1)

    print "[+] Server:", server
    print "[+] User Loaded:", len(users)
    print "[+] Words Loaded:", len(words), "\n"
    for user in users:
        for word in words:
            try:
                print "-" * 22
                print "User:"******"Password:"******"\t\nLogin successful:", word, user
                print pop.stat()
                pop.quit()
                sys.exit(2)
            except (poplib.error_proto), msg:
                #print "An error occurred:", msg
                pass

if door == 'MYSQL':
    print "\n\t Enter the server address to be cracked"
    server = raw_input()
    try:
        users = open('users.txt', "r").readlines()
コード例 #19
0
 def connect(self):
     '''Connects to the server, which allows the other methods to be called.'''
     self._s = poplib.POP3(self._cfg['pop_server'])
     self._check(self._s.user(self._cfg['sender']))
     self._check(self._s.pass_(self._cfg['password']))
コード例 #20
0
ファイル: Email.py プロジェクト: hokaii/CodeShow
 def reset_pop(self):
     self.close_pop()
     self.server = poplib.POP3(options['receiver']['pop3_server'])
     self.server.user(options['receiver']['user_account'])
     self.server.pass_(options['receiver']['password'])
コード例 #21
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import poplib

pop = poplib.POP3("pop.hostname.de")
pop.user("benutzername")
pop.pass_("passwort")

for i in range(1, pop.stat()[0] + 1):
    for zeile in pop.retr(i)[1]:
        print(zeile)
    print("***")

pop.quit()
コード例 #22
0
    if not os.path.exists(file_path):
        os.makedirs(file_path)

    # config Mail Server
    print "======== Please Config mail server: server, port, username ,password ,filepath ========"
    server = sys.argv[1]
    port = sys.argv[2]
    pop_user = sys.argv[3]
    pop_pass = sys.argv[4]
    file_path = sys.argv[5]

    # if it's 110, using POP3 to get the mail attachment
    if port == "110":
        try:
            pop = poplib.POP3(server, port, timeout=15)
            pop.set_debuglevel(1)
            pop.user(pop_user)
            pop.pass_(pop_pass)
        except:
            print "please check the mail server and port, also check the username and password again! "
            sys.exit(1)

        # pop.uidl ????uid???
        result, data, oct = pop.uidl()
        for item in data:
            uid = item.split()
            mail_num = uid[0]
            mail_uid = uid[1]
            #if not db.select_uid(db_name, mail_uid):
            #               logging.info("Start to fetch mail, num: %s, uid: %s" %(mail_num, mail_uid))
コード例 #23
0
def spamclam_a_pop3_mailbox(str_srvr, str_user, str_pass, str_mode, str_wob, restat='False'):

    # =============   Connect to POP3 server   =============================

    # Open connection to email (POP) server
    try:
        con_pop = poplib.POP3(str_srvr)
        con_pop.user(str_user)
        con_pop.pass_(str_pass)
        print("Server says:  "+con_pop.getwelcome())
        num_tot_msgs, num_tot_bytes = con_pop.stat()
        print("Mailbox stat:\n  {} messages\n  {} bytes total".format(str(num_tot_msgs),str(num_tot_bytes)))
    except:
        print("\nSeems to be unable to access the e-mail server...")
        sys.exit(102)

    # =============   Spamalyse   ==========================================

    # Create Spamalyser object(s)
    salysr_sbw = spamalyse.Spamalyser(str_mode, 'filter_simple_bw/', str_wob)  # Consider moving WOB to simple_bw.py
    ##salysr_sbw.show_rules()  ## only for debug - a non ui-module should not use print, nor pp

    # Create a Statistics object
    salsta = spamstat.Spamstat()

    # =============   Run   ================================================"

    ##print "{}".format(con_pop.list()[0])  # XXX This is a non-ui module, to be called from cli and gui alike.

    num_email = 0  # To avoid problems with counter after this loop, if no mails found.
    for num_email in range(1,num_tot_msgs+1):  # pop server count from 1 (not from 0)
        email_raw = con_pop.retr(num_email)
        email_string = "\n".join(email_raw[1])
        msg = email.message_from_string(email_string)
        #print "------- HDR e-mail --------------"
        #print num_email, "date:", msg.get('date'),  "from:", msg.get('from'), "subj:", msg.get('subject')  # XXX Before salmsg
        #print "------- raw e-mail --------------"
        #print msg
        #print "------- raw e-mail --------------"

        # ** Turn the email.massage into a spamalyse.Salmsg
        salmsg = spamalyse.Salmail(msg)
        #salmsg.show()

        # ** Check the salmsg for 'spam'
        logger.debug("Email: {}; {}".format(salmsg.get('from'),salmsg.get('subject')))
        sal_res_sbw = salysr_sbw.is_spam(salmsg)

        # Actually delete the e-mail, and write to log file
        logger.info("Email: [{}] {} {}; {}".format(num_email, sal_res_sbw['spam'], salmsg.get('from'),salmsg.get('subject')))
        if sal_res_sbw['spam']:
            logger.info("  hit: {}".format(sal_res_sbw['votb']))  # if it's spam print the proof, which must be black...
            print("  hit: {}".format(sal_res_sbw['votb']))

            # ** Actually delete the file (on some pop3 servers this do not really happen until we log out...)
            #
            #con_pop.dele(num_email)  # <-------------------------------------------------------------------- LUS

        # ** send this email, and sal_res_sbw to the stat object
        salsta.add_salres(salmsg, sal_res_sbw, restat=restat)

    # Close connection to email server
    con_pop.quit()

    # Close statistics collector
    #for line in salsta.show(sort='spam'): # sort: 'spam', 'rule_hits', 'no_rules', 'cnt', 'cnt_spam'
    #    print "stat > ", line
    salsta.close()

    # Clean major objects
    del con_pop
    del salysr_sbw
    del salsta
    del str_srvr, str_user, str_pass

    return [num_email]  # List of return elements can be expanded later...
コード例 #24
0
 def setUp(self):
     self.server = DummyPOP3Server((HOST, PORT))
     self.server.start()
     self.client = poplib.POP3(self.server.host,
                               self.server.port,
                               timeout=3)
コード例 #25
0
#!/usr/bin/python

import poplib

username = '******'
passwd = '*'
mail_server = 'mail.office365.com'

p = poplib.POP3(mail_server)
p.user(username)
p.pass_(passwd)
for msg_id in p.list()[1]:
	print msg_id
	outf = open('%s.eml' % msg_id, 'w')
	outf.write('\n'.join(p.retr(msg_id)[1]))
	outf.close()
p.quit()
コード例 #26
0
 def testTimeoutValue(self):
     pop = poplib.POP3(HOST, self.port, timeout=30)
     self.assertEqual(pop.sock.gettimeout(), 30)
     pop.sock.close()
コード例 #27
0
ファイル: ClientPOP3.py プロジェクト: hxp2k6/Katana
def cpop3(run):
    try:
        global defaulthost, defaultport, defaultuser, defaultpass
        if run != 1:
            actions = raw_input(d.prompt("clt/pop3"))
        else:
            actions = "run"
        if actions == "show options" or actions == "sop":
            d.option()
            d.descrip("target", "yes", "IP or DNS", defaulthost)
            d.descrip("port", "no", "Port of target", defaultport)
            d.descrip("user", "yes", "Username", defaultuser)
            d.descrip("pass", "yes", "Password", defaultpass)
            d.space()
            cpop3(0)
        elif actions[0:10] == "set target":
            defaulthost = defaulthost.replace("http://", "")
            defaulthost = ping.update(defaulthost, actions, "target")
            d.change("target", defaulthost)
        elif actions[0:8] == "set port":
            defaultport = ping.update(defaultport, actions, "port")
            d.change("port", defaultport)
        elif actions[0:8] == "set user":
            defaultuser = ping.update(defaultuser, actions, "user")
            d.change("user", defaultuser)
        elif actions[0:8] == "set pass":
            defaultpass = ping.update(defaultpass, actions, "pass")
            d.change("pass", defaultpass)
        elif actions == "exit" or actions == "x":
            d.goodbye()
            exit()
        elif actions == "help" or actions == "h":
            help.help()
        elif actions == "back" or actions == "b":
            return
        elif actions == "run" or actions == "r":
            d.run()
            try:
                red = poplib.POP3(defaulthost, defaultport)
                try:
                    red.user(defaultuser)
                    red.pass_(defaultpass)
                    if True:
                        cmd = "nop"
                        print "\n " + Hlp + " POP3 Client help\n"
                        print "  ----------------------------------------"
                        print "  |" + colors[6] + "Commd" + colors[
                            0] + "| " + colors[6] + "Description" + colors[
                                0] + " | " + colors[6] + "Examples" + colors[
                                    0] + "         |"
                        print "  ----------------------------------------"
                        print "  |list	| list mails  | list             |"
                        print "  |retr	| show mail   | retr 2           |"
                        print "  |dele	| remove mail | dele 2           |"
                        print "  |quit	|exit d remove| quit             | "
                        print "  ----------------------------------------"
                        print ""
                        if True:
                            if True:
                                if True:
                                    while (cmd != "exit"):
                                        cmd = raw_input(
                                            d.Client_prompt('pop3'))
                                        if cmd == "list":
                                            numMessages = len(red.list()[1])
                                            for i in range(numMessages):
                                                print "	mail " + str(i)
                                        if cmd[0:4] == "retr":
                                            for j in red.retr(
                                                    int(cmd[5:]) + 1)[1]:
                                                print j
                                        if cmd[0:4] == "dele":
                                            try:
                                                red.dele(int(cmd[5:]) + 1)[1]
                                                if True:
                                                    print " " + Alr + " email marked for delete ('quit' for exit and delete all email marked)"
                                            except Exception, e:
                                                print(" " + Bad + " Error", e)
                                        if cmd == "quit":
                                            red.quit()
                                            print " " + Alr + " Exit, bye."
                                            break
                except:
                    d.No_match()
            except:
                Errors.Errors(event=sys.exc_info()[0],
                              info=defaulthost + ":" + defaultport)
        else:
            d.No_actions()
    except:
        Errors.Errors(event=sys.exc_info()[0], info=False)
    cpop3(0)
コード例 #28
0

import os
import poplib
import email
from email.parser import Parser
from email.header import decode_header
from email.utils import parseaddr


POP_SERVER = "pop.sina.com"
USERNAME = "******"
PASSWD = "zwh123"



server = poplib.POP3(host=POP_SERVER)
print(server.getwelcome())
server.user(USERNAME)
server.pass_(PASSWD)
resp, mails, octets = server.list()
print(mails)
index = len(mails)
resp, lines, octets = server.retr(index)
msg_content = '\r\n'.join(lines)
msg = Parser().parsestr(msg_content)
#server.quit()



                                                     
コード例 #29
0
ファイル: get_mail.py プロジェクト: ziyi19851021/Python
def get_mail(email, password, limit=1):
    pop3_server = ''
    st = email.split('@')[1]
    if st and (st in pops):
        pop3_server = pops[st]

    msgAll = []

    # 输入邮件地址, 口令和POP3服务器地址:
    email = email  # input('Email: ')
    password = password  # input('Password: '******'POP3 server: ') # pop.126.com   pop.163.com

    try:
        # 连接到POP3服务器:
        server = poplib.POP3(pop3_server)

        # 可以打开或关闭调试信息:
        server.set_debuglevel(1)

        # 可选:打印POP3服务器的欢迎文字:
        # print(server.getwelcome().decode('utf-8'))

        # 身份认证:
        server.user(email)
        server.pass_(password)
    except:
        return msgAll

    # stat()返回邮件数量和占用空间:
    print('Messages: %s. Size: %s' % server.stat())

    # list()返回所有邮件的编号:
    resp, mails, octets = server.list()

    # 可以查看返回的列表类似[b'1 82923', b'2 2184', ...]
    # print(mails)

    # 获取最新一封邮件, 注意索引号从1开始:
    index = len(mails)  # 总数

    page = (index - limit) if (index - limit) > 0 else 0
    for x in range(index, page, -1):  #循环获取所有邮件

        try:
            resp, lines, octets = server.retr(x)

            # lines存储了邮件的原始文本的每一行,
            # 可以获得整个邮件的原始文本:
            msg_content = b'\r\n'.join(lines).decode('utf-8')

            # 稍后解析出邮件:
            msg = Parser().parsestr(msg_content)

            msgAll.append(print_info(msg))
        except:
            pass

    # 可以根据邮件索引号直接从服务器删除邮件:
    # server.dele(index)
    # 关闭连接:
    server.quit()
    # except:
    # 	pass

    return msgAll
コード例 #30
0
def pop3connection():
    M = poplib.POP3(pop3server)
    M.user(usernm)
    M.pass_(passwd)
    return M