Beispiel #1
0
def user_new(email):
    # create user and get the initial password in plaintext.
    email = _unicode_fix(email)

    user, password = get_user_database().new_user_from_email(email)

    transaction_commit(None, 'NewUser') # moved from user.ptl/NewUserForm.commit()

    # send email
    e = url_quote(email)
    p = url_quote(password)
    s = url_quote("Sign in")
    
    message = _(_new_user_message) % dict(email=email,
        password=password,                             
        auto_login_url=messages.login_url + "?email=" + e + "&password="******"&submit-login="******"&from_url=Y")

    extra_headers = ['Content-Type: text/html'] # because of the href
    sendmail("Welcome to ned.com", message, [email], extra_headers=extra_headers)

    # send pm using _live_tmpl_pm_new_user in sitedev as the template
    template_text = qon.util.get_page_template('pm_new_user', format='text')
    if template_text:
        message_anon_send(user, "Welcome to ned.com!", template_text, True)

    # add orientation page to all new users' watch lists
    try:
        orientation = get_group_database()['help'].get_wiki().pages['start_here']
        user.get_watch_list().watch_item(orientation)
    except:
        pass        

    qon.search.searchengine.notify_new_user(user)
    return (email, message)
Beispiel #2
0
def group_invite_user(user, group, email, inviter):
    """Invite email to join group. May raise smtplib.SMTPRecipientsRefused if server
    rejects email.
    """
    if not group.is_accepted() or not group.get_members().can_manage(user):
        raise AccessError

    group.add_invitation(email, inviter)

    transaction_commit(inviter, 'InviteToGroup')    # moved from group/form.ptl/InviteForm.commit()
    
    try:
        user = get_user_database().get_user_by_email(email)
    except KeyError:
        # e-mail address is not registered, send an e-mail (rather than internal message)
        subject=_(_email_invite_subject) % dict(group_name=group.name)
        body=_(_email_invite_body) % dict(email=email,
            home_url=messages.home_url,
            inviter=qon.ui.blocks.user.display_name_plain(inviter),
            group_name=qon.ui.blocks.group.display_name_plain(group))
            
        sendmail(subject, body, [email])
    else:
        message_send(inviter, user,
            subject=_(_message_invite_subject) % dict(group_name=group.name),
            body=_(_message_invite_body) % dict(
                email=email,
                inviter=qon.ui.blocks.user.display_name_plain(inviter),
                group_name=qon.ui.blocks.group.display_name_plain(group)
                )
            )
def fetch_yesterday():
    """下载昨日的数据"""
    jobs = [gevent.spawn(fetch, year, month, day, n)
            for n in range(24)]
    gevent.joinall(jobs)
    if not util.detect(data_dir, year, month, day):
        util.sendmail('Download Error', '\n'.join(os.listdir(data_dir)) + '\nFound In Target Dir.')
Beispiel #4
0
def misc_email_page(from_email, to_email, user, subject, personal_message, obj):
    """Email page to a person. May raise smtplib.SMTPRecipientsRefused if server
    rejects email.
    """
    subject = _unicode_fix(subject)
    personal_message = _unicode_fix(personal_message)
    
    if not personal_message:
        personal_message = ''
    else:
        personal_message = "\nPersonal message:\n" + personal_message + '\n'

    # show title in message body only for non-internal groups
    title = ''
    if not qon.ui.blocks.util.is_internal_item(obj):
        title = qon.ui.blocks.util.formatted_display_name_plain(obj)

    url = "http://www.ned.com" + qon.ui.blocks.util.path_to_obj(obj)

    body=_(_email_page_body) % dict(email=to_email,
        sender=qon.ui.blocks.user.display_name_plain(user),
        title = title,
        url = url,
        personal_message = personal_message,
        home_url = messages.home_url)

    sendmail(subject, body, [to_email], from_addr=from_email)        
Beispiel #5
0
def message_email_copy_self(fr, to, message):
    """Email a notice to the recipient's primary e-mail address."""
    if type(to) is not list:
        to_name = to.display_name()
    else:
        if len(to) == 1:
            to_name = to[0].display_name()
        else:
            to_name = "all %i users in the group" % len(to)

    body = _notify_new_message_copy_self % dict(
        uid=fr.get_user_id(),
        recipient=to_name,
        sender=qon.ui.blocks.util.display_name_plain(message.sender),
        subject=message.subject,
        date=qon.ui.blocks.util.format_datetime(message.date),
        text=message.body,
        )
    
    #subject = _('Copy of message to %s') % to_name
    #subject = _('%s') % message.subject
    subject = _('PM: to %s: %s') % (to_name, message.subject)

    # mark content as utf-8
    extra_headers = ['Content-Type: text/plain; charset=utf-8']
    
    sendmail(subject, body, [fr.get_primary_email()], extra_headers=extra_headers)
Beispiel #6
0
def worker_main(anime, shared):
    try:
        timeline = shared['timeline']
        # pre-processing
        anchor = create_title_link(generate_uri(anime.search_title))
        filtered = filter_tuple(anchor)
        latest_episode = episodes(filtered)[0]
        logstate(anime, filtered, latest_episode)
        if anime.latest_episode == -1 or latest_episode > anime.latest_episode:
            # update latest episode information
            anime.latest_episode = latest_episode

            # remove all occurrence of this animation from timeline then update shared dictionary
            for index in range(len(timeline)-1, -1, -1):
                if timeline[index][0].title == anime.title:
                    timeline.pop(index)
            shared['timeline'] = timeline

            # send an email for subscriber
            with io.StringIO() as strbuf:
                print('Transmission DateTime: %s' % nowstr(), file=strbuf)
                print('Anime: %s' % anime.title, file=strbuf)
                print('Latest episode: %s' % latest_episode, file=strbuf)
                print(filtered, file=strbuf)
                print('', file=strbuf)
                sendmail(settings.recipients, anime, strbuf)

    # may fail when nyaa torrent suffering DDOS
    except Exception:
        with open('{startup}_{filename}'.format(
                startup=now().strftime('%Y%m%d_%H%M%S'), filename='fatal.txt'), 'a') as fatal_log:
            traceback.print_exc(file=fatal_log)
Beispiel #7
0
  def notify(self, notification):
    sender = SENDER
    receiver = '*****@*****.**' % notification['username']    
    subject, content = self.build_notification_body(notification)
    sendmail(sender, receiver, subject, content)

    crns = ','.join(map(lambda x: x['crn'], notification['sections']))
    print 'Sent mail to %s for %s' % (notification['username'], crns)
Beispiel #8
0
    def notify(self, notification):
        sender = SENDER
        receiver = '*****@*****.**' % notification['username']
        subject, content = self.build_notification_body(notification)
        sendmail(sender, receiver, subject, content)

        crns = ','.join(map(lambda x: x['crn'], notification['sections']))
        print 'Sent mail to %s for %s' % (notification['username'], crns)
Beispiel #9
0
def email_msg(msg):
    c = load_config()
    if not c.HasNotifierEmail():
        print("email_build_failed() not ran because not c.HasNotifierEmail()")
        return
    sender, senderpwd = c.GetNotifierEmailAndPwdMustExist()
    subject = "SumatraPDF buildbot failed"
    util.sendmail(sender, senderpwd, ["*****@*****.**"], subject, msg)
def email_msg(msg):
    c = load_config()
    if not c.HasNotifierEmail():
        print("email_build_failed() not ran because not c.HasNotifierEmail()")
        return
    sender, senderpwd = c.GetNotifierEmailAndPwdMustExist()
    subject = "SumatraPDF buildbot failed"
    util.sendmail(sender, senderpwd, ["*****@*****.**"], subject, msg)
Beispiel #11
0
def fetch_yesterday():
    """下载昨日的数据"""
    jobs = [gevent.spawn(fetch, year, month, day, n) for n in range(24)]
    gevent.joinall(jobs)
    if not util.detect(data_dir, year, month, day):
        util.sendmail(
            'Download Error',
            '\n'.join(os.listdir(data_dir)) + '\nFound In Target Dir.')
 def POST(self):
     f = form.email_sent_form()
     if not f.validates():
         return render({'title': settings.SITE_NAME}).share(f, 'failure')
     else:
         for recip in f.d.address.replace(' ', '').split(';'):
             if recip:
                 accept_str = util.accept_code()
                 model.new_code(accept_str)
                 util.sendmail(f.d.address, accept_str)
         return render({'title': settings.SITE_NAME}).share(f, 'success')
 def POST(self):
     f = form.email_sent_form()
     if not f.validates():
         return render({'title': settings.SITE_NAME}).share(f, 'failure')
     else:
         for recip in f.d.address.replace(' ', '').split(';'):
             if recip:
                 accept_str = util.accept_code()
                 model.new_code(accept_str)
                 util.sendmail(f.d.address, accept_str)
         return render({'title': settings.SITE_NAME}).share(f, 'success')
Beispiel #14
0
def opsjob_deal(auth_info, **kwargs):
    if auth_info['code'] == 1:
        return json.dumps(auth_info)
    if auth_info['role'] != '0':
        return json.dumps({'code': 1, 'errmsg': '只有管理员才有此权限'})
    try:
        username = auth_info['username']
        data = request.get_json()['params']
        # data = {'where': {'id': '65'},'data':{'status':'0','id':'65','deal_desc':'info'}}
        where = data.get('where', None)
        data = data.get('data', None)
        if not where or not data:
            return json.dumps({'code': 1, 'errmsg': '必须有where条件和update数据'})
        status = data.get('status', None)
        deal_desc = data.get('deal_desc', None)
        data['deal_persion'] = username
        result = app.config['cursor'].get_one_result(
            'ops_jobs', ['apply_persion', 'apply_type', 'apply_desc'], where)
        if not result:
            return json.dumps({'code': 1, 'errmsg': '需要操作的数据不存在'})

        # 开始处理工单,状态为处理中
        if status and status == '0':
            data['status'] = 1
            app.config['cursor'].execute_update_sql('ops_jobs', data, where)
            util.write_log(result['apply_persion'], '提交的工单正在处理中......')
            return json.dumps({'code': 0, 'result': '工单正在处理中......'})

        # 处理完成工单,状态改为成功或者失败
        elif status and deal_desc:
            data['deal_time'] = time.strftime("%Y-%m-%d %H:%M")
            app.config['cursor'].execute_update_sql('ops_jobs', data, where)
            if result[
                    'apply_type'] == 1 and status == '2':  #DB类型的修改成功操作,需要通知测试组
                util.write_log(username,
                               ' DB类型修改,同时给测试组发送邮件.....................')
                smtp_to = [
                    '*****@*****.**',
                    result['apply_persion'] + '@yuanxin-inc.com'
                ]
            else:
                smtp_to = [result['apply_persion'] + '@yuanxin-inc.com']
            smtp_info = '%s提交的工单已经处理完成' % username + '\n' + data['deal_desc']
            util.sendmail(app.config, smtp_to, '圆心运维工单', smtp_info)
            util.write_log(username, 'finish the ope job')
            return json.dumps({'code': 0, 'result': '工单处理完成!'})
        else:
            return json.dumps({'code': 1, 'errmsg': '传入参数不正确'})

    except:
        logging.getLogger().error('opsjob finish error : %s' %
                                  traceback.format_exc())
        return json.dumps({'code': 1, 'errmsg': '工单处理失败!'})
Beispiel #15
0
def user_new_password(user, email):
    password = user.generate_password()

    transaction_commit(user, 'NewPassword')    # moved from user.ptl/NewPasswordForm.commit() 

    message = _(_new_password_message) % dict(
        email=email,
        password=password,
        )

    sendmail("ned.com New Password", message, [email])
    return (email, message)
Beispiel #16
0
def email_build_failed(ver):
	s3_url_start = "http://kjkpub.s3.amazonaws.com/sumatrapdf/buildbot/"
	c = load_config()
	if not c.HasNotifierEmail():
		return
	sender, senderpwd = c.GetNotifierEmailAndPwdMustExist()
	subject = "SumatraPDF build %s failed" % str(ver)
	checkin_url = "https://code.google.com/p/sumatrapdf/source/detail?r=%s" + str(ver)
	body = "Checkin: %s\n\n" % checkin_url
	build_log_url = s3_url_start + str(ver) + "/rel_build_log.txt"
	body += "Build log: %s\n\n" % build_log_url
	buildbot_index_url = s3_url_start + "index.html"
	body += "Buildbot: %s\n\n" % buildbot_index_url
	util.sendmail(sender, senderpwd, g_email_to, subject, body)
Beispiel #17
0
def email_build_failed(ver):
	s3_url_start = "http://kjkpub.s3.amazonaws.com/sumatrapdf/buildbot/"
	c = load_config()
	if not c.HasNotifierEmail():
		return
	sender, senderpwd = c.GetNotifierEmailAndPwdMustExist()
	subject = "SumatraPDF build %s failed" % str(ver)
	checkin_url = "https://code.google.com/p/sumatrapdf/source/detail?r=%s" + str(ver)
	body = "Checkin: %s\n\n" % checkin_url
	build_log_url = s3_url_start + str(ver) + "/rel_build_log.txt"
	body += "Build log: %s\n\n" % build_log_url
	buildbot_index_url = s3_url_start + "index.html"
	body += "Buildbot: %s\n\n" % buildbot_index_url
	util.sendmail(sender, senderpwd, g_email_to, subject, body)
Beispiel #18
0
def email_tests_failed(ver, err):
    s3_url_start = "http://kjkpub.s3.amazonaws.com/sumatrapdf/buildbot/"
    c = load_config()
    if not c.HasNotifierEmail():
        print("email_tests_failed() not ran because not c.HasNotifierEmail()")
        return
    sender, senderpwd = c.GetNotifierEmailAndPwdMustExist()
    subject = "SumatraPDF tests failed for build %s" % str(ver)
    checkin_url = "https://code.google.com/p/sumatrapdf/source/detail?r=%s" % str(ver)
    body = "Checkin: %s\n\n" % checkin_url
    log_url = s3_url_start + str(ver) + "/tests_error.txt"
    body += "Build log: %s\n\n" % log_url
    buildbot_index_url = s3_url_start + "index.html"
    body += "Buildbot: %s\n\n" % buildbot_index_url
    body += "Error: %s\n\n" % err
    util.sendmail(sender, senderpwd, g_email_to, subject, body)
Beispiel #19
0
def email_tests_failed(ver, err):
    s3_url_start = "http://kjkpub.s3.amazonaws.com/sumatrapdf/buildbot/"
    c = load_config()
    if not c.HasNotifierEmail():
        print("email_tests_failed() not ran because not c.HasNotifierEmail()")
        return
    sender, senderpwd = c.GetNotifierEmailAndPwdMustExist()
    subject = "SumatraPDF tests failed for build %s" % str(ver)
    checkin_url = "https://code.google.com/p/sumatrapdf/source/detail?r=%s" % str(ver)
    body = "Checkin: %s\n\n" % checkin_url
    log_url = s3_url_start + str(ver) + "/tests_error.txt"
    body += "Build log: %s\n\n" % log_url
    buildbot_index_url = s3_url_start + "index.html"
    body += "Buildbot: %s\n\n" % buildbot_index_url
    body += "Error: %s\n\n" % err
    util.sendmail(sender, senderpwd, g_email_to, subject, body)
Beispiel #20
0
def opsjob_create(auth_info, **kwargs):
    if auth_info['code'] == 1:
        return json.dumps(auth_info)
    username = auth_info['username']
    try:
        data = request.get_json()['params']
        data['apply_date'] = time.strftime('%Y-%m-%d %H:%M')
        data['status'], data['apply_persion'] = 0, username
        app.config['cursor'].execute_insert_sql('ops_jobs', data)
        '''sendemail'''
        smtp_to = ['*****@*****.**']
        send_info = '%s提交工单申请,运维同事请及时处理!' % username + '\n' + '工单申请描述\n' + data[
            'apply_desc']
        util.sendmail(app.config, smtp_to, '圆心运维工单申请', send_info)
        util.write_log(username, "create opsjonb  create")
        return json.dumps({'code': 0, 'result': '创建工单成功!'})
    except:
        logging.getLogger().error('opsjob create error: %s' %
                                  traceback.format_exc())
        return json.dumps({'code': 1, 'errmsg': '工单申请失败!'})
Beispiel #21
0
def user_add_email(user, email):
    email = _unicode_fix(email)
    
    code = user.add_unconfirmed_email(email)

    transaction_commit(user, 'AddEmail')    # moved from user.ptl/AddEmailForm.commit() 

    message = _(_confirm_email_message) % dict(email=email,
        base_url=messages.base_url,
        url=qon.ui.blocks.user.path_to_user(user)[1:] + 'private/confirm', code=code)

    sendmail("ned.com Confirm New Email", message, [email])
    
    inform = _(_notify_new_email_message) % dict(
        primary=user.get_primary_email(),
        new=email)
    
    sendmail("ned.com Email Added", inform, [user.get_primary_email()])

    qon.search.searchengine.notify_edited_user(user)
    return (email, message)
Beispiel #22
0
def group_purge(group):
    """Purge an unsponsored group."""
    if not group.is_accepted():
        # send a message to group owner that his group is being purged
        
        email = group.owners[0].get_primary_email()
        
        d=dict(group_name=group.display_name(),
            primary=email,
            group_description=group.description,
            )
        
        message = _notify_group_purged % d
        
        import socket
        try:
            sendmail("ned.com Group Not Sponsored", message, [email])
        except socket.error:
            pass
        
        # delete the group
        group_delete(group)
Beispiel #23
0
def message_email(to, message):
    """Email a notice to the recipient's primary e-mail address."""
    
    body = _notify_new_message % dict(
        primary=to.display_name(),
#       url=messages.base_url[:-1] + qon.ui.blocks.message.path_to_message(to, message),
        url=messages.base_url[:-1] + qon.ui.blocks.user.path_to_user(to) + 'msg/',
        settings_url=messages.base_url[:-1] + qon.ui.blocks.user.path_to_user_settings(to),
        sender=qon.ui.blocks.util.display_name_plain(message.sender),
        subject=message.subject,
        date=qon.ui.blocks.util.format_datetime(message.date),
        text=message.body,
        )

    #subject = _('Message from %s') % qon.ui.blocks.util.display_name_plain(message.sender)
    #subject = _('%s') % message.subject
    subject = _('PM: from %s: %s') % (qon.ui.blocks.util.display_name_plain(message.sender), message.subject)

    # mark content as utf-8
    extra_headers = ['Content-Type: text/plain; charset=utf-8']
    
    sendmail(subject, body, [to.get_primary_email()], extra_headers=extra_headers)
Beispiel #24
0
def test14():
    util.sendmail('f**k', 'Test')
Beispiel #25
0
        dep = float(dep)
        mw = float(mw)
        if mw < magmin or mw > magmax:
            continue
        evt_time = datetime.datetime(year,mon,day,hour,min,sec)
        if datemin <= evt_time <= datemax:
            if isph == 1:
                dis = distaz.distaz(stla, stlo, lat, lon).delta
                arr = mod.get_travel_times(source_depth_in_km=dep, distance_in_degree=dis, phase_list=[phase])
                if len(arr) != 0:
                    arr_time = evt_time + datetime.timedelta(seconds=arr[0].time)
                    date = arr_time + datetime.timedelta(seconds=btime)
                    dateend = arr_time + datetime.timedelta(seconds=etime)
            else:
                date = evt_time + datetime.timedelta(seconds=btime)
                dateend = evt_time + datetime.timedelta(seconds=etime)
            event.append([date.strftime('%Y %m %d %H %M %S'), dateend.strftime('%Y %m %d %H %M %S')])
    if event == []:
        print('No events found in the range')

msg = generatemsg(NAME, INST, EMAIL, MEDIA, ALTERNATEMEDIA, LABEL)
for row in event:
    msg += station+' '+network+' '+row[0]+' '+row[1]+' 1 '+chan+' '+loca+'\n'
try:
    sendmail(recipient, msg)
    print("Successful sending the mail of "+network+"."+station+" to IRIS DMC!!!")
    time.sleep(4)
except:
    print('ERROR in sending mail')
    sys.exit(1)
Beispiel #26
0
def test14():
    util.sendmail('f**k', 'Test')
Beispiel #27
0
            print("Wrong format in -e option")
            sys.exit(1)
    nowtime = datemin
    while 1:
        if nowtime >= datemax:
            break
        endtime = nowtime + datetime.timedelta(hours=timeval)
        LABEL = 'IRIS_' + nowtime.strftime('%Y.%m.%d.%H')
        msg = generatemsg(NAME, INST, EMAIL, MEDIA, ALTERNATEMEDIA, LABEL)
        for sta_row in sta:
            msg += sta_row[1] + ' ' + sta_row[0] + ' ' + nowtime.strftime(
                '%Y %m %d %H %M %S') + ' ' + endtime.strftime(
                    '%Y %m %d %H %M %S'
                ) + ' 1 ' + chan + ' ' + sta_row[2] + '\n'
        try:
            sendmail(recipient, msg)
            print("Successful sending the mail from " +
                  nowtime.strftime('%Y.%m.%d.%H') + " to " +
                  endtime.strftime('%Y.%m.%d.%H') + "!!!")
            time.sleep(5)
            nowtime = endtime
        except:
            print("Some error occured in sending mail")
else:
    with open(datetimefile) as f:
        datelst = [
            datetime.datetime.strptime(line.strip(), "%Y.%m.%d")
            for line in f.readlines()
        ]
    for nowtime in datelst:
        endtime = nowtime + datetime.timedelta(hours=timeval)
Beispiel #28
0
ONE_DAY = 24 * 60 * 60

if __name__ == '__main__':
    conf_name = os.path.join(work_dir, 'service.conf')
    config = util.get_config(conf_name)

    now = int(time.time()) / ONE_DAY * ONE_DAY
    expire = time.strftime('%Y-%m-%d', time.localtime(now + 20 * ONE_DAY))

    content = []
    cursor = db.Cursor(config)
    sql = "SELECT type, expire, remark FROM soft_asset WHERE expire < '%s' ORDER BY expire" % expire
    cursor.execute(sql)
    for row in cursor.fetchall():
        t = time.mktime(time.strptime(str(row[1]), '%Y-%m-%d'))
        last_day = (int(t) - now + 8 * 60 * 60) / ONE_DAY
        if last_day >= 0:
            msg = '[%s - %s] 到期时间:%s 剩余%s天' % (row[0].encode('utf-8'),
                                               row[2].encode('utf-8'), row[1],
                                               last_day)
        else:
            msg = '[%s - %s] 到期时间:%s 已过期%s天' % (row[0].encode('utf-8'),
                                                row[2].encode('utf-8'), row[1],
                                                -last_day)
        content.append(msg)

    if content:
        content.append('以上服务快到期了,请及时续费!')
        util.sendmail(config, '*****@*****.**', '服务快到期通知',
                      '\n'.join(content))