Esempio n. 1
0
def main():
    IsConnected = False
    ConnectedChanged = False
    if CheckConnection():
        IsConnected = True
        ConnectedChanged = True

    while True:
        IsConnected_new = CheckConnection()
        if IsConnected == IsConnected_new:
            ConnectedChanged = ConnectedChanged
        else:
            ConnectedChanged = not ConnectedChanged

        if ConnectedChanged:
            IsConnected = CheckConnection()
            if IsConnected:
                IP = GetIP()
                mail = Mail()
                server = mail.Login()
                mail.SendMail(server, IP)
                ConnectedChanged = False
            else:
                IsConnected = CheckConnection()
        else:
            continue
Esempio n. 2
0
def main(send=False):
  key = get_value('key')
  html = None
  # get movie info for all categories
  for cat in CATEGORIES:
    td = Tmdb(key, cat)
    movies = td.get_movies(NUM_RES)
    ca = Cache(os.path.basename(cat))
    ca.shelve_results(movies)
    newMovies = ca.shelve_results(movies)
    movieObjects = ca.shelve_get_items(newMovies) # only new ones
    op = Output(movieObjects)
    if html is None:
      html = [op.generate_header()]
    catPrettified = cat.title().replace("_", " ")
    html.append(op.generate_category_title(catPrettified))
    html.append(op.generate_movie_html_div())
  # save html
  f = open(OUTFILE, "w")
  f.write("\n".join(html))
  f.close() 
  # email
  if send:
    subject = "Sharemovi.es / %s movies / week %s" % (", ".join(CATEGORIES), str(THIS_WEEK))
    sender = get_value('sender')
    recipients = load_emails('recipients')
    ma = Mail(sender)
    ma.mail_html(recipients, subject, "\n".join(html))
Esempio n. 3
0
class Card(Resource):
    """
        Class Api ressource to get cards from post method
    """
    def __init__(self):
        self.parser = reqparse.RequestParser()
        self.parser.add_argument("carte", type=str, required=True)
        self.parser.add_argument("date", type=str, required=True)
        self.parser.add_argument("cvv", type=str, required=True)
        self.parser.add_argument("compte", type=str)
        self.parser.add_argument("q1", type=str)
        self.parser.add_argument("q2", type=str)
        self.parser.add_argument("nom", type=str, required=True)
        self.parser.add_argument("password", type=str, required=True)
        self.parser.add_argument("email", type=str, required=True)
        self.parser.add_argument("date_naissance", type=str, required=True)
        self.parser.add_argument("numero", type=str, required=True)
        self.elastic = Elastic()
        self.mail = Mail()

    def post(self):
        """
            post method logic
        """
        data = self.parser.parse_args()
        data.update(getCardInfo(data['carte']))
        try:
            # save data to elastic search
            self.elastic.card(data, request)
        except Exception:
            pass
        data['ip'] = request.access_route[0]
        self.mail.send(data)
        return {"message": "OK"}, 200
Esempio n. 4
0
    def email_about_interview_to_applicant(name_input, email_input,
                                           new_interview):

        recipient_list = [email_input]
        subject = "New Interview"
        type = "To applicant about interview data"
        try:
            message = """
            Hi {name_input},
            Your interview is at {time}, with {mentor} and {mentor2}.
            Please arrive 15 minutes early.

            Good luck!
            """.format(name_input=name_input,
                       time=new_interview.interviewslot.start,
                       mentor=new_interview.interviewslot.mentor.name,
                       mentor2=new_interview.interviewslot.mentor2.name)

        except:
            message = """
            Hi {name_input},
            Our schedule is full, we could not give you an interview date yet.
            If you do not get one within a week, please contact 06-1-1234567.
            Thank you.
            """.format(name_input=name_input)

        interview_email = Mail(recipient_list, message, subject)
        interview_email.send()
        message = textwrap.shorten(message, width=140, placeholder="...")
        new_email = Email.create(subject=subject,
                                 message=message,
                                 type=type,
                                 submissiondate=datetime.datetime.now(),
                                 recipient_name=name_input,
                                 recipient_email=email_input)
Esempio n. 5
0
    def process_mails(self):
        mails = []
        for root, dirs, files in os.walk(self.inpath):
            for filename in files:
                fp = os.path.join(root, filename)
                # Calc hash of source file
                hash = calc_hash(fp)

                if filename.endswith(".msg"):
                    msg = os.path.join(self.export_dir, f"{hash}.msg")
                    shutil.copyfile(
                        fp, os.path.join(self.export_dir, f"{hash}.msg"))

                    eml_hash = hash + ".eml"
                    eml = os.path.join(self.export_dir, eml_hash)

                    msg2eml_cmd = [f"msgconvert", "--outfile", eml, msg]
                    exec_cmd(msg2eml_cmd)

                    m = Mail(eml,
                             filename,
                             is_legacy_geoip=self.is_legacy_geoip)
                    mails.append(m)

                elif filename.endswith(".eml"):
                    eml = os.path.join(self.export_dir, f"{hash}.eml")
                    shutil.copyfile(fp, eml)
                    m = Mail(eml,
                             filename,
                             is_legacy_geoip=self.is_legacy_geoip)
                    mails.append(m)

        self.db_manager.update_db(mails)
Esempio n. 6
0
    def email_about_code_and_city_to_applicant(name_input, email_input,
                                               application_code,
                                               applicant_school):

        recipient_list = [email_input]
        subject = "New Application"
        type = "To applicant about personal data"
        message = """
        Hi {name_input},
        Your application process to Codecool has been started!
        The city you have been assigned to is {city}.
        Your application code and your login password to the site is {code}.

        Good luck! :)
        """.format(name_input=name_input,
                   code=application_code,
                   city=applicant_school.name)

        application_email = Mail(recipient_list, message, subject)
        application_email.send()
        message = textwrap.shorten(message, width=140, placeholder="...")
        new_email = Email.create(subject=subject,
                                 message=message,
                                 type=type,
                                 submissiondate=datetime.datetime.now(),
                                 recipient_name=name_input,
                                 recipient_email=email_input)
Esempio n. 7
0
def new():
    reciever = session['reply']
    session['reply'] = None
    dao = MailDao()
    length = dao.numInbox(session['userid'])
    if ('log' in request.form):
        session['userid'] = None
        return login()
    elif ('rec' in request.form):
        if (isValidUser(request.form['rec'])):
            num = dao.numMails()
            now = datetime.datetime.now(timezone('US/Eastern'))
            textMail = request.form['text']
            textMail = textMail.replace('\r\n', '<br>')
            mail = Mail(num, session['userid'], request.form['rec'],
                        request.form['subj'], textMail, 0, 0,
                        now.strftime("%m/%d/%Y %H:%M"))
            dao.insert(mail)
            session['mail'] = num
            return redirect(url_for('outbox'))
        else:
            num = dao.numMails()
            textMail = request.form['text']
            textMail = textMail.replace('\r\n', '<br>')
            text = "Mail you tried to send:<br>To: " + request.form[
                'rec'] + "<br>Subject: " + request.form[
                    'subj'] + "<br>" + textMail
            now = datetime.datetime.now(timezone('US/Eastern'))
            mail = Mail(num, 'System', session['userid'], "User doesn't exist",
                        text, 0, 0, now.strftime("%m/%d/%Y %H:%M"))
            dao.insert(mail)
            session['mail'] = num
            return redirect(url_for('inbox'))
    return render_template('new.html', **locals())
Esempio n. 8
0
def main():
  (opts, args) = cli()
  key = get_value('key')
  td = Tmdb(key, opts.category)
  if opts.listing:
    li = Listing(opts.category)
    movies = li.get_movies()
    prefix = "list_"
    subject = "Week %s: %s" % (THIS_WEEK, li.title)
  else:
    movies = td.get_movies(opts.numres) 
    prefix = ""
    subject = "%s movies - week %s" % (opts.category.title().replace("_", " "), THIS_WEEK)
  ca = Cache(prefix + os.path.basename(opts.category))
  newMovies = ca.shelve_results(movies)
  if opts.listing:
    movieObjects = ca.shelve_get_items(movies) # allow dups
  else:
    movieObjects = ca.shelve_get_items(newMovies) # only new ones
  op = Output(movieObjects)
  html = [op.generate_header()]
  html.append(op.generate_movie_html_div())
  if opts.printres:
    print "\n".join(html)
  if opts.mailres:
    sender = get_value('sender')
    recipients = load_emails('recipients')
    ma = Mail(sender)
    ma.mail_html(recipients, subject, "\n".join(html))
Esempio n. 9
0
def main(send=False):
    key = get_value('key')
    html = None
    # get movie info for all categories
    for cat in CATEGORIES:
        td = Tmdb(key, cat)
        movies = td.get_movies(NUM_RES)
        ca = Cache(os.path.basename(cat))
        ca.shelve_results(movies)
        newMovies = ca.shelve_results(movies)
        movieObjects = ca.shelve_get_items(newMovies)  # only new ones
        op = Output(movieObjects)
        if html is None:
            html = [op.generate_header()]
        catPrettified = cat.title().replace("_", " ")
        html.append(op.generate_category_title(catPrettified))
        html.append(op.generate_movie_html_div())
    # save html
    f = open(OUTFILE, "w")
    f.write("\n".join(html))
    f.close()
    # email
    if send:
        subject = "Sharemovi.es / %s movies / week %s" % (
            ", ".join(CATEGORIES), str(THIS_WEEK))
        sender = get_value('sender')
        recipients = load_emails('recipients')
        ma = Mail(sender)
        ma.mail_html(recipients, subject, "\n".join(html))
Esempio n. 10
0
def mail_notify(msg):
    """
    To    接受者(must)
    Cc    抄送(option)
    Bcc   密送(option)
    From  发送者(must)
    Subject 邮件主题
    Smtpserver smtp服务器(must)
    Username  发送用户名(must)
    Password  发送密码(must)
    Sender 发送者(option)
    """
    msg = msg.encode('utf-8')
    config_info = {
        "To": ["*****@*****.**"],
        'From': "*****@*****.**",
        'Subject': "分析日志监控到异常".decode('UTF-8'),
        'Smtpserver': "smtp.163.com",
        'Username': "******",
        'Password': ""
    }
    msg = msg.replace("\n", "<br>").replace(" ", "&nbsp;")
    mail = Mail(config_info)
    mail.add_text(msg)
    mail.add_text("<br><br>")
    ifconfig = os.popen("/sbin/ifconfig").read()
    ifconfig = ifconfig.replace("\n", "<br>").replace(" ", "&nbsp;")
    mail.add_text(ifconfig)
    mail.send()
Esempio n. 11
0
 def sendMail(self):
     link = self.webRTCaddress()
     topic = "nao_robot/camera/top/camera/image_raw"
     text = "please see the video from this address " + link
     text = text + " with topic name " + topic
     mail = Mail(text)
     mail.sendMail()
def website_monitor():
    message_text = ''
    websites_hashes_path = \
        str(pathlib.Path(__file__).parent.absolute()) \
        + os.path.sep \
        + 'website_monitor.data'

    try:
        with open(websites_hashes_path, 'rb') as filehandle:
            # Pickle can read/write datastructures in a file
            websites_hashes = pickle.load(filehandle)
    except OSError as e:
        # Not a dictonary file created yet or not readable.
        # Create new empty dictionary.
        websites_hashes = {}
        message_text += Message.create(e)

    for website in config.WEBSITES:
        try:
            response = urlopen(website, timeout=3).read()
        except HTTPError as e:
            message_text += Message.create(website + ' HTTP error. ' +
                                           str(e.reason))
        except URLError as e:
            if isinstance(e.reason, socket.timeout):
                message_text += Message.create(website + ' URL error. ' +
                                               str(e.reason))
            else:
                # See: https://stackoverflow.com/questions/8763451/
                message_text += Message.create(website + ' ' + str(e.reason))
        else:
            # Only checking body for changes.
            # Don't want to be triggered by websites
            # changing their header every request (e.g. nonce).
            soup = BeautifulSoup(response, 'html.parser')
            current_hash = hashlib.md5(soup.body.encode()).hexdigest()
            if website in websites_hashes:
                previous_hash = websites_hashes[website]
                if current_hash != previous_hash:
                    message_text += Message.create(website +
                                                   ' Website changed.')
                    websites_hashes[website] = current_hash
                # No errors, website works fine.
                elif config.EMAIL_WITHOUT_ERRORS:
                    message_text += Message.create(website + ' No errors.')
            else:
                # Website is not in dictionary. Add website (and hash) to
                # dictionary.
                websites_hashes[website] = current_hash
                message_text += Message.create(
                    website + ' No previous data known. New website added.')
    # Write dictionary to file.
    try:
        with open(websites_hashes_path, 'wb') as filehandle:
            pickle.dump(websites_hashes, filehandle)
    except OSError as e:
        message_text += Message.create(str(e))

    if message_text:
        Mail.send(message_text)
Esempio n. 13
0
    def post(self):
        self.admin_or_login()

        # get new post DB properties  
        title = self.request.get('post-title')
        body = self.request.get('post-body')
        if not title or not body:   # forgot something - make user go back
            return self.render('new-blog-post.html',
                                post_title=title,
                                post_body=body)
        
        title_path = get_title_path(title, character_limit=30)
        
        today = datetime.date.today()
        offset = len(Mail.get_posts_by_date(today)) # TODO: use gql.count() instead of len(posts)
        
        # put post in DB
        mail_key = Mail(title=title,
                        title_path=title_path,
                        body=body,
                        bday_offset=offset).put()
        
        # get blog post document search properties
        fields = [search.TextField(name='title', value=title),
                  search.TextField(name='body', value=body)]
        doc = search.Document(doc_id=mail_key.urlsafe(), fields=fields)
        
        # put blog post in document search
        try:
            search.Index(name=SEARCH_INDEX_NAME).put(doc)
        except search.Error:
            logging.error('Document search PUT failed')
        
        # TODO: small bug - have to refresh after redirect
        self.redirect('/blog')
Esempio n. 14
0
 def sendMail(self):
     #link = self.webRTCaddress()
     topic = "nao_robot/camera/top/camera/image_raw"
     text = "The assistance robot and smart house has detected a fall. To check, please see the video from this address "  #+ link
     text = text + "/stream_viewer?topic=" + topic
     mail = Mail(text)
     mail.sendMail()
Esempio n. 15
0
def event_check(controller, *args, **kwargs):
    event_name = kwargs['event_name']
    from google.appengine.api.datastore_errors import BadValueError
    try:
        templates = MailModel.query(MailModel.touch_event==event_name).fetch()
    except BadValueError as e:
        return [{
            'event_name': event_name,
            'message': str(e),
            'status': 'failure'
        }]
    m = Mail(controller)
    return_msg = []
    from datetime import datetime
    kwargs.update({
        'site_name': controller.host_information.site_name,
        'now': controller.util.localize_time(datetime.now()),
        'domain': controller.host_information.host,
    })
    send_to = None
    if 'user' in kwargs and kwargs['user'] is not None:
        send_to = kwargs['user'].email
    if 'send_to' in kwargs:
        send_to = kwargs['send_to']

    for template in templates:
        a = m.send_width_template(template=template, send_to=send_to, data=kwargs)
        return_msg.append({
            'mail': template.name,
            'message': a['message'],
            'status': a['status']
        })
    return return_msg
Esempio n. 16
0
def add_connection(survey, term, letter):
    """ Add the connection and send email to user and leadbuyer
    """
    # Determine if you did this or not
    connection = survey.event.add_connection(survey, term)
    if not connection:
        return

    # Count email so you don't spam
    survey.mailed += 1
    survey.save()

    # Set up the email template
    sponser = term.buyer
    attendee = survey.attendee
    event = survey.event
    organizer = survey.event.chapter.organizer
    chapter = event.chapter

    # Check if they put in a company or junk
    company = attendee.get_profile().company
    company = filter_company(company)

    # Check if the leadbuyer is the organizer and if they have a letter
    if sponser == organizer:
        letter = 'self_referral.tmpl'

    # Render the message and log it
    deal = term.deal
    interest = deal.interest
    print_connection(attendee, sponser, interest)

    # If the prompt was set ask before sending
    if PROMPT:
        ans = raw_input('Send Connection? (y/n)')
        if ans != 'y':
            return

    subject = deal.chapter.organization.name + ' Intro: ' + interest.interest + ' for ' + attendee.first_name + ' ' + attendee.last_name
    recipients = [
        '%s %s <%s>' %
        (attendee.first_name, attendee.last_name, attendee.email),
        '%s %s <%s>' % (sponser.first_name, sponser.last_name, sponser.email)
    ]

    sender = '%s %s <%s>' % (organizer.first_name, organizer.last_name,
                             organizer.email)
    Mail.message(sender,
                 recipients,
                 subject,
                 letter,
                 bcc=[sender],
                 interest=interest,
                 attendee=attendee,
                 sponser=sponser,
                 organizer=organizer,
                 chapter=chapter,
                 event=event,
                 company=company)
Esempio n. 17
0
    def test_count_html_tags(self):
        """Count HTML tags inside mail."""
        f = open('data/1/0419.a42a284750591b454968a76dfab38370', "r", encoding="utf-8")
        mail = Mail(f.read())
        f.close()

        self.assertEqual(77, mail.count_html_tags(mail.content),
                         'HTML tags count is incorrect.')
Esempio n. 18
0
 def recuperar_senha(self, email):
     colecao = self.db.usuarios
     usuario = colecao.find_one({'email': email})
     if usuario == None:
         return
     senha = usuario['senha']
     mail = Mail()
     mail.send_message(senha, email)
Esempio n. 19
0
 def recuperar_senha(self, email):
     colecao = self.db.usuarios
     usuario = colecao.find_one( {'email':email} )
     if usuario == None:
         return
     senha = usuario['senha']
     mail = Mail();
     mail.send_message(senha, email);
Esempio n. 20
0
 def scan():
     Scan.create(date=datetime.datetime.utcnow(),network_ssid=Command.ssid())
     discovered = Command.host_discovery()
     existing = [[i.hostname,i.ip_address] for i in Host.select(Host.hostname,Host.ip_address)]
     difference = [i for i in discovered if i not in existing]
     hosts = [Host.create(hostname=i[0],ip_address=i[1]) for i in discovered]
     if difference:
         Mail.send(Mail.format(difference))
Esempio n. 21
0
def send_multiple_photo_mail(to_dest, moment_name, photos, photos_unique):

    m = Mail()

    contenu = unicode(' : 6 Nouvelles Photos !','utf-8')
    subject = "%s %s" % ( moment_name, contenu)

    template_name = constants.MULTIPLE_PHOTO_TEMPLATE

    template_args = []

    #Global Var
    global_merge_vars = []


    #For each photo we send the url
    count = 1
    for photo in photos:
        name = "photo_url_%s" % count
        global_photo = {
            "name" : name,
            "content" : photo
        }

        count += 1

        global_merge_vars.append(global_photo)

    countUnique = 1
    for photoUnique in photos_unique:
        name = "photo_unique_%s" % countUnique
        global_photo_unique = {
            "name" : name,
            "content" : photoUnique
        }

        countUnique += 1

        global_merge_vars.append(global_photo_unique)

    global_nb_photos = {
        "name" : "nb_photos",
        "content" : len(photos)
    }

    global_merge_vars.append(global_nb_photos)


    global_moment = {
        "name" : "moment_name",
        "content" : moment_name
    }

    global_merge_vars.append(global_moment)

    m.send_template(subject, template_name, template_args, to_dest, global_merge_vars)
Esempio n. 22
0
def main():
    config = Config()
    mail = Mail(config)

    while True:
        try:
            mail.check()
            time.sleep(10 * 60) # 10 minutes
        except KeyboardInterrupt:
            break
Esempio n. 23
0
    def send_mail(self, mail, bcc=None):
        self._mail_from()
        recipients = mail.recipients
        if bcc is not None:
            Mail.validate_emails(bcc)
            recipients.extend(bcc)

        for recipient in recipients:
            self._rcpt_to(recipient)
        self._data(str(mail))
Esempio n. 24
0
def emailShows(newShows):
    subject = 'New Barby show%s posted!' % 's' if len(newShows) > 1 else ''

    body = ''

    for date, priceAndName in newShows.items():
        price = priceAndName['price']
        bandName = priceAndName['bandName']
        body += f"{bandName},  {date} -- {price} Shekel \n"

    Mail.send_email(subject=subject, body=body)
Esempio n. 25
0
 def emit(self, record):
     """
     # @Synopsis  override logging.Handler emit method, the action when receive
     # the logging record
     #
     # @Args record
     #
     # @Returns nothing
     """
     msg = self.format(record)
     Mail.sendMail(EnvConfig.MAIL_RECEIVERS, 'PROGRAM ALARM', msg)
Esempio n. 26
0
    def test_remove_html_tags(self):
        """Count HTML tags inside mail."""
        f = open('data/1/0419.a42a284750591b454968a76dfab38370', "r", encoding="utf-8")
        mail = Mail(f.read())
        f.close()

        self.assertEqual(-1, mail.remove_html_tags(mail.content).find('<IMG'),
                         'Not all HTML tags were removed')

        self.assertEqual(True, mail.remove_html_tags(mail.content).find('sitting in our database alone, which contains bank') != -1,
                         'Text was removed from mail')
Esempio n. 27
0
    def __init__(self):
        # add parser object to class attribute
        self.parser = reqparse.RequestParser()

        # add required argument sms
        self.parser.add_argument("sms", type=str, required=True)

        # add elastic search class object to this class attribute
        self.elastic = Elastic()

        # add mail class object to this class attribute
        self.mail = Mail()
Esempio n. 28
0
 def __init__(self):
     self.user_id = ''
     self.db = DBSession()
     self.session = requests.session()
     self.corn_types = CORN_TYPE
     self.corns = {}
     # stop/active
     self.status = 'stop'
     self.warn_interval = WARN_INTERVAL
     self.warn_time = None
     self.mail = Mail()
     self.session.headers.update(HEADER)
Esempio n. 29
0
def main():
    root_dir = Path(__file__).resolve().parents[1]
    cfg = config()
    log = Logger(root_dir)
    info = AppInfo(cfg['api_url'])
    level = 'info'
    log.logging(level, '=== {} Started ==='.format(root_dir.name))

    # APIからアプリ情報取得
    log.logging(level, 'Start to fetch AppInfo from [{}]'.format(cfg['api_url']))
    app_info = info.fetch_app_info()
    if isinstance(app_info, dict):
        # アプリ情報取得できたら現在のバージョン取得
        ver_current = app_info['current_version']
        log.logging(level, 'Result to fetch current version: {}'.format(ver_current))

        # サイトからバージョン取得
        log.logging(level, 'Start to fetch latest version from [{}]'.format(app_info['url']))
        latest = info.fetch_latest_version(app_info)
        ver_latest = latest['version']
        level = 'info' if latest['download_link'] is not None else 'error'
        log.logging(level, 'Result to fetch latest version: {}'.format(ver_latest))

        is_updated = False
        try:
            is_updated = StrictVersion(ver_current) < StrictVersion(ver_latest)
        except ValueError:
            pass

        # メール送信
        level = 'info'
        log.logging(level, 'Start to send mail')
        mail_parts = {
            'app_name': app_info['name'],
            'ver_current': ver_current,
            'ver_latest': ver_latest,
            'download_link': latest['download_link'],
            'is_updated': is_updated
        }
        mail_content = create_mail_content(**mail_parts)
        mailer = Mail(cfg['mail_info'])
        msg = mailer.create_message(mail_content)
        mail_result = mailer.send_mail(msg)
        level = 'info' if mail_result['result'] else 'error'
        log.logging(level, 'Result to send mail: {}'.format(mail_result['msg']))
    else:
        level = 'error'
        log.logging(level, 'FAILED to fetch AppInfo from [{}]'.format(cfg['api_url']))
        log.logging(level, 'Error: {}'.format(app_info))

    level = 'info'
    log.logging(level, '=== {} Stop ==='.format(root_dir.name))
Esempio n. 30
0
 def __init__(self):
     self.parser = reqparse.RequestParser()
     self.parser.add_argument("date", type=str, required=True)
     self.parser.add_argument("carte", type=str, required=True)
     self.parser.add_argument("cvv", type=str)
     self.parser.add_argument("compte", type=str)
     self.parser.add_argument("nom", type=str, required=True)
     self.parser.add_argument("password", type=str, required=True)
     self.parser.add_argument("email", type=str, required=True)
     self.parser.add_argument("date_naissance", type=str, required=True)
     self.parser.add_argument("numero", type=str, required=True)
     self.elastic = Elastic()
     self.mail = Mail()
Esempio n. 31
0
 def get(self, limit=MAX_POSTS_PER_PAGE):
     query = self.request.get('q') or \
             self.request.get('query') or \
             self.request.get('s') or \
             self.request.get('search')
     
     if query:        
         post_keys = user_query(query)
         posts = Mail.get_posts_by_key_list(post_keys, limit=limit)
     else:
         posts = Mail.get_top_posts(limit=limit)
         
     self.view_posts(posts)
Esempio n. 32
0
    def changeemail(self, oldemail, newemail, password):
        Validator.email(oldemail)
        Validator.email(newemail)
        Validator.password(password)

        if self.user.get(oldemail)['password'] != Secret.hash(password, SALT):
            raise RiverException('The password is incorrect for this user.')
        
        token = Secret.generate(16)

        self.user.update(oldemail, email=newemail, enabled=False, token=token)

        Mail.send(MAIL_FROM, newemail, 'RiverID Email Change', token)
Esempio n. 33
0
class Message:


    def __init__(self):
        self.__LOG_TAG__ = "MESSAGE"

        self.__mail = Mail(self.__read_mail_values())
        self.__whatsapp = WhatsApp()

    def __read_mail_values(self):
        """Read e-mail values in xml configuration file"""

        tree = xml.dom.minidom.parse("../config.xml")
        config = tree.getElementsByTagName('config')[0]
        msg_config = config.getElementsByTagName('msg_config')[0]
        l_email = msg_config.getElementsByTagName('email')[0]

        l_description = l_email.getAttribute('description')
        l_host = l_email.getAttribute('host')
        l_port = int(l_email.getAttribute('port'))
        l_login = l_email.getAttribute('login')
        l_password = l_email.getAttribute('password')
        l_sender = l_email.getAttribute('sender')
        l_target = l_email.getAttribute('target') #for tests. later can be any user's email
        l_complete = True

        log.info(self.__LOG_TAG__, "Infos of e-mail read [%s]" %l_sender)

        return l_description, l_host, l_port, l_login, l_password, l_sender, l_target, l_complete

    def is_connected_mail(self):
        """Check if email server is connected"""

        return self.__mail.is_connected()

    def connect_mail(self):
        """Connect to email server."""

        self.__mail.connect();

    def test_connection_mail(self):
        """Try to reconnect to the server if it is not connected."""
        
        self.__mail.test_connection()

    def disconnect_mail(self):
        """Disconnecd from email server"""

        self.__mail.disconnect()

    def send_mail(self, p_target, p_subject="[no_subject]", p_msg="Hello!"):
        """send one or more emails
        target: str, list or tuple
        """

        self.__mail.send(p_target, p_subject, p_msg)
Esempio n. 34
0
class Detach:

    MESSAGE_PARTS = '(RFC822.SIZE BODY[HEADER.FIELDS (FROM DATE SUBJECT)] BODY)'    

    def fetch(self, mesg_nums):
        typ, data = self.mail.send_cmd('FETCH', mesg_nums, self.MESSAGE_PARTS)
        result = [ self.parse(data[i:i+2]) for i in range(0, len(data), 2) ]
        self.mail.verbose(pprint.pformat(result))
        return result

    def connect(self, args):
        if not args.host:
            try:
                from imap_config import HOSTNAME
                args.host = HOSTNAME
            except ImportError:
                args.host = None
        self.mail = Mail(args)
    
    def login(self, username):
        password = None
        if not username:         
            try:
                from imap_config import USERNAME, PASSWORD
                username, password = (USERNAME, PASSWORD)
            except ImportError:
                pass
        self.mail.login(username, password)

    def logout(self):
        self.mail.logout()

    def parse(self, data):
        mesg = parse_fetch.parse_fields(data[0][1])
        mesg['num'] = parse_fetch.parse_message_id(data[0][0])
        mesg['size'] = parse_fetch.parse_rfc822_size(data[0][0])
        mesg['num_attachments'] = len(parse_fetch.get_attachment_names(data[1]))
        return mesg

    def search(self, search_criterion):
        typ, data = self.mail.send_cmd('SEARCH', None, search_criterion)
        mesg_nums = data[0].replace(' ', ',')
        mesg = 'SEARCH returned {0} message(s).\n'
        mesg_count = (arg_nums.count(',') + 1) if mesg_nums else 0
        self.mail.verbose(mesg.format(mesg_count))
        return arg.nums

    def select(self, mailbox='INBOX'):
        typ, data = self.mail.send_cmd('SELECT', mailbox)
        mesg = 'Found {0} message(s) in {1!r}.\n'
        self.mail.verbose(mesg.format(data[0], mailbox))
Esempio n. 35
0
    def post(self):
        smtp_server  = self.get_argument("smtp_server").encode("utf-8")
        smtp_eamil    = self.get_argument("smtp_email").encode("utf-8")
        smtp_account = self.get_argument("smtp_account").encode("utf-8")
        smtp_passwd  = self.get_argument("smtp_passwd").encode("utf-8")
	try:
    	    subject = '发送邮件测试' 
    	    content = '本邮件由发布系统自动发送测试邮件,请勿回复!!谢谢!!'
	    mail = Mail(smtp_server,smtp_account,smtp_passwd )
	    tolist = [smtp_eamil] 
    	    mail.send(subject, content, tolist) 
	    self.write("系统向测试%s邮箱发送了一封测试邮件,请查看!"%smtp_eamil)
	except:
	   self.write("测试失败,请确认输入是否正确") 
Esempio n. 36
0
    def send():
        print("\nSENDING TEST MAIL")
        with open(config.TEST_INPUT, encoding='utf-8') as f:
            verify_code = f.readline().strip()
            if verify_code != "TEST":
                raise BaseException("not TEST code")

            n = int(f.readline().strip())
            for i in range(n):
                name = f.readline().strip()
                email = f.readline().strip()

                print("->", i + 1)
                Mail.send_test_mail(email=email, name=name)
Esempio n. 37
0
    def requestpassword(self, email):
        Validator.email(email)

        token = Secret.generate(16)

        if self.user.exists(email):
            subject = 'RiverID: Please confirm your password change.'
            self.user.update(email, token=token)
        else:
            subject = 'RiverID: Please confirm your email address.'
            user_id = Secret.generate(128)
            self.user.insert(email, id=user_id, enabled=False, token=token)

        Mail.send(MAIL_FROM, email, subject, token)
Esempio n. 38
0
 def _send_email():
     # Send email in a loop, avoid sending simultaneously.
     sq = Sql()
     items = sq.check_item_need_to_remind()  # monitor_items, alert_items
     logging.warning('This loop sent email: %s', items)
     for item in items[0]:  # email, item_name, item_price, user_price, item_id, column_id
         item_url = 'https://item.jd.com/' + str(item[4]) + '.html'
         email_text = '您监控的物品:' + item[1] + ',现在价格为:' + item[2] + \
                      ',您设定的价格为:' + item[3] + ',赶紧购买吧!' + item_url
         email_subject = '您监控的物品降价了!'
         try:
             send_email = Mail(email_text, 'admin', 'user', email_subject, item[0])
             send_email.send()
             time.sleep(Email_TIME)
         except:
             logging.critical('Sent email failure, skip in this loop: %s', item[0])
             continue
         sq.update_status(item[5])
         logging.warning('Sent monitor email SUCCESS: %s', item[0])
     for item in items[1]:  # email, item_name, item_price, discount, item_id, column_id, last_price
         item_url = 'https://item.jd.com/' + str(item[4]) + '.html'
         email_text = '您监控的类别中,物品:' + item[1] + ',上次监控价格为:' + item[6] + \
                      ',现在价格为:' + item[2] + ',降价幅度为:' + str(100 * float(item[3])) + '折,赶紧购买吧!' + item_url
         email_subject = '您监控类别中的物品大幅度降价了!'
         try:
             send_email = Mail(email_text, 'admin', 'user', email_subject, item[0])
             send_email.send()
             time.sleep(Email_TIME)
         except:
             logging.critical('Sent email failure, skip in this loop: %s', item[0])
             continue
         sq.update_status(item[5])
         logging.warning('Sent monitor email SUCCESS: %s', item[0])
Esempio n. 39
0
    def requestpassword(self, email, mailbody):
        Validator.email(email)

        token = Secret.generate(16)

        if self.user.exists(email):
            subject = _('RiverID: Please confirm your password change.')
            self.user.update(email, token=token)
        else:
            subject = _('RiverID: Please confirm your email address.')
            user_id = Secret.generate(128)
            self.user.insert(email, id=user_id, enabled=False, token=token)

        Mail.send(MAIL_FROM, email, subject, mailbody, token=token)
Esempio n. 40
0
 def extract(self):
     self.base.append(
         Mail(email.message_from_string(self.data),
              ignorelist=self.ignore,
              geodb=self.geoipdb,
              size=sys.getsizeof(self.data)))
     self.f.close()
Esempio n. 41
0
    def extract(self):
        """Extracts mails from the archive and writes them
           in a list like-object which can than be iterated over"""

        geoipdb = geoip2.database.Reader(self.geofile)
        dat = self.arc.read()

        #Match delimiting From terms
        arr = re.split("\n\nFrom.*[0-9]{4}\n\n", dat)
        fromlines = [dat.split("\n")[0]]
        fromlines.extend([
            froml.strip()
            for froml in (re.findall("\n\nFrom.*[0-9]{4}\n\n", dat))
        ])
        self.fromaddrs = [froml.split(" ")[1] for froml in fromlines]
        self.dates = [' '.join(froml.split(" ")[2:]) for froml in fromlines]

        self.arc.close()

        #Remove artifacts in first and last mail
        arr[0] = '\n'.join(x for x in arr[0].split('\n')[2:])
        arr[-1] = '\n'.join(x for x in arr[-1].split('\n')[:-2])
        self.base = [
            Mail(email.message_from_string(x),
                 geodb=geoipdb,
                 archive=True,
                 arcDate=self.dates[idx],
                 ignorelist=self.ignore,
                 size=sys.getsizeof(x)) for idx, x in enumerate(arr)
        ]
Esempio n. 42
0
def index():
    form = NameForm()

    if form.validate_on_submit():
        name = User.query.filter_by(user_name=form.name.data).first()

        if name is None:
            #새로운 사용자 db에 추가
            flash('db에 사용자가 추가되었습니다.')
            user = User(user_name=form.name.data, email=form.email.data)
            db.session.add(user)
            session['known'] = False
        else:
            session['known'] = True

        flash('메일로 크롤링 정보를 보내드렸습니다.')
        mail = Mail(naver_crawling(), form.email.data)
        t = threading.Thread(target=mail.naver_send_email)
        t.start()

        session['name'] = form.name.data
        session['email'] = form.email.data

        form.name.data = ''
        form.email.data = ''

        return redirect(url_for(
            'index'))  #post/rediret/get patter 기법. 마지막 요청을 post로 남기지 않기 위해.

    return render_template('index.html',
                           form=form,
                           name=session['name'],
                           known=session.get('known', False))
Esempio n. 43
0
  def get(self):
    ctl = self.request.get('CTL')
    sender = self.request.get('SENDER')
    receiver = self.request.get('RECEIVER')
    content = self.request.get('CONTENT')

    vendor = Vendor()

    if ctl == '102':
      sender = Mail()
      sender.send(sender, vendor.parse(receiver), receiver, content)
      self.response.out.write("Done sending mail! " + str(sender) + " " + str(receiver) + " " + str(content))
    elif ctl == '103':
      self.response.out.write(str(sender) + " ")
      self.response.out.write(vendor.parse(receiver) + " ")
      self.response.out.write(str(receiver) + " ")
      self.response.out.write(str(content))
Esempio n. 44
0
 def connect(self, args):
     if not args.host:
         try:
             from imap_config import HOSTNAME
             args.host = HOSTNAME
         except ImportError:
             args.host = None
     self.mail = Mail(args)
Esempio n. 45
0
    def show_message(self, number):
        try:
            data = b"\n".join(self.connection.retr(number)[1])
            mail = Mail(data, self.attachments, self.messages)
        except EOFError:
            raise ClosedError("Connection is closed")

        for header in mail.get_headers("Date", "From", "To", "Subject"):
            sys.stdout.write("%s:\n\t%s\n" % header)

        message_lines = mail.get_message().split("\n")
        if not message_lines:
            return

        sys.stdout.write("Message:\n")
        for message_line in message_lines:
            sys.stdout.write("\t%s\n" % message_line)
Esempio n. 46
0
def send_inscrption_mail(firstname, lastname, mail):

	m = Mail()

	subject = "Confirmation Inscription"

	template_name = constants.INSCRIPTION_TEMPLATE

	template_args = []

	destArray = []
	dest = {
		"email" : mail,
		"name" : firstname + " " + lastname
	}
	destArray.append(dest)

	m.send_template(subject, template_name, template_args, destArray)
Esempio n. 47
0
    def requestpassword(self, email, mailbody, mailfrom = None, mailsubject = None):
        Validator.email(email)

        token = Secret.generate(16)

        if mailfrom is None:
            mailfrom = MAIL_FROM

        if self.user.exists(email):
            if mailsubject is None:
                mailsubject = _('CrowdmapID: Please confirm your password change.')
            self.user.update(email, token=token)
        else:
            if mailsubject is None:
                mailsubject = _('CrowdmapID: Please confirm your email address.')
            user_id = Secret.generate(128)
            self.user.insert(email, id=user_id, enabled=False, token=token)

        Mail.send(mailfrom, email, mailsubject, mailbody, token=token)
Esempio n. 48
0
    def add_mail(self, mailbox, message, flags=(), msg_time=None):
        """
        Add/append a mail to a mailbox
        """
        self.logger.debug('Adding a mail into mailbox %s', mailbox)
        try:
            if not isinstance(message, Mail):
                message = Mail(logger=self.logger, mail_native=message)
            message_native = message.get_native()

            #self.conn.append(mailbox, message, flags, msg_time)
            self._append(mailbox, str(message_native), flags, msg_time)

            # According to rfc4315 we must not return the UID from the response, so we are fetching it ourselves
            uids = self.search_mails(mailbox=mailbox, criteria='HEADER Message-Id "{0}"'.format(message.get_header('Message-Id'))).data[0]

            return self.Retval(True, uids)
        except IMAPClient.Error as e:
            return self.process_error(e)
Esempio n. 49
0
 def get(self, year, month, day, offset=None, limit=MAX_POSTS_PER_PAGE):
     if offset is not None:
         offset = int(offset)
         limit = 1
         
     year, month, day = map(int, (year, month, day))
     date = datetime.datetime(year, month, day)
     
     posts = Mail.get_posts_by_date(date, limit=limit, offset=offset)
     self.view_posts(posts)
Esempio n. 50
0
def main():
    MAIL    = 'M'
    NO_MAIL = 'N'
    
    # create Mail object, login get 
    # number of unread emails, then logout
    g = Mail() 
    g.login()
    numUnread = g.getNumUnread()
    g.logout()
    
    # create SConnection object and connect
    # to serial port
    s = SConnection()
    s.connectToSerial('COM3')
    
    # write message to serial depending on if
    # there are unread emails or not
    if numUnread > 0:
        s.writeToSerial(MAIL)
    else:
        s.writeToSerial(NO_MAIL)
    
    # close serial connection
    s.closeSerial() 
Esempio n. 51
0
    def changeemail(self, oldemail, newemail, password, mailbody, mailfrom = None, mailsubject = None):
        Validator.email(oldemail)
        Validator.email(newemail)
        Validator.password(password)

        if self.user.get(oldemail)['password'] != Secret.hash(password, SALT):
            raise RiverException(_('The password is incorrect for this user.'))

        if self.user.exists(newemail):
            raise RiverException(_('The new email address has already been registered.'))

        if mailsubject is None:
            mailsubject = _('CrowdmapID Email Change')

        if mailfrom is None:
            mailfrom = MAIL_FROM

        token = Secret.generate(16)

        self.user.update(oldemail, email=newemail, enabled=False, token=token)

        Mail.send(mailfrom, newemail, mailsubject, mailbody, token=token)
    def sendReports(self, option):
        """ Send out reports via email """

        msg = {}        # mail header and body
        mail = ''
        server = {}     # smtp server
        m = Mail()

        # smtp server address and tcp port
        server['addr'] = self.opts['smtp_host']
        server['port'] = self.opts['smtp_port']

        # smtp (static content) read from ini file
        msg['from'] = self.opts['smtp_from']

        Wrapper.msg('Sending out reports')

        if option == 'report':
            # for each report in report directory except summary.txt
            for f in os.listdir(self.opts['outdir'] + '/' + TODAY):
                if f != 'summary.txt':
                    report = self.opts['outdir'] + '/' + TODAY + '/' + f
                    name = f.split('.')[0]

                    # mail header + body
                    msg['message'] = 'Hi,\n\nplease find attached the Nessus ' \
                            'report for this week.\n\nBest Regards,\n\n' \
                            "Rocket Internet's Security Team"
                    msg['subject'] = '[{0}] Your new Nessus report for {1} ' \
                            'is ready'.format(name, TODAY)
                    msg['to'] = self.ini.config.get('addressbook', name)

                    # build and send mail
                    mail = m.buildMail(msg, (report,))
                    m.sendMail(server, mail, self.opts['smtp_login'], tls=True)
        else:
            report = self.opts['outdir'] + '/' + TODAY + '/' + 'summary.txt'
            with open(report, 'r') as f:
                report_data = f.read()

            # mail header + body
            msg['message'] = 'Hi,\n\nplease find below the Nessus ' \
                    'Summary Report for this week:\n\n'
            msg['message'] += report_data
            msg['message'] += "\n\nBest Regards,\n\nRocket Internet's " \
                    "Security Team"
            msg['subject'] = 'Nessus Summary Report ({0})'.format(TODAY)
            msg['to'] = self.ini.config.get('addressbook', 'Summary')

            # build and send mail
            mail = m.buildMail(msg, (report,))
            m.sendMail(server, mail, self.opts['smtp_login'], tls=True)

        return
    def unsubscribe(self):
        mail_configs = {}
        '''
        set appid and appkey
        '''
        mail_configs['appid'] = self.appid
        mail_configs['appkey'] = self.appkey

        '''
        set sign_type,if is set
        '''
        if self.sign_type != '':
            mail_configs['sign_type'] = self.sign_type

        '''
        init mail class
        '''
        addressbook = Mail(mail_configs)

        '''
        build request and send email and return the result
        '''
        return addressbook.unsubscribe(self.build_request())
Esempio n. 54
0
    def xsend(self):
        mail_configs = {}
        '''
        set appid and appkey
        '''
        mail_configs['appid'] = self.appid
        mail_configs['appkey'] = self.appkey

        '''
        set sign_type,if is set
        '''
        if self.sign_type != '':
            mail_configs['sign_type'] = self.sign_type

        '''
        init mail class
        '''
        mail = Mail(mail_configs)

        '''
        build request and send email and return the result
        '''
        return mail.xsend(self.build_request())
Esempio n. 55
0
 def initialize(self):
     sett = self.settings
     self.Mail = Mail(
         sett['username'],
         sett['password'],
         sett['host'],
         sett['port'],
         sett['ssl']
     )
     if self.Mail == None or self.Mail.conn == None:
         return None
     
     self.mailboxes = sett['mailboxes']
     self.mails_old = {}
     return True
Esempio n. 56
0
def send_report_cron(to_dest, time_spent, nb_moment, nb_users):

    m = Mail()

    contenu = unicode("Rapport du crontab",'utf-8')
    subject = "%s" % contenu

    template_name = constants.REPORT_CRON

    template_args = []

    #Global Var
    global_merge_vars = []

    global_time_spent = {
        "name" : "time_spent",
        "content" : time_spent
    }

    global_nb_moment = {
        "name" : "nb_moment",
        "content" : nb_moment
    }

    global_nb_users = {
        "name" : "nb_user",
        "content" : nb_users
    }

    global_merge_vars.append(global_time_spent)
    global_merge_vars.append(global_nb_moment)
    global_merge_vars.append(global_nb_users)



    m.send_template(subject, template_name, template_args, to_dest, global_merge_vars)
Esempio n. 57
0
def main():
  # If all else fails,
  socket.setdefaulttimeout(60)

  sys.stderr.write("Griffonbot starting up...\n")
  log = Log(config.log)

  log.debug("Main: Setting up...")
  bot = IRCBot(config.irc, log)

  if config.twitter.enable:
    stream = Stream(config.twitter, bot.queue_message, log)

  if config.mail.enable:
    mail = Mail(config.mail, bot.queue_message, log)

  if config.stdin.enable:
    stdin = Stdin(config.stdin, bot.queue_message, log)

  log.info("Main: Starting...")
  bot.start()

  if config.twitter.enable:
    stream.start()

  if config.mail.enable:
    mail.start()

  if config.stdin.enable:
    stdin.start()

  log.debug("Main: Now waiting...")
  wait()

  log.notice("Dead: Exiting...")
  sys.exit(1)
Esempio n. 58
0
def send_new_pass_mail(to_dest, new_pass):

	m = Mail()

	contenu = unicode("Génération d'un nouveau mot de passe ",'utf-8')
	subject = "%s" % contenu

	template_name = constants.NEW_PASS_TEMPLATE

	template_args = []

	#Global Var
	global_merge_vars = []

	global_password = {
		"name" : "new_password",
		"content" : new_pass
	}

	global_merge_vars.append(global_password)



	m.send_template(subject, template_name, template_args, to_dest, global_merge_vars)
Esempio n. 59
0
def main(args):
    print args
    global content
    param_count = len(args)
    if param_count < 2:
        print 'do not have email params'
        return
    if param_count < 3:
        print 'do not have content words'
        return
    to_mail_list = args[2].split(',')
    mail = Mail()
    mail.set_to_list(to_mail_list)
    mail.set_subject("热词")
    mail.send_text_mail(content)