Exemplo n.º 1
0
 def __init__(self, server, debug=0, do_expunge = options["imap", "expunge"] ):
     if ":" in server:
         server, port = server.split(':', 1)
         port = int(port)
     else:
         if options["imap", "use_ssl"]:
             port = 993
         else:
             port = 143
     if not hasattr(self, "ssl"):
         readline = self.readline
         self.readline = self.readline_timeout
     try:
         BaseIMAP.__init__(self, server, port)
     except (BaseIMAP.error, socket.gaierror, socket.error):
         if options["globals", "verbose"]:
             print >> sys.stderr, "Cannot connect to server", server, "on port", port
             if not hasattr(self, "ssl"):
                 print >> sys.stderr, ("If you are connecting to an SSL server,"
                                       "please ensure that you\n"
                                       "have the 'Use SSL' option enabled.")
         self.connected = False
     else:
         self.connected = True
     if not hasattr(self, "ssl"):
         self.readline = readline
     self.debug = debug
     self.do_expunge = do_expunge
     self.server = server
     self.port = port
     self.logged_in = False
     self.current_folder = None
     self._read = self.read
     self.read = self.safe_read
Exemplo n.º 2
0
 def login(self, username, pwd):
     try:
         BaseIMAP.login(self, username, pwd)  # superclass login
     except BaseIMAP.error, e:
         if str(e) == "permission denied":
             print "There was an error logging in to the IMAP server."
             print "The userid and/or password may be incorrect."
             sys.exit()
         else:
             raise
Exemplo n.º 3
0
 def logout(self):
     # sign off
     if self.do_expunge:
         # we may never have logged in, in which case we do nothing
         if self.logged_in:
             # expunge messages from the spam and unsure folders
             for fol in ["spam_folder",
                         "unsure_folder",]:
                 self.select(options["imap", fol])
                 self.expunge()
             # expunge messages from the ham and spam training folders
             for fol_list in ["ham_train_folders",
                              "spam_train_folders",]:
                 for fol in options["imap", fol_list]:
                     self.select(fol)
                     self.expunge()
     BaseIMAP.logout(self)  # superclass logout
Exemplo n.º 4
0
 def logout(self):
     """Log off from the IMAP server, possibly expunging.
     Note that most, if not all, of the expunging is probably done in
     SelectFolder, rather than here, for purposes of speed."""
     if self.connected and self.logged_in and self.do_expunge:
         for fol in ["spam_folder",
                     "unsure_folder",
                     "ham_folder"]:
             folder_name = options["imap", fol]
             if folder_name:
                 self.select(folder_name)
                 self.expunge()
         for fol_list in ["ham_train_folders",
                          "spam_train_folders",]:
             for fol in options["imap", fol_list]:
                 self.select(fol)
                 self.expunge()
     BaseIMAP.logout(self)  # superclass logout
Exemplo n.º 5
0
    def __init__(self, server, port, debug=0, do_expunge=False):
        try:
            BaseIMAP.__init__(self, server, port)
        except (BaseIMAP.error, socket.gaierror, socket.error):
            print "Cannot connect to server %s on port %s" % (server, port)
            sys.exit(-1)
        self.debug = debug
        # For efficiency, we remember which folder we are currently
        # in, and only send a select command to the IMAP server if
        # we want to *change* folders.  This function is used by
        # both IMAPMessage and IMAPFolder.
        self.current_folder = None
        self.do_expunge = do_expunge
        self.logged_in = False

        # We override the base read so that we only read a certain amount
        # of data at a time.  OS X and Python has problems with getting 
        # large amounts of memory at a time, so maybe this will be a way we
        # can work around that (I don't know, and don't have a mac to test,
        # but we need to try something).
        self._read = self.read
        self.read = self.safe_read
Exemplo n.º 6
0
 def __init__(self, mail, app_password):
     self.imap = IMAP4_SSL(host='imap.gmail.com', port=993)
     self.imap.login(mail, app_password)
Exemplo n.º 7
0
import os
from imaplib import IMAP4_SSL
from configparser import ConfigParser

config = ConfigParser()
config.read("imap-checker.ini")
imap_host = config['MailRu']['imap_host']
imap_port = config['MailRu']['imap_port']
username = config['MailRu']['username']
token = config['MailRu']['token']
action_url = config['MailRu']['action_url']
history_url = config['MailRu']['history_url']

with IMAP4_SSL(host=imap_host, port=imap_port) as M:
    M.login(username, token)
    M.select()
    return_code, mail_ids = M.search(None, 'UnSeen')
    mail_ids_splitted = mail_ids[0].decode().split(" ")
    if mail_ids_splitted[0] == '':
        unread_count = 0
        os.system("termux-notification-remove imap-checker")
    else:
        unread_count = len(mail_ids_splitted)
        os.system("termux-notification -i imap-checker \
        -t 'mail.ru' \
        -c 'unread messages: {}' \
        --action 'termux-open-url {}; \
          termux-notification-remove imap-checker' \
        --button1 'history' \
        --button1-action 'termux-open-url {}; \
          termux-notification-remove imap-checker' \
Exemplo n.º 8
0
 def login(self):
     self.imp = IMAP4_SSL(self.host)
     self.imp.login(self.user, self.password)
     self.imp.select("INBOX")
Exemplo n.º 9
0
print '*** Doing POP recv...'
s = POP3_SSL('pop.gmail.com', 995)
s.user(MAILBOX)
s.pass_(PASSWD)
rv, msg, sz = s.retr(s.stat()[0])
s.quit()
line = getSubject(msg)
print '    Received msg via POP: %r' % line

msg = msg.replace('587/TLS', '465/SSL')

# SMTP/SSL
if SMTP_SSL:
    print '*** Doing SMTP send via SSL...'
    s = SMTP_SSL('smtp.gmail.com', 465)
    s.login(MAILBOX, PASSWD)
    s.sendmail(from_, to, msg)
    s.quit()
    print '    SSL mail sent!'

# IMAP
print '*** Doing IMAP recv...'
s = IMAP4_SSL('imap.gmail.com', 993)
s.login(MAILBOX, PASSWD)
rsp, msgs = s.select('INBOX', True)
rsp, data = s.fetch(msgs[0], '(RFC822)')
line = getSubject(StringIO(data[0][1]))
s.close()
s.logout()
print '    Received msg via IMAP: %r' % line
Exemplo n.º 10
0
"""This file is to fetch summaries through IMAP and pass them on to the appropriate parser"""
#see http://docs.python.org/library/imaplib.html for the python interface
#see http://tools.ietf.org/html/rfc2060#section-6.4.4 for IMAP4 search criteria

import sys
from imaplib import IMAP4_SSL
from Summaries import Summaries
from PokerStarsSummaries import PokerStarsSummaries

#TODO: move all these into the config file. until then usage is: ./ImapSummaries.py YourImapHost YourImapUser YourImapPw 
configHost=sys.argv[1]
configUser=sys.argv[2]
configPw=sys.argv[3]

server = IMAP4_SSL(configHost) #TODO: optionally non-SSL
response = server.login(configUser, configPw) #TODO catch authentication error
#print "response to logging in:",response
#print "server.list():",server.list() #prints list of folders

response = server.select("INBOX")
#print "response to selecting INBOX:",response
if response[0]!="OK":
    raise error #TODO: show error message

neededMessages=[]
response, searchData = server.search(None, "SUBJECT", "PokerStars Tournament History Request")
for messageNumber in searchData[0].split(" "):
    response, headerData = server.fetch(messageNumber, "(BODY[HEADER.FIELDS (SUBJECT)])")
    #print "response to fetch subject:",response
    if response!="OK":
Exemplo n.º 11
0
TO = "*****@*****.**"  # адрес получателя
# SUBJECT = '=?UTF-8?B?0JfQsNGJ0LjRgtCwINC+0YIg0L/RgNC+0YLQtdGH0LXQug==?='  # тема письма
SUBJECT = '=?UTF-8?B?' + base64.b64encode(
    'Защита от протечек'.encode()).decode() + '?='  # тема письма

# Переменная для тела письма
body = "\n".join(
    ("From: %s" % FROM, "To: %s" % TO, "Subject: %s" % SUBJECT, ""))

SUBJECT_request = '=?UTF-8?B?' + base64.b64encode(
    'Протечка'.encode()).decode() + '?='  # тема письма запроса
SENDER = '*****@*****.**'  # отправитель запрса
UID = ''  # UID номер письма
last_uid = ''  # UID номер последнего письма

M = IMAP4_SSL('imap.mail.ru')
M.login('*****@*****.**', 'Asdf210781')
msgs = M.select(
    'inbox')  # подключаемся к папке входящие. пример ('OK', [b'8'])


def UID_new_email():  # выполняет проверку наличия новых писем
    global UID, last_uid

    if len(UID) == 0:
        with open('./UID_email.txt', 'r') as file:  # открываем файл для чтения
            for line in file:  # читаем строку
                UID = line

    typ_message_uid, list_message_uid = M.uid(
        'search', None, 'ALL')  # получаем список UID писем
Exemplo n.º 12
0
def read_emails():
    con = IMAP4_SSL(IMAP_URL)
    try:
        con.login(_userEmail, _password)
        con.select('Inbox')
        _, data = con.search(None, '(UNSEEN)')
        mail_ids = data[0]
        id_list = mail_ids.split()
        ans = ''
        if len(id_list) == 0:
            print("\nFinished!\nNo new emails found")
            con.logout()
            return

        for email_id in tqdm(reversed(id_list),
                             desc='\nFetching your emails ',
                             total=len(id_list)):
            _, email_data = con.fetch(email_id, '(RFC822)')
            # converts byte literal to string removing b''
            raw_email = email_data[0][1].decode("utf-8")
            email_msg = email.message_from_string(raw_email)
            extract_mail = re.findall(EMAIL_REGEX, email_msg['From'])[0]

            if is_contain_black_listed_sender(con, extract_mail,
                                              email_id):  ## action 1
                continue

            if is_contain_unknown_contact(con, extract_mail,
                                          email_id):  ## action 2
                continue

            is_offensive = False
            for part in email_msg.walk():
                if part.get_content_maintype() == 'multipart':
                    continue
                if part.get('Content-Disposition') is None:
                    continue

                file_type = part.get_content_type()
                if is_contain_forbidden_file_type(con, extract_mail, file_type,
                                                  email_id):  ## action 3
                    is_offensive = True
                    break

                file_name = part.get_filename().split('.')[0]
                if is_file_contain_forbidden_words(con, extract_mail, email_id,
                                                   file_name):  ## action 4
                    is_offensive = True
                    break

                file_data = part.get_payload(decode=True)
                if is_dangerous(con, file_data, extract_mail, email_id,
                                part.get_filename()):  ## action 5
                    is_offensive = True
                    break

            if is_offensive:
                continue

            subject = email_msg['Subject']
            body = extract_email_body_message(email_msg)
            if is_mail_contain_forbidden_words(con, extract_mail, email_id,
                                               subject, body):  ## action 6
                continue

            # Email passed all validationד, add it to mailbox
            ans += '\n----------------------- ' \
                   '\nEmail From: {}' \
                   '\nEmail Subject: {}' \
                   '\nDate: {}' \
                   '\nBody: {}'.format(extract_mail, subject, ' '.join(email_msg['Date'].split()[:5]),
                                       body)
        time.sleep(1)
        if ans == '':
            print('\nFinished!\nNo new emails found')
        else:
            print('\nFinished!\nYour Mailbox:{}'.format(ans).expandtabs(15))

    except Exception as e:
        print('DEBUG: read_mailbox() Failed: {} '.format(e))

    con.logout()
Exemplo n.º 13
0
def get_connection(host, username, password):
    """Initialize IMAP server and login"""
    server = IMAP4_SSL(host)
    server.login(username, password)
    server.select("inbox")
    return server
Exemplo n.º 14
0
    def mail(self):
        mail_data = {"mail": 0, "urgent": False}
        for k, v in self.mailboxes.items():
            mail_data[k] = 0
            for i, account in enumerate(v, 1):
                if k == "imap":
                    inbox = IMAP4_SSL(account["server"], account["port"])
                    inbox.login(account["user"], account["password"])

                    if self.first_run:
                        import re

                        filters = "|".join(account.pop("filters"))
                        objs = [x.decode() for x in inbox.list()[1]]
                        folders = [x[-1] for x in reader(objs, delimiter=" ")]
                        lines = ["===== IMAP {} =====".format(i)]
                        for name in folders:
                            subscribed = " "
                            try:
                                if re.search(filters, name):
                                    subscribed = "x"
                                    folder = name.replace("\\", "\\\\")
                                    folder = folder.replace('"', '\\"')
                                    folder = '"{}"'.format(folder)
                                    account["folders"].append(folder)
                            except re.error:
                                account["folders"] = []
                                break
                            lines.append("[{}] {}".format(subscribed, name))
                        if not account["folders"]:
                            self.py3.error(
                                STRING_INVALID_FILTER.format(filters),
                                self.py3.CACHE_FOREVER,
                            )
                        if account.get("log") is True:
                            for line in lines:
                                self.py3.log(line)

                    count_mail = 0
                    for folder in account["folders"]:
                        if inbox.select(folder, readonly=True)[0] == "OK":
                            imap_data = inbox.search(None, "(UNSEEN)")
                            count_mail += len(imap_data[1][0].split())
                        else:
                            account["folders"].remove(folder)
                    try:
                        inbox.close()
                        inbox.logout()
                    except IMAP4.error:
                        pass
                else:
                    inbox = getattr(mailbox, account["box"])(account["path"],
                                                             create=False)
                    count_mail = len(inbox)
                    inbox.close()
                if "name" in account:
                    mail_data[account["name"]] = count_mail
                if account["urgent"] and count_mail:
                    mail_data["urgent"] = True
                mail_data["{}_{}".format(k, i)] = count_mail
                mail_data["mail"] += count_mail
                mail_data[k] += count_mail

        for x in self.thresholds_init:
            if x in mail_data:
                self.py3.threshold_get_color(mail_data[x], x)

        self.first_run = False

        response = {
            "cached_until": self.py3.time_in(self.cache_timeout),
            "full_text": self.py3.safe_format(self.format, mail_data),
        }
        if mail_data["urgent"]:
            response["urgent"] = True
        return response
Exemplo n.º 15
0
def disconnect(imap: imaplib.IMAP4_SSL):
    imap.close()
Exemplo n.º 16
0
def login(imap: imaplib.IMAP4_SSL, username: str, password: str):
    imap.login(username, password)
Exemplo n.º 17
0
Arquivo: abuse.py Projeto: lopes/koala
 def __init__(self, server, user, password, workbox, bkpbox):
     self.server = IMAP4_SSL(server)
     self.server.login(user, password)
     self.workbox = workbox
     self.bkpbox = bkpbox
Exemplo n.º 18
0
print('***Doing POP recv...')
s = POP3_SSL('pop.163.com', 995)
s.user(MAILBOX)
s.pass_(PASSWD)
rv, msg_pop, sz = s.retr(s.stat()[0])
s.quit()
line = getSubject(msg_pop)
print('Received msg via POP: {}'.format(line.decode()))

headers[2] = headers[2].replace('25/TLS', '465/SSL')
msg_SSL = '\r\n\r\n'.join(('\r\n'.join(headers), '\r\n'.join(body)))
#SMTP/SSL
if SMTP_SSL:
    print('*** Doing SMTP send via SSL...')
    s = SMTP_SSL('smtp.163.com', 465)
    s.login(MAILBOX, PASSWD)
    s.sendmail(from_, to, msg_SSL)
    s.quit()
    print('SSL mail sent!')

# IMAP
print('***Doing IMAP recv...')
s = IMAP4_SSL('imap.qq.com', 993)
s.login(MAILBOX_QQ, PASSWD_QQ)
rsp, Msgs = s.select('INBOX', True)
rsp, data = s.fetch(Msgs[0], '(RFC822)')
line = getSubject(StringIO(data[0][1].decode()))

s.close()
s.logout()
print('Received msg via IMAP: {}'.format(line))
Exemplo n.º 19
0
 def _get_message(self, mailbox: IMAP4_SSL, uid: int) -> email.message.Message:
     self.update('mailbox', 'retrieving mail')
     return email.message_from_bytes(mailbox.uid('FETCH', str(uid), '(RFC822)')[1][0][1])
Exemplo n.º 20
0
def connect(creds: Credentials) -> IMAP4_SSL:
    imap = IMAP4_SSL('imap.gmail.com')
    imap.login(creds.id, creds.pwd)
    imap.select()
    return imap
from conf import login
from conf import password
import smtplib
from imaplib import IMAP4_SSL

server = "mail.uar.net"

# HOST = "imap.yandex.ru"
# PORT = 993
USER = "******"
PASSWORD = "******"
# SENDER = "Yoba"

connection = IMAP4_SSL(host=server)
connection.login(user=login, password=password)
status, msgs = connection.select('INBOX')
assert status == 'OK'

typ, data = connection.search(None, 'FROM', '"%s"', "Forwarded")
print(data)
for num in data[0].split():
    typ, message_data = connection.fetch(num, '(RFC822)')
    print(data)
    print('Message %s\n%s\n' % (num, message_data[0][1]))
connection.close()
connection.logout()
Exemplo n.º 22
0
email_user = os.environ.get('email_username')
email_pass = os.environ.get('email_password')
server = os.environ.get('email_server')
search = json.load(open('search_actions.json','r'))

print(search['email'])

def process_message(mail,action):

    actions.opt[action](mail)


#connect and login to the mailserver
try:
    mailserver = IMAP4_SSL(server)
    resp = mailserver.login(email_user,email_pass)
except imaplib.error as err:
    print(err)
    print("unable to login or connect to server.")

#select the inbox 'folder'
mailserver.select("INBOX")

for option in search['email']:
    print(option)

    (repcode, list) = mailserver.uid('search', None, '(%s)' % option['search-criteria'])
    print(list)
    if len(list[0].decode('utf-8')) == 0:
        break
 def setup_connection(self):
     self.server = IMAP4_SSL(self.HOST, port=self.PORT)
     self.server.login(self.USER, self.PASSWORD)
Exemplo n.º 24
0
def _auth():
    mbox = IMAP4_SSL(SERVER)
    mbox.login(USERNAME, PASSWORD)
    return mbox
Exemplo n.º 25
0
    print("Invalid SMTP credentials.")
    exit()
errs = sendSvr.sendmail(who, recipients, body)
sendSvr.quit()
assert len(errs) == 0, errs
choice = input(
    "Mail sent. Which protocol do you want to use for receiving it? (POP / IMAP)? "
)
if not (choice == "POP" or choice == "IMAP"):
    print("Please enter a valid choice.")
    exit()
sleep(10)  #wait for mail to be delivered
if choice == "IMAP":
    # IMAP stuff below.
    try:
        recvSvr = IMAP4_SSL(IMAPSVR, 993)
    except gaierror:
        print("Can't connect to %s." % IMAPSVR)
        exit()
    try:
        recvSvr.login(who, PASSWD)
    except imaplib.error as e:
        print(str(e)[2:-1])  # This may be a stupid thing to do.
        exit()
    rsp, msgs = recvSvr.select('INBOX', True)
    try:
        rsp, data = recvSvr.fetch(msgs[0], '(RFC822)')
    except imaplib.error as e:
        print(e)
        exit()
    recvBody = data[0][1].decode('unicode_escape').split('\r\n')
Exemplo n.º 26
0
import email
import email.utils
import re
import csv
import getpass
from PIL import Image
from datetime import datetime
from imaplib import IMAP4, IMAP4_SSL
from bs4 import BeautifulSoup
from selenium import webdriver
from time import sleep
import config

# Connect to the server
if config.IMAP_SSL:
    mailbox = IMAP4_SSL(host=config.IMAP_HOST, port=config.IMAP_PORT)
else:
    mailbox = IMAP4(host=config.IMAP_HOST, port=config.IMAP_PORT)

# Log in and select the configured folder
mailbox.login(config.IMAP_USERNAME, config.IMAP_PASSWORD)
mailbox.select(config.FOLDER)

# Search for matching emails
status, messages = mailbox.search(None, '(FROM {})'.format(config.FROM_EMAIL))
if status == "OK":
    # Convert the result list to an array of message IDs
    messages = messages[0].split()

    if len(messages) < 1:
        # No matching messages, stop
Exemplo n.º 27
0
PATH = r'\\10.37.2.3\Documents\01_Бухгалтерия\From Sberbank\ '
EXTRACT_PATH = r'\\10.37.2.3\Documents\01_Бухгалтерия\From Sberbank\Обработанные\ '
LOG_PATH = r'\\10.37.2.3\Documents\01_Бухгалтерия\From Sberbank\app.log'

logging.basicConfig(level=logging.INFO, filename=LOG_PATH, format='%(asctime)s - %(message)s')

def extract_attachment(file_name):
    with zipfile.ZipFile(file_name) as z_file:
        z_file.extractall(EXTRACT_PATH.strip())

    return filename[:-3] + 'xlsx'


files = list(filter(lambda x: x.endswith('.zip'), os.listdir(PATH.strip())))

connection = IMAP4_SSL(host=YA_HOST, port=YA_PORT)
connection.login(user=YA_USER, password=YA_PASSWORD)
status, msgs = connection.select('INBOX')
logging.info('Скрипт запущен ')
if status != 'OK':
    logging.info('Соединение не установлено! ' + YA_HOST + ' ' + YA_PORT + ' ' + YA_USER + ' ' + YA_PASSWORD)
else:
    logging.info('Соединение установлено!')
assert status == 'OK'

typ, data = connection.search(None, 'FROM', '"%s"' % SENDER)

for num in data[0].split():
    typ, message_data = connection.fetch(num, '(RFC822)')
    mail = email.message_from_bytes(message_data[0][1])
Exemplo n.º 28
0
    def __init__(self, server, account, password):
        self.server = server
        self.account = account
        self.password = password

        self.client = IMAP4_SSL(self.server)
Exemplo n.º 29
0
#SETTING pin numbering system as BCM
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)


def High(PinNumber):
    GPIO.setup(PinNumber, GPIO.OUT)
    GPIO.output(PinNumber, 1)


def Low(PinNumber):
    GPIO.setup(PinNumber, GPIO.OUT)
    GPIO.output(PinNumber, 0)


mail = IMAP4_SSL('imap.gmail.com')  # connects IMAP services
mail.login(
    "*****@*****.**",
    "password")  #it is recommended to have separate account for the purpose

while True:
    # print(mail.list())
    mail.select("INBOX")
    result, data = mail.search(
        None, "ALL"
    )  # first item of list which contains all mail as [b'1 2 3 4'],#result is string as "ok"(status)
    ids = data[0]  # ids will be b'1 2 3 4'
    # print(ids)#output b'1 2 3 4'
    id_list = ids.split()  # eleliminates space and makes a new list
    # print(id_list) [b'1', b'2', b'3', b'4'
    latest_id = id_list[-1]
Exemplo n.º 30
0
 def __init__(self):
     self.imap = IMAP4_SSL(self.imap_server, self.imap_ssl_port)
     self.imap.login("*****@*****.**", "passphrases")
     self.smtp = SMTP_SSL(self.smtp_server, self.smtp_ssl_port)
     self.smtp.login("*****@*****.**", "passphrases")
Exemplo n.º 31
0
 def _login(self):
     imap = IMAP4_SSL(self.server)
     imap.login(self.user, self.password)
     return imap
Exemplo n.º 32
0
FROM = "*****@*****.**"  # адрес отправки письма
TO = "*****@*****.**"  # адрес получателя
SUBJECT = '=?UTF-8?B?' + base64.b64encode(
    'Квартира'.encode()).decode() + '?='  # тема письма

# Переменная для тела письма
body = "\n".join(
    ("From: %s" % FROM, "To: %s" % TO, "Subject: %s" % SUBJECT, ""))

SUBJECT_request = '=?UTF-8?B?' + base64.b64encode(
    'Квартира'.encode()).decode() + '?='  # тема письма для запроса
SENDER = '*****@*****.**'  # отправитель запрса
UID = ''  # UID номер письма
last_uid = ''  # UID номер последнего письма

M = IMAP4_SSL('imap.mail.ru')  # почтовый сервер
M.login('*****@*****.**',
        'Asdf210781')  # адрес почты для запроса. подключаемся
msgs = M.select(
    'inbox')  # подключаемся к папке входящие. пример ('OK', [b'8'])

CONNECT = True

LINK = 'https://ya.ru'  # ссылка для проверки интернета
Flag = 1
T_1 = ''  # переменная для фиксации даты и времени разрыва интернета


def Con_ser():
    global CONNECT, ser
Exemplo n.º 33
0
 def login(self):
     self.conn = IMAP4_SSL('imap.gmail.com')
     response = self.conn.login(self.username, self.password)
     return response
Exemplo n.º 34
0
        print '    error: server unexpectedly disconnected... try again'
else:
    print '    error: SMTP_SSL requires 2.6.3+'

# POP
print '*** Doing POP recv...'
try:
    s = POP3_SSL('pop.mail.yahoo.com', 995)
    s.user(MAILBOX)
    s.pass_(PASSWD)
    rv, msg, sz = s.retr(s.stat()[0])
    s.quit()
    line = getSubject(msg)
    print '    Received msg via POP: %r' % line
except error_proto:
    print '    error: POP for Yahoo!Mail Plus subscribers only'

# IMAP
print '*** Doing IMAP recv...'
try:
    s = IMAP4_SSL('imap.n.mail.yahoo.com', 993)
    s.login(MAILBOX, PASSWD)
    rsp, msgs = s.select('INBOX', True)
    rsp, data = s.fetch(msgs[0], '(RFC822)')
    line = getSubject(StringIO(data[0][1]))
    s.close()
    s.logout()
    print '    Received msg via IMAP: %r' % line
except error:
    print '    error: IMAP for Yahoo!Mail Plus subscribers only'
Exemplo n.º 35
0
    def search_email(self, from_address):
        try:
            # 受信サーバアクセス
            conn = IMAP4_SSL(self.imap_host, self.imap_port)
            conn.login(self.user, self.password)

            # 受信トレイ検索
            conn.list()
            conn.select('inbox')

            # 特定の送信者アドレスのメールを取得
            typ, data = conn.search(None,
                                    '(ALL HEADER FROM "%s")' % from_address)

            ids = data[0].split()
            self.enable_camera = 0
            print("ids=%s" % ids)

            # 受信メール格納内容を初期化
            self.email = {
                'from_address': "",
                'to_addresses': "",
                'cc_addresses': "",
                'bcc_addresses': "",
                'date': "",
                'subject': "",
                'body': "",
            }

            if ids:
                # 新しいものから順に確認
                for id in ids[::-1]:
                    typ, data = conn.fetch(id, '(RFC822)')
                    raw_email = data[0][1]

                    msg = email.message_from_string(raw_email.decode('utf-8'))
                    msg_encoding = decode_header(msg.get(
                        'Subject'))[0][1] or self.email_default_encoding
                    msg = email.message_from_string(
                        raw_email.decode(msg_encoding))

                    date = msg.get('Date')
                    subject = ""

                    body = ""
                    try:
                        tmp_str = msg.get_payload()
                        body = base64.standard_b64decode(
                            tmp_str + '=' *
                            (-len(tmp_str) % 4)).decode(encoding='utf-8')
                    except:
                        body = msg.get_payload()
                        print("Warning : probabry ascii only message.")

                    print("date    : %s" % date)
                    print("body    : %s" % body)

                    # 本文にキーワードが含まれる
                    k = 0
                    try:
                        k = re.search(TRIGGER_KEYWORD, body)
                    except:
                        print(
                            "Warning : probabry email has attach file. this message ignored."
                        )

                    if k:
                        # 解析したメールは削除
                        conn.store(id, '+FLAGS', '\\Deleted')

                        # カメラ撮影を許可する
                        self.enable_camera = 1

                        self.email = {
                            'from_address': msg.get('From'),
                            'to_addresses': msg.get('To'),
                            'cc_addresses': msg.get('CC'),
                            'bcc_addresses': msg.get('BCC'),
                            'date': date,
                            'subject': subject,
                            'body': body,
                        }
                        break

        except:
            raise

        finally:
            conn.close()
            conn.logout()