示例#1
0
    def test_mail_blacklist(self):
        mail_obj = mail.Mail(
            mail_data.replace(b"2002:a4a:3b52:0:0:0:0:0",
                              b"unittest.malicious.com"))
        mail_obj.DOMAIN_COEFFICIENT = 2
        mail_obj.DOMAIN_THRESHOLD = 5
        mail_obj.check_blacklisted()
        self.assertTrue(mail_obj._spam)

        mail_obj = mail.Mail(
            mail_data.replace(b"*****@*****.**",
                              b"*****@*****.**"))
        mail_obj.MAIL_COEFFICIENT = 2
        mail_obj.MAIL_THRESHOLD = 5
        mail_obj.check_blacklisted()
        self.assertTrue(mail_obj._spam)
示例#2
0
文件: ioc.py 项目: klmhsb42/redirect
def manager():
    the_config = config.read_redirect_configs()
    from_email = the_config.get('mail', 'from')
    device_error_email = the_config.get('mail', 'device_error')
    activate_url_template = the_config.get('mail', 'activate_url_template')
    password_url_template = the_config.get('mail', 'password_url_template')

    redirect_domain = the_config.get('redirect', 'domain')
    redirect_activate_by_email = the_config.getboolean('redirect',
                                                       'activate_by_email')
    mock_dns = the_config.getboolean('redirect', 'mock_dns')

    if mock_dns:
        dns = MagicMock()
    else:
        statsd_cli = statsd_client(the_config)
        dns = Dns(the_config.get('aws', 'access_key_id'),
                  the_config.get('aws', 'secret_access_key'),
                  the_config.get('aws', 'hosted_zone_id'), statsd_cli)

    create_storage = db_helper.get_storage_creator(the_config)
    smtp = mail.get_smtp(the_config)

    the_mail = mail.Mail(smtp, from_email, activate_url_template,
                         password_url_template, device_error_email)
    users_manager = services.Users(create_storage, redirect_activate_by_email,
                                   the_mail, dns, redirect_domain)
    return users_manager
示例#3
0
    def checkJobs(self):
        if(self.upstream):
            for job in self.config.jobs:
                data = []
                index = self.config.jobs[job].get_index()
                for run in index:
                    console, date, link = utils.get_console(run)
                    if not console or not date:
                        continue

                    fails, ok, errors = utils.get_tests_results(console)
                    d = {
                        'run': True,
                        'date': date,
                        'link': link
                    }

                    if fails or errors:
                        covered, new = utils.compare_tests(fails)
                        d.update({
                            'failed': fails,
                            'covered': covered,
                            'new': new,
                            'errors': errors,
                        })
                    elif ok:
                        d['ok'] = ok
                    elif not fails and not ok and not errors:
                        d['run'] = False
                    data.append(d)

                data = sorted(data, key=lambda x: x['date'])
                last = data[-1]
                send_mail = mail.Mail(self.config)
                send_mail.send_mail(self.config.jobs[job], last)
示例#4
0
def reply():
    body = request.values.get('Body', None)
    number = request.values.get('From', None)
    print("Sender Number: " + number)
    command = base_command.Command(body).command
    return_text = ''
    print("Command: " + command)
    if command == "help":
        response = helps.Help(body)
        return_text = response.exec()
    elif command == "stock":
        response = stock.Stock(body)
        return_text = response.exec()
    elif command == "mail":
        response = mail.Mail(body)
        return_text = response.exec()
    elif command == "weather":
        response = weather.Weather(body)
        return_text = response.exec()
    elif command == "translate":
        response = translate.Translate(body)
        return_text = response.exec()
    elif command == "movie":
        response = movies.Movie(body)
        return_text = response.exec()

    if return_text == '':
        send_message("please type !help for response", number)
    else:
        print("RETURN MESSAGE:", return_text)
        send_message(return_text, number)
    return str(return_text)
示例#5
0
def main():
    emails = mail.Mail()
    emails.save_attachments()
    emails.logout()

    kindle_device = kindle.Kindle()
    kindle_device.convert_files()
    kindle_device.send_files()
示例#6
0
def send_mail(msg, to, filename, data):
	m = mail.Mail(CONFIG.email_user, CONFIG.email_password, CONFIG.email_smtp, CONFIG.email_user, CONFIG.email_sender_name)

	smtp_msg = m._prepare_msg('Donation Swap Stats Update', msg, msg, to, None, None)

	part = MIMEApplication(data, Name=filename)
	part['Content-Disposition'] = 'attachment; filename="' + filename + '"'
	smtp_msg.attach(part)

	m._send_msg(smtp_msg)
示例#7
0
    def __init__(self):
        self.trades = {}
        self.last_message = 0
        self.trade_no = 19
        self.last_update = datetime.datetime.now()

        self.mail = mail.Mail()
        self.mail.connect()
        self.bitmex = bitmex_api.Bitmex()

        self.percent = .02
 def run(self):
     pubmedresults, termsfound = textmining.textming_Start(
         self.termList, self.searchDept, [])
     sessionobject = self.createSessionObject(pubmedresults, termsfound)
     visualiseGraph.createNewGraph(sessionobject)
     try:
         databaseconnectie.databasevullen(sessionobject)
     except mysql.connector.errors.IntegrityError:
         #Still seems to work just fine
         pass
     databaseconnectie.sessiesophalen()
     mail.Mail(self.email, self.sessionName)
示例#9
0
def main():
    myConfig = config.Config()
    myWeibo = weibo.Weibo(myConfig)
    myMail = mail.Mail(myConfig)
    thread_pool = [myWeibo, myMail]
    for t in thread_pool:
        t.start()
        time.sleep(10)
    for t in thread_pool:
        t.join()
    print('###Everything has been done, now you can exit.###\n')
    while True:
        time.sleep(1)
    def __init__(self, email_id, series):

        self.getSeriesName(series)

        self.getimdbIDs()

        self.getSeason()

        self.Dates()

        self.datesToSend()

        mail.Mail(self.original_series, self.dates_to_send, email_id,
                  self.running_year)

        db.Database(email_id, series)
示例#11
0
	def __init__(self, config_path):
		self._config = config.Config(config_path)

		self._database = database.Database(self._config.db_connection_string)

		self._captcha = captcha.Captcha(self._config.captcha_secret)
		self._currency = currency.Currency(self._config.currency_cache, self._config.fixer_apikey)
		self._geoip = geoip.GeoIpCountry(self._config.geoip_datafile)
		self._mail = mail.Mail(self._config.email_user, self._config.email_password, self._config.email_smtp, self._config.email_from, self._config.email_sender_name)

		with self._database.connect() as db:
			entities.load(db)

		self._ip_address = None

		self.automation_mode = False
def CopyToOtherDirectories(path, dailyPdfPath, monthlyPdfPath):

    try:
        files = [f for f in listdir(path) if isfile(join(path, f))]

        for file in files:
            if not file.lower().endswith(".pdf"):
                continue

            # example source file name:  company_SFTP_statement_dstm_20150909.pdf
            day = file[-6:-4]
            month = file[-8:-6]
            year = file[-12:-8]

            if not day.isdigit() or not month.isdigit() or not year.isdigit():
                # there are no files that should trip this condition
                continue

            sourceFilePath = path + file

            # destination file postfix:  _MM_DD_YYYY.pdf
            if 0 < file.lower().find("_dstm_"):
                destFileName = "{0}_{1}_{2}_{3}.pdf".format(
                    g_dailyFileTemplate, month, day, year)
                destFilePath = dailyPdfPath + destFileName
                shutil.copy2(sourceFilePath, destFilePath)
                os.chown(destFilePath, 1019, 501)  # 1019 is jimmy's uid
            elif 0 < file.lower().find("_mstm_"):
                destFileName = "{0}_{1}_{2}_{3}.pdf".format(
                    g_monthlyFileTemplate, month, day, year)
                destFilePath = monthlyPdfPath + destFileName
                shutil.copy2(sourceFilePath, destFilePath)
                os.chown(destFilePath, 1019, 501)  # 1019 is jimmy's uid
            elif 0 < file.lower().find("_deqty_"):
                pass
            else:
                mail.Mail(sys.argv[0] + ": Notice",
                          dateTime + ": Unexpected file: " + file, False)

    except Exception as e:
        err = "CopyToOtherDirectories('{0}','{1}'): Exception caught: ".format(
            sourceFilePath, destFilePath) + repr(e)
        raise Exception(err)
示例#13
0
class Pop3Tests(unittest.TestCase):

    with open('test_message.txt', 'rb') as file:
        message = mail.Mail(file.read())

    client = mailclient.MailClient('*****@*****.**', 'pass')

    def test_is_message(self):
        self.assertIsInstance(self.message.message, email.message.Message)

    def test_get_header(self):
        headers = list(self.message.get_headers('Subject', 'Not Exists',
                                                'To'))
        expected = [('Subject', 'Some Subject'),
                    ('To', 'Слава Вихарев')]
        self.assertSequenceEqual(headers, expected)

    def test_get_message(self):
        message = self.message.get_message()
        expected = '''Hello World\nПривет Мир\nПривет'''
        self.assertEqual(message, expected)

    def test_check_number(self):
        self.assertFalse(self.client.check_mail_number('-1', 5))
        self.assertFalse(self.client.check_mail_number('0', 5))
        self.assertTrue(self.client.check_mail_number('1', 5), 1)
        self.assertTrue(self.client.check_mail_number('5', 5))
        self.assertFalse(self.client.check_mail_number('6', 5))
        self.assertFalse(self.client.check_mail_number('asd', 5))

    def test_check_address(self):
        address = '*****@*****.**'
        self.assertTrue(mailclient.check_address(address))
        address = 'domain.ru'
        self.assertFalse(mailclient.check_address(address))
        address = '@s.com'
        self.assertFalse(mailclient.check_address(address))
        address = '[email protected]'
        self.assertFalse(mailclient.check_address(address))
        address = 'a@com'
        self.assertFalse(mailclient.check_address(address))
示例#14
0
 def __init__(self, train, file):
     self.mail = mail.Mail(train)  # Create a mail object
     self.corpus = self.get_corpus()  # Brown corpus, lower case only
     self.spam = {}  # Dictionary containing word : count
     self.notspam = {}  # Dictionary containing word : count
     self.results = []  # Results of testing for spam
     self.correct = 0.0  # Correct number of emails
     self.correct_pct = 0.0  # Correct percentage
     self.incorrect = 0.0  # Incorrect number of emails
     self.incorrect_pct = 0.0  # Incorrect percentage
     self.total = 0.0  # Total number of predictions
     self.model = {}
     self.model_json = ""
     self.model_file = os.getcwd() + '/' + file
     self.spam_count = 0.0
     self.notspam_count = 0.0
     self.predicted_spam = 0.0
     self.predicted_notspam = 0.0
     self.correct_spam = 0.0
     self.incorrect_spam = 0.0
     self.correct_notspam = 0.0
     self.incorrect_notspam = 0.0
示例#15
0
    def connectPhone(self, port):
        try:
            self.ser = serial.Serial(port, 38400, timeout=1)  # открывакм порт
            time.sleep(0.1)

            self.flushing()
            time.sleep(0.1)

            # self.ser.write(b'ATZ\r') #сброс натроек модема
            # time.sleep(0.5)

            self.ser.write(
                b'AT+CMGF=1\r')  # установка текстового режима режима
            time.sleep(0.1)

            self.ser.write(b'AT+CPMS="ME","ME","ME"\r'
                           )  # изменить память для всех секторов
            time.sleep(0.1)
            #print(self.ser.readall().rsplit())

            self.ser.write(b'ATE0\r')  # отключение эхо
            time.sleep(0.1)

            self.ser.write(
                b'AT^CURC=0\r')  # отключаем отладочные сообщения для Huawei
            time.sleep(0.1)

            self.ser.write(
                b'AT+CSCS="UCS2"\r\n')  # выбираем кодировку близкую к utf-8
            time.sleep(0.1)

        except Exception:
            print("Порт был найден, но не был открыт")
            my_mail = mail.Mail()
            my_mail.send_Mail("Error connect to modem by port")
            my_mail.close_mail()
            sys.exit()
示例#16
0
def GetMessageInfos(opts):
    m = mail.Mail(
        opts["server"], "use_ssl" in opts, opts["username"], opts["password"], opts["days"], opts["date_from"],
        "record" in opts, "replay" in opts,
        "max_messages" in opts and int(opts["max_messages"]) or -1,
        "random_subset" in opts)

    # First, get all message infos
    if "use_label" not in opts:
       m.SelectAllMail()
    else:
       m.SelectMailbox(opts["use_label"])

    message_infos = m.GetMessageInfos()

    # Then for each mailbox, see which messages are in it, and attach that to
    # the mail info
    if "skip_labels" not in opts:
        message_infos_by_id = \
            dict([(mi.GetMessageId(), mi) for mi in message_infos])

        # Don't want to parse all these dates, since we already have them from the
        # message infos above.
        messageinfo.MessageInfo.SetParseDate(False)

        for mailbox in m.GetMailboxes():
            m.SelectMailbox(mailbox)
            message_ids = m.GetMessageIds()
            for mid in message_ids:
                if mid in message_infos_by_id:
                    message_info = message_infos_by_id[mid]
                    message_info.AddMailbox(mailbox)

        messageinfo.MessageInfo.SetParseDate(True)

    m.Logout()

    # Filter out those that we're not interested in
    if "filter_out" in opts:
        message_infos = FilterMessageInfos(message_infos, opts["filter_out"])

    # Tag messages as being from the user running the script
    if "me" in opts:
        logging.info("Identifying \"me\" messages")
        me_addresses = [
            address.lower().strip() for address in opts["me"].split(",")]

        me_from_count = 0
        me_to_count = 0

        for message_info in message_infos:
            name, address = message_info.GetSender()

            for me_address in me_addresses:
                if me_address == address:
                    message_info.is_from_me = True
                    me_from_count += 1
                    break

            for name, address in message_info.GetRecipients():
                for me_address in me_addresses:
                    if me_address == address:
                        message_info.is_to_me = True
                        me_to_count += 1
                        break
                if message_info.is_to_me: break

        logging.info("  %d messages are from \"me\"" % me_from_count)
        logging.info("  %d messages are to \"me\"" % me_to_count)

    return message_infos
示例#17
0
文件: aplication.py 项目: rcrs4/Mail
    socket.sendMessage(f"GET {email.getUser()}")
    msg = socket.recvMsg()
    while msg != constant.endMails and msg != constant.noMail:
        mail.Mail.putIntoMailBox(msg)
        msg = socket.recvMsg()


def menu(client, email):
    print(f"You have {mail.Mail.countMails()} Mail(s)")
    print("\nTo go to mail Box press 1\nTo send a email press 2\n")
    command = input()
    if command == '1':
        mail.Mail.readMailBox()
    elif command == '2':
        print("Put the destination")
    destination = input()
    print("Put the message")
    msg = input()
    client.sendMessage(
        f"SEND {email.getUser()} " +
        f"{destination:<{constant.HEADERSIZE-len(email.getUser())-len(destination)}} "
        + msg)


email = mail.Mail()
clientSocket = client.Client()
intro(clientSocket, email)
#os.system("clear")
while True:
    menu(clientSocket, email)
示例#18
0
 def test_received(self):
     mail_obj = mail.Mail(mail_data)
     self.assertEqual(
         mail_obj.header_data["Received"],
         'by 2002:a4a:3b52:0:0:0:0:0 with SMTP id s79csp5499397oos;\r\n        Mon, 14 Oct 2019 22:17:00 -0700 (PDT)'
     )
示例#19
0
 def raise_em(self):
     mail.Mail()
示例#20
0
from flask import Flask, request, jsonify
from flask_cors import cross_origin
import mail
import os
from dotenv import load_dotenv
import algorithms.feistel as feistel
import algorithms.sm2_dsa as sign
import algorithms.sm2 as sm2
import algorithms.ecc as ecc

app = Flask(__name__)
app.config['DEBUG'] = True

email = os.getenv("EMAIL")
m = mail.Mail()
s = sign.SM2_DSA()


@app.route('/send', methods=['POST'])
@cross_origin(origin='localhost')
def send():
    body = request.json
    to = body['to']
    subject = body['subject']
    message = body['message']
    encrypt_key = body['encryptKey']
    encrypt_mode = body['encryptMode']
    signature = body['signature']
    signature_key = body['signatureKey']
    enc = False
示例#21
0
def on_press(key):
    logging.info(str(key))
    # sending mail when user press enter button..
    if(key == Key.enter):
        # firing the sendMail function of our Mail() class in mail.py
        mail.Mail().sendMail()
        phoenixFirstDate = sortedPhoenixDateMargins[0]
        phoenixLastDate = sortedPhoenixDateMargins[
            len(sortedPhoenixDateMargins) - 1]
        # print "Phoenix FirstDate: '{0}', LastDate: '{1}'".format(phoenixFirstDate, phoenixLastDate)

        synthymTradingDays = GetTradingDays(synthymFirstDate, synthymLastDate)
        for tradingDay in synthymTradingDays:
            if not tradingDay in synthymDateMargins.keys():
                raise Exception(
                    "Trading day {0} has no Synthym file".format(tradingDay))

        phoenixTradingDays = GetTradingDays(phoenixFirstDate, phoenixLastDate)
        for tradingDay in phoenixTradingDays:
            if not tradingDay in phoenixDateMargins.keys():
                raise Exception(
                    "Trading day {0} has no Phoenix file".format(tradingDay))

        returnMsg = CheckInsertMarginsTiburon(synthymDateMargins, "Synthym")
        returnMsg += "\r\n\r\n"
        returnMsg += CheckInsertMarginsTiburon(phoenixDateMargins, "Phoenix")

        dateTime = time.strftime("%Y-%m-%d %H:%M:%S")
        mail.Mail(sys.argv[0] + ": Notice", dateTime + ":\r\n\r\n" + returnMsg,
                  False)

    except Exception as e:
        dateTime = time.strftime("%Y-%m-%d %H:%M:%S")
        mail.Mail(g_subject, dateTime + ": " + repr(e))
        # print(g_subject + dateTime + ": " + repr(e))
        exit(0)
示例#23
0
        if currency == 'CHN':
            price = float(data['ticker']['last'])
            buy = data['ticker']['buy']
            sell = data['ticker']['sell']
            symbol = '¥'
        else:
            price = float(data[currency]['last'])
            buy = str(data[currency]['buy'])
            sell = str(data[currency]['sell'])
            symbol = str(data[currency]['symbol'])

        if price > high or price < low:
            if time.time() - last_sent > 5 * 60:
                try:
                    m.send(send_to, "BTC Ticker Warning",
                           "the price now is " + str(price))
                    print "sent email"
                    last_sent = time.time()
                except Exception, e:
                    print e

        print("Price: " + symbol + str(price) + " Buy: " + symbol + buy +
              "  Sell: " + symbol + sell)
        time.sleep(3)


if __name__ == "__main__":
    m = mail.Mail(account, smtp_addr, account, password)
    moniter(m, send_to, high, low)
示例#24
0
 def test_domain_blacklist(self):
     mail_obj = mail.Mail(mail_data)
     mail_obj.DOMAIN_COEFFICIENT = 2
     mail_obj.DOMAIN_THRESHOLD = 5
     mail_obj.check_spam()
     self.assertTrue(mail_obj._spam)
示例#25
0
 def test_from(self):
     mail_obj = mail.Mail(mail_data)
     self.assertEqual(mail_obj.header_data["From"],
                      "Google <*****@*****.**>")
示例#26
0
文件: update.py 项目: Nalkey/update
    update_titles = []
    while i < len(updates.titles):
        timestamp = time.mktime(time.strptime(updates.titles[i].replace('CST', ''),
                                              "%a %b %d %H:%M:%S %Y"))
        if timestamp <= latest:
            return update_titles
        update_titles.append(updates.titles[i+1])
        i += 2
    return update_titles
    """该脚本最开始用正则表达式来处理HTML
    updates = re.findall(r'<em>(.+?)</em>.+?<a.+?">(.+?)</a>', text, re.S)
    # print(updates[0][0])
    if updates[0][0] != "Mon May 09 00:00:00 CST 2016":
        return updates[0][1]
    else:
        return None"""

if __name__ == '__main__':
    r = requests.get(URL)
    # print(type(r.status_code))
    if r.status_code == 200:
        titles = '\n'.join(get_title(r.text))
        action = mail.Mail()
        if titles:
            res = action.send_mail('网页更新:\n{}'.format(titles))
        else:
            res = action.send_mail('没更新')
        print(res)
    else:
        print('链接失败:{}'.format(r.status_code))
示例#27
0
def _send_mail(msg, to):
    cfg = config.Config(CONFIG_FILENAME)
    m = mail.Mail(cfg.watchdog_email_user, cfg.watchdog_email_password,
                  cfg.watchdog_email_smtp, cfg.watchdog_email_user,
                  cfg.watchdog_email_sender_name)
    m.send('Donation Swap Watchdog', msg, to=to, send_async=False)
示例#28
0
def GetMessageInfos(opts):

    if "maildir" in opts:
        m = mail.MaildirInfo(opts["maildir"])
    else:
        if "mailboxpackage" in opts:
            m = mail.MailBoxPackageInfo(opts["mailboxpackage"])
        else:
            m = mail.Mail(
                opts["server"],
                "use_ssl" in opts,
                opts["username"],
                opts["password"],
                "record" in opts,
                "replay" in opts,
                "max_messages" in opts and int(opts["max_messages"]) or -1,
                "random_subset" in opts,
            )

    message_infos = []
    server_mailbox = []
    if "server_mailbox" in opts:
        server_mailbox = opts['server_mailbox'].split(",")

    # Then for each mailbox, see which messages are in it, and attach that to
    # the mail info
    # if "skip_labels" not in opts:

    # Don't want to parse all these dates, since we already have them from the
    # message infos above.
    messageinfo.MessageInfo.SetParseDate(False)

    for mailbox in m.GetMailboxes():
        if len(server_mailbox) > 0:
            if mailbox not in server_mailbox:
                continue

        m.SelectMailbox(mailbox)
        mb_message_infos = m.GetMessageInfos()
        for message_info in mb_message_infos:
            message_info.AddMailbox(mailbox)
        message_infos.extend(mb_message_infos)
        logging.info("Mailbox had %d messages. Total=%d",
                     len(mb_message_infos), len(message_infos))

    message_infos_by_id = dict([(mi.GetMessageId(), mi)
                                for mi in message_infos])
    messageinfo.MessageInfo.SetParseDate(True)

    m.Logout()

    # Filter out those that we're not interested in
    if "filter_out" in opts:
        message_infos = FilterMessageInfos(message_infos, opts["filter_out"])

    # Tag messages as being from the user running the script
    if "me" in opts:
        logging.info("Identifying \"me\" messages")
        me_addresses = [
            address.lower().strip() for address in opts["me"].split(",")
        ]

        me_from_count = 0
        me_to_count = 0

        for message_info in message_infos:
            name, address = message_info.GetSender()

            for me_address in me_addresses:
                if me_address == address:
                    message_info.is_from_me = True
                    me_from_count += 1
                    break

            for name, address in message_info.GetRecipients():
                for me_address in me_addresses:
                    if me_address == address:
                        message_info.is_to_me = True
                        me_to_count += 1
                        break
                if message_info.is_to_me:
                    break

        logging.info("  %d messages are from \"me\"" % me_from_count)
        logging.info("  %d messages are to \"me\"" % me_to_count)

    return message_infos
示例#29
0
 def test_date(self):
     mail_obj = mail.Mail(mail_data)
     self.assertEqual(mail_obj.header_data["Date"],
                      "Tue, 15 Oct 2019 05:16:58 +0000 (GMT)")