Ejemplo n.º 1
0
    def GET(self, id=None):
        #if id is None, email every active user with his balance
        if id is not None:
            users = [get_object_or_404(User, id=id)]
        else:
            users = User.filter(active=True)

        default_tpl = settings.MAIL_DEFAULT_TEMPLATE
        try:
            f = open(settings.MAIL_FILE_TEMPLATE, 'rb')
            tpl = pickle.load(f)
            f.close()
        except (IOError, pickle.PickleError):
            tpl = default_tpl

        userside = web.input(u=0).u != 0 # used to check if the mail is coming from a QR scan
        for u in users:
            utpl = default_tpl
            if u.balance < 0 and not userside:
                utpl = tpl
            
            body = utpl.format(apayer = float2str(-u.balance if u.balance <0 else 0), 
                               solde = float2str(u.balance), 
                               prenom = u.firstname, 
                               nom = u.lastname)

            web.sendmail(settings.MAIL_ADDRESS, u.email, 'Your INGI cafetaria balance', body)

        if userside:
            return render_no_layout.consume('BALANCE', u)

        raise web.seeother('/')
Ejemplo n.º 2
0
 def POST(self, slug):
     entry, p = self.getEntry(slug)
     f = commentForm()
     if f.validates():
         comment = Comment(entry.id, f.username.value, f.email.value, f.url.value, f.comment.value)
         entry.comment_num = entry.comment_num + 1
         entry.view_num = entry.view_num - 1
         web.ctx.orm.add(comment)
         emails = ['*****@*****.**']
         message = u'<p>您在&lt;泥泞的沼泽&gt;上回复的日志 "' + entry.title + u'" 又有新的回复了, 请您去看看.</p><p>' \
             u'<a href="http://davidx.me/entry/' + slug + u'/#comments">点击查看回复</a></p>'
         for c in entry.comments:
             emails.append(c.email)
         for e in set(emails):
             try:
                 web.sendmail('*****@*****.**', e,
                     '您在"泥泞的沼泽"上回复的日志又有新的回复了!'.encode('utf-8'), message,
                     headers={'Content-Type':'text/html;charset=utf-8'})
             except:
                 pass
         raise web.seeother('/entry/%s/' % slug)
     else:
         d['p'] = p
         d['entry'] = entry
         d['f'] = f
         d['usedTime'] = time.time() - d['startTime']
         return render.entry(**d)
Ejemplo n.º 3
0
def send_followup(msgid, response_body):
    from_addr = config.from_address
    to_addr = get_sender_email(msgid)
    if not to_addr: return
    subject = 'FILL IN HERE'
    body = response_body +  'FILL IN HERE'                   
    web.sendmail(from_addr, to_addr, subject, body)
Ejemplo n.º 4
0
 def GET(self):
     web.config.smtp_server = 'smtp.gmail.com'
     web.config.smtp_port = 587
     web.config.smtp_username = '******'
     web.config.smtp_password = '******'
     web.config.smtp_starttls = True
     web.sendmail('*****@*****.**','*****@*****.**','message','message content')
Ejemplo n.º 5
0
    def __helper(self, form):
        salt = hashlib.sha1(urandom(16)).hexdigest()
        print "here"
        #SQL query to INSERT a record into the table FACTRESTTBL.
        cur.execute('''INSERT INTO Users (first_name, last_name, encrypted_password, email, created_at, updated_at, current_sign_in_at, last_sign_in_at, current_sign_in_ip, last_sign_in_ip, privilege)
                        VALUES (%s, %s, %s, %s, NOW(), NOW(), NOW(), NOW(), %s, %s, %s)''',
                        (form.d.first_name, 
                        form.d.last_name, 
                        salt + hashlib.sha1(salt + form.d.password).hexdigest(),
                        form.d.email,
                        web.ctx['ip'],
                        web.ctx['ip'],
                        form.d.privilege))

        # Commit your changes in the database
        db.commit()
        try:
            web.config.smtp_server = 'smtp.gmail.com'
            web.config.smtp_port = 587
            web.config.smtp_username = '******'
            web.config.smtp_password = '******'
            web.config.smtp_starttls = True
            web.sendmail('*****@*****.**', form.d.email, 'Welcome to HMS!', 'Hello, '+form.d.first_name+'! Congratulations you are now apart of the HMS family!')
        except:
            print "Error: unable to send email"
Ejemplo n.º 6
0
 def POST(self):
     data = web.input()
     try:
         web.sendmail(websafe(data.email), m.User.by_id(1).email, "Blog About Page Contact from: %s" % websafe(data.name), websafe(data.message))
         flash("error","Thanks for Contacting me!")
     except Exception,e:
         flash("error","Sorry, there was a problem, message not sent")
Ejemplo n.º 7
0
def send_bao(
    name, total, order_info, timestamp, payment="cash", email_from=localconf.email, email_to=localconf.to_email
):
    message = """%s, you got a new bao order! 

order:

    for: %s
    order: %s

    payment: %s
    total: %s

    placed: %s

you rock!
""" % (
        localconf.name,
        name,
        order_info,
        payment,
        total,
        timestamp,
    )
    subject = "a new bao order! %s wants %s, total: $%s (%s)" % (name, order_info, total, payment)
    web.sendmail(email_from, email_to, subject, message)
Ejemplo n.º 8
0
    def POST(self):
        context = web.ctx.request
        i = web.input()
        email = i.email.strip()
        password = i.password
        if not email:
            web.ctx.msg = u"邮箱地址不能为空"
            raise web.seeother('/auth/reg')
        user = User(email=email, password=hash_password(password))
        web.ctx.orm.add(user)
        #web.ctx.orm.commit()

        u = web.ctx.orm.query(User).filter(User.email==email).first()
        if u:
            active_key = gen_sha1(u.email)
            context['active_key'] = active_key
            context['uid'] = u.id
            user_signup = UserSignup(user=u, active_key=active_key)
            web.ctx.orm.add(user_signup)
            web.ctx.orm.commit()
            #web.ctx.session.login = 1
            web.ctx.session.email = email
            web.sendmail(web.config.smtp_username, email, u'注册邮件',
                         render_mail('templates/auth/activation_email_message.txt', **context))

            raise web.seeother('/auth/succ')
        else:
            raise
Ejemplo n.º 9
0
    def _batch_job_done_callback(self, batch_job_id, result, send_mail=None):
        """ Called when the batch job with id jobid has finished.
            result is a dictionnary, containing:

            - {"retval": 0, "stdout": "...", "stderr": "...", "file": "..."}
                if everything went well.(where file is a tgz file containing the content of the / output folder from the container)
            - {"retval": "...", "stdout": "...", "stderr": "..."}
                if the container crashed (retval is an int != 0)
            - {"retval": -1, "stderr": "the error message"}
                if the container failed to start
        """

        # If there is a tgz file to save, put it in gridfs
        if "file" in result:
            result["file"] = self._gridfs.put(result["file"].read())

        # Save submission to database
        self._database.batch_jobs.update(
            {"_id": batch_job_id},
            {"$set": {"result": result}}
        )

        # Send a mail to user
        if send_mail is not None:
            try:
                web.sendmail(web.config.smtp_sendername, send_mail, "Batch job {} finished".format(batch_job_id),
                             """This is an automated message.

The batch job you launched on INGInious is done. You can see the results on the "batch operation" page of your course
administration.""")
            except Exception as e:
                print "Cannot send mail: " + str(e)
Ejemplo n.º 10
0
 def POST(self):
     form = addform()
     if not form.validates():
         users = model.get_users()
         return render.index(users, form)
     model.new_user(form.d.login,
                    form.d.password,
                    form.d.prefix,
                    form.d.firstname,
                    form.d.lastname,
                    form.d.email,
                    form.d.phone,
                    form.d.addr1,
                    form.d.addr2,
                    form.d.city,
                    form.d.state,
                    form.d.country,
                    form.d.zip,
                    form.d.approved)
     mailfrom = "rhn-newuser-request@localhost"
     mailto = "root@localhost"
     subject = "New User Added"
     message = "The following user has requested access: %s" % (form.d.login) 
     web.sendmail(mailfrom, mailto, subject, message)
     return "Thank you, an email will be sent for Approval."
Ejemplo n.º 11
0
def sendmail_to_signatory(user, pid):
    p = db.select('petition', where='id=$pid', vars=locals())[0]
    p.url = 'http//watchdog.net/c/%s' % (pid) 
    token = auth.get_secret_token(user.email)
    msg = render_plain.signatory_mailer(user, p, token)
    #@@@ shouldn't this web.utf8 stuff taken care by in web.py?
    web.sendmail(web.utf8(config.from_address), web.utf8(user.email), web.utf8(msg.subject.strip()), web.utf8(msg))
Ejemplo n.º 12
0
Archivo: code.py Proyecto: scoot557/ah
 def POST(self):
     data=web.input()
     email=data.get('email', '').lower()
     newpassword = data.get('newpw','')
     oldpassword = data.get('oldpw','')
     print 'Password change attempt...'
     if email:
         if  not emailregex.match(email):
             return "Invalid email."
         print 'non logged in user'
         newpassword=usermodel.resetPassword(email)
         if newpassword:
             body = '<p>Your account recently asked for a password reset.  <p>'
             body+= 'Here is the new password:  %s</p>' % (newpassword)
             body+= '<p>Please click here and login: <a href="http://www.actuallyheard.com/">Log In</a></p></html>'
             web.sendmail('Actually Heard',email,'Password Reset', body, headers=({'Content-Type':'text/html; charset="utf-8";'}))
             return True
         else:
             return "No email registered."
     elif session.userid!='none' and newpassword!='':
         oldpw = hashlib.sha256(oldpassword).hexdigest()
         if usermodel.authUser(session.email, oldpw):
             stat=usermodel.changePassword(session.userid,newpassword)
             if stat:
                 body = '<p>Your account recently changed the password to login.  <p>'
                 body+= '<p>If this was unauthorized, please click <a href="http://www.actuallyheard.com/contactus">here</a> and notify us.</p></html>'
                 web.sendmail('Actually Heard',session.email,'Password Change', body, headers=({'Content-Type':'text/html; charset="utf-8";'}))
                 return True
     return 'Invalid Email';
Ejemplo n.º 13
0
    def __disabled_POST(self):
        i = web.input(_method='post')
        i['type.key'] = '/type/comment'
        i['_comment'] = ''
        path = '/c/'+ str(get_random_string())

        # prevent most common spam
        if 'url' in  i['comment'] and 'link' in i['comment'] and 'http://' in i['comment']:
            return web.seeother(i['article.key'])
        if '<a href' in  i['comment'] and 'http://' in i['comment']:
            return web.seeother(i['article.key'])
        if i['website'] in ['http://www.yahoo.com/', 'http://www.google.com/', 'http://www.bing.com/', "http://www.facebook.com/"]:
            return web.seeother(i['article.key'])            
          
        query = {
            'key': path,
            'type': {'key': "/type/comment"},
            'article': {"key": i["article.key"]},
            'comment': {'type': '/type/text', 'value': i['comment']},
            'author': i['author'],
            'website': i['website'],
            'email': i['email'],
            'permission':  {'key': '/permission/restricted'} 
        }

        web.ctx.site.save(query, comment='new comment')

        c = web.ctx.site.get(path)
        msg = render.comment_email(c, web.ctx.home)
        try:
            web.sendmail(config.from_address, config.comment_recipients, web.utf8(msg.subject).strip(), web.utf8(msg))
        except:
            import traceback
            traceback.print_exc()
        web.seeother(i['article.key']+"#comments")
Ejemplo n.º 14
0
    def POST(self, path):
        if not self.is_scan_user():
            return permission_denied('Permission denied.')

        book = web.ctx.site.get(path)
        i = web.input("scan_status", _comment=None)
        
        q = {
            'key': '/scan_record' + path,
            'scan_status': {
                'connect': 'update',
                'value': i.scan_status
            }
        }
        web.ctx.site.write(q, i._comment)

        def get_email(user):
            try:
                delegate.admin_login()
                return web.utf8(web.ctx.site.get_user_email(user.key).email)
            finally:
                web.ctx.headers = []

        scan_record = get_scan_record(path)
        to = scan_record.sponsor and get_email(scan_record.sponsor)
        cc = getattr(config, 'scan_email_recipients', [])
        if to:
            if i.scan_status == 'SCAN_IN_PROGRESS':
                message = render.scan_inprogress_email(book, scan_record, i._comment)
            else:    
                message = render.scan_book_notfound_email(book, scan_record, i._comment)
            web.sendmail(config.from_address, to, message.subject.strip(), str(message), cc=cc)
        raise web.seeother(web.changequery(query={}))
Ejemplo n.º 15
0
    def POST(self):
        inp = web.input(close_after=False, item_host=None, item_path=None, item_name=None, content=None, item_user=None)

        model.new_comment(session.user.name, inp.item_host, inp.item_path, inp.item_name, inp.content, inp.item_user)

        page_owner = model.get_user(name=inp.item_user)
        if page_owner.mailmode == "all":
            web.sendmail(
                'Comment on This! <*****@*****.**>',
                page_owner.email,
                '[CoT] New comment on '+get_domain(inp.item_host),
                session.user.name+" posted a comment on "+inp.item_host+inp.item_path+"#"+inp.item_name+":"+
                "\n\n"+inp.content+
                "\n\n    -- The Comment on This Team"
            )

        if inp.close_after:
            return render.comment_thanks()
        else:
            raise web.seeother(
                "/comment"+
                "?item_host="+web.urlquote(inp.item_host)+
                "&item_path="+web.urlquote(inp.item_path)+
                "&item_name="+web.urlquote(inp.item_name)
            )
Ejemplo n.º 16
0
    def lost_passwd(self, data):
        error = False
        msg = ""

        # Check input format
        email_re = re.compile(
            r"(^[-!#$%&'*+/=?^_`{}|~0-9A-Z]+(\.[-!#$%&'*+/=?^_`{}|~0-9A-Z]+)*"  # dot-atom
            r'|^"([\001-\010\013\014\016-\037!#-\[\]-\177]|\\[\001-011\013\014\016-\177])*"'  # quoted-string
            r')@(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+[A-Z]{2,6}\.?$', re.IGNORECASE)  # domain
        if email_re.match(data["recovery_email"]) is None:
            error = True
            msg = "Invalid email format."

        if not error:
            reset_hash = hashlib.sha512(str(random.getrandbits(256))).hexdigest()
            user = self.database.users.find_one_and_update({"email": data["recovery_email"]}, {"$set": {"reset": reset_hash}})
            if user is None:
                error = True
                msg = "This email address was not found in database."
            else:
                try:
                    web.sendmail(web.config.smtp_sendername, data["recovery_email"], "INGInious password recovery",
                                 "Dear " + user["realname"] + """,

Someone (probably you) asked to reset your INGInious password. If this was you, please click on the following link :
""" + web.ctx.homedomain + "/register?reset=" + reset_hash)
                    msg = "An email has been sent to you to reset your password."
                except:
                    error = True
                    msg = "Something went wrong while sending you reset email. Please contact the administrator."

        return msg, error
Ejemplo n.º 17
0
 def POST(self):
   web.sendmail(
     web.config.smtp_username, 
     str(Form['E-mail'].value),
     '99Party - Esqueci minha senha',
     'Mensagem'
   )
Ejemplo n.º 18
0
Archivo: app.py Proyecto: LSchanner/gda
        def POST(self):
            auxiliar = POSTParse(web.data())
            Form = ForgottenForm

            S = sessionmaker(bind=DB)()
            LocDB = create_engine(UserDB, echo=False)
            Me = S.query(Student).filter(Student.ra == auxiliar['ra'])

            if Me.count():
                caracters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
                newpass = ''
                for char in xrange(8):
                        newpass += choice(caracters)

                ThisUser = S.query(User).filter(User.student_id == Me.one().id).one()

                web.sendmail('*****@*****.**', str(ThisUser.email), 'Recuperar Senha - GDA', 'Sua nova senha é: '+
                newpass+'\n \n Caso ache necessário, você pode mudar sua senha na página de alteração de dados cadatrais do GDA.')

                stmt = update(User).where(ThisUser.email == User.email).values(password=encode(newpass))
                LocDB.execute(stmt)
                raise web.seeother('/login')

            else:
                return Render.forgottenpassword(Form, "Não existe usuário cadastrado com o RA fornecido!", Render)
Ejemplo n.º 19
0
 def POST(self):
     i = web.input(email='*****@*****.**')
     web.sendmail('Feedback <%s>' % i.email, 'Watchdog <*****@*****.**>',
       'watchdog.net feedback', 
       i.content +'\n\n' + web.ctx.ip)
     
     return render.feedback_thanks()
Ejemplo n.º 20
0
    def POST(self):
        i = web.input()
        f = form_talk()
        
        if not f.validates(i):
            return render_template("talks/submit", form=f)

        key = new_talk(i)
        
        if config.get('from_address') and config.get('talk_submission_contact'):
            email = render_template("talks/email", i)
            web.sendmail(
                from_address=config.from_address, 
                to_address=config.talk_submission_contact,
                subject=web.safestr(email.subject.strip()),
                message=web.safestr(email)
            )

        dir = config.get("talks_dir", "/tmp/talks")
        write("%s/%s.txt" % (dir, time.time()), simplejson.dumps(i))
        
        tweet.tweet("talk_template", title=i.title, author=i.authors, url=web.ctx.home + "/" + key)
        
        add_flash_message("info", "Thanks for submitting your talk. The selection committee will review your talk and get in touch with you shortly.")
        raise web.seeother("/" + key)
Ejemplo n.º 21
0
    def sendMessage(self, subject, content):
        mailSendFrom = 'monitor-py'
        mailSendTo = '*****@*****.**' #['*****@*****.**', '*****@*****.**']

        web.sendmail(mailSendFrom, mailSendTo, subject, content)
        # send sms ...
        return "ok"
Ejemplo n.º 22
0
def fetch_and_update(imap_conn, db_conn = None):
    for resp in get_new_emails(imap_conn):
        try:
            messageid, message = parse_imap_response(resp)
        except Exception,e:
            logger.warning(" Message parsing failed", exc_info = True)
            continue
        m = subject_re.search(message['Subject'])
        if m:
            caseid = m.groups()[0]
            logger.debug(" Updating case %s", caseid)
            try:
                frm = email.utils.parseaddr(message['From'])[1]
                case = db_conn.get_case(caseid)
                casenote = get_casenote(message)
                update_support_db(frm, casenote, case)
                imap_move_to_folder(imap_conn, messageid, "Accepted")
                message = template%dict(caseno = caseid,
                                        message = casenote,
                                        author = frm)
                subject = "Case #%s updated"%(caseid)
                assignee = case.assignee
                web.sendmail("*****@*****.**", assignee, subject, message)
            except Exception, e:
                logger.warning(" Couldn't update case. Resetting message", exc_info = True)
                imap_reset_to_unseen(imap_conn, messageid)
Ejemplo n.º 23
0
def thread_send_mail(email,passwd):
    web.config.smtp_server = 'smtp.gmail.com'
    web.config.smtp_port = 587
    web.config.smtp_username = '******'
    web.config.smtp_password = '******'
    web.config.smtp_starttls = True
    web.sendmail('*****@*****.**', email, 'nomadic修改密码', passwd)
Ejemplo n.º 24
0
	def POST(self):
		form = web.input()
		if form.email != None:
			if len(form.email) > 0:
				# generate api key info
				key = uuid.uuid4()
				key_hash = hashlib.md5(str(key)).digest().encode('utf-8')
				# add info to database
				email = form.email
				name = form.name
				org_name = form['organization name']
				org_url = form['organization url']
				use = form['intended use']
				reschk = db.select('users',where='email=$email OR apikey=$key_hash',vars={'email':email, 'key_hash':key_hash})
				if len(reschk.list()) > 0:
					return self.ERR('This email address is already registered, check your records for your API Key')
				else:
					res = db.insert('users',name=name,email=email,organization_name=org_name,organization_url=org_url,intended_use=use,apikey=key_hash,is_active=0)
					# send email with api key			
					text = """Thank you for registering for a ALEC Exposed API key.

Please visit the following URL to verify your email address and activate your key
%s/register/activate/%s

Your details are included below for your records:
    Email: %s
    API Key: %s
""" %(root_url,key,email,key)
					web.sendmail('*****@*****.**',email,"ALEC Exposed Registration",text)
					return docs().thanks('Thank you for registering, click the link in your email to activate your API Key')
			else:
				return self.ERR('A valid email address is required')
		else:
			return self.ERR('A valid email address is required')
Ejemplo n.º 25
0
	def POST(self):
		my_signup = globs.signup_form()
		if my_signup.validates(): 			
			email = my_signup['username'].value
			password = my_signup['password'].value
			passwordAgain = my_signup['password_again'].value	
			result = handle_user(email, password, "register")
			if (result == False):
				my_signup['username'].note = "username already there!"
				return globs.render.register(my_signup)
			else:
				get_email_hash = globs.db.query("SELECT email_hash FROM users WHERE email=$id", vars={'id':email})[0]
				htmlbody = web.template.frender('webclient/templates/email/email.html')
				#For the server
				
				baselink = "http://www.intra-vires.com/response?id="
				#baselink = "localhost:8080/response?id="
				link = baselink + get_email_hash.email_hash
				web.sendmail('*****@*****.**', email, 'Complete Your Intra Vires Registration', htmlbody(link), headers={'Content-Type':'text/html;charset=utf-8'})
				return globs.render.signupEmailSent(email)
		else:
			email = my_signup['username'].value
			password = my_signup['password'].value
			passwordAgain = my_signup['password_again'].value				
			
			validateResult = ValidateRegister(password,passwordAgain,email)
			my_signup['username'].note = validateResult;
			return globs.render.register(my_signup)
Ejemplo n.º 26
0
    def POST(self):
        if not support_db:
            return "Couldn't initialise connection to support database"
        form = web.input()
        email = form.get("email", "")
        topic = form.get("topic", "")
        description = form.get("question", "")
        url = form.get("url", "")
        user = accounts.get_current_user()
        useragent = web.ctx.env.get("HTTP_USER_AGENT","")
        if not all([email, topic, description]):
            return ""
        c = support_db.create_case(creator_name      = user and user.get_name() or "",
                                   creator_email     = email,
                                   creator_useragent = useragent,
                                   creator_username  = user and user.get_username() or "",
                                   subject           = topic,
                                   description       = description,
                                   url               = url,
                                   assignee          = config.get("support_case_default_address","*****@*****.**"))

        # Send an email to the creator of the case
        subject = "Case #%s: %s"%(c.caseno, topic)
        message = render_template("email/support_case", c)
        web.sendmail(config.get("support_case_control_address","*****@*****.**"), 
                     email, subject, message)

        return render_template("email/case_created", c)
Ejemplo n.º 27
0
	def POST(self):
		data = web.input()
		ishuman = False
		if data.__contains__('session-secret'):
			ishuman = ayah.score_result(data['session-secret'])
		if ishuman and data.__contains__('subject') and data.__contains__('message') and data.__contains__('senderemail'):
				# good
				web.sendmail('*****@*****.**', '*****@*****.**', data['subject'], data['message'])
Ejemplo n.º 28
0
def sendmail_to_signatory(user, pid):
    """sends a thanks mail to the user, with request to share the petition with friends.
    """
    p = get_petition_by_id(pid)
    p.url = "http://watchdog.net/c/%s" % (pid)
    token = auth.get_secret_token(user.email)
    msg = render_plain.signatory_mailer(user, p, token)
    web.sendmail(config.from_address, user.email, msg.subject.strip(), str(msg))
Ejemplo n.º 29
0
def send_feedback(_from, subject, message):
    to = ['*****@*****.**']
    
    success = False
    if _from and message:
        web.sendmail(_from, ','.join(to), projectName + ': ' + subject, message)
        success = True
    return success
Ejemplo n.º 30
0
 def POST(self):
     i = web.input()
     to_addr = test_email
     from_addr = self.get_from_input('email', i) or ''
     subject = self.get_from_input('issue', i) or ''
     msg = self.get_from_input('message', i) or ''
     web.sendmail(from_addr, to_addr, subject, msg)
     return 
Ejemplo n.º 31
0
    def _send_emails_in_background(self, emails, registered,
                                   delete_user_function):

        if registered:
            subject = _("You have been enrolled on a course")
        else:
            subject = _("Welcome on UNCode")
        headers = {"Content-Type": 'text/html'}
        for (email_address, email_content) in emails:
            try:
                web.sendmail(web.config.smtp_sendername, email_address,
                             subject, email_content, headers)
            except:
                # Unregister student in case it failed to send the email.
                if not registered:
                    delete_user_function({"email": email_address})
Ejemplo n.º 32
0
    def sendmail(self, to, msg, cc=None):
        cc = cc or []
        subject = msg.subject.strip()
        body = web.safestr(msg).strip()

        if config.get('dummy_sendmail'):
            print('To:', to, file=web.debug)
            print('From:', config.from_address, file=web.debug)
            print('Subject:', subject, file=web.debug)
            print(file=web.debug)
            print(body, file=web.debug)
        else:
            web.sendmail(config.from_address,
                         to,
                         subject=subject,
                         message=body,
                         cc=cc)
Ejemplo n.º 33
0
    def lost_passwd(self, data):
        """ Send a reset link to user to recover its password """
        error = False
        msg = ""

        # Check input format
        email_re = re.compile(
            r"(^[-!#$%&'*+/=?^_`{}|~0-9A-Z]+(\.[-!#$%&'*+/=?^_`{}|~0-9A-Z]+)*"  # dot-atom
            r'|^"([\001-\010\013\014\016-\037!#-\[\]-\177]|\\[\001-011\013\014\016-\177])*"'  # quoted-string
            r')@(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+[A-Z]{2,6}\.?$',
            re.IGNORECASE)  # domain
        if email_re.match(data["recovery_email"]) is None:
            error = True
            msg = _("Invalid email format.")

        if not error:
            reset_hash = hashlib.sha512(
                str(random.getrandbits(256)).encode("utf-8")).hexdigest()
            user = self.database.users.find_one_and_update(
                {"email": data["recovery_email"]},
                {"$set": {
                    "reset": reset_hash
                }})
            if user is None:
                error = True
                msg = _("This email address was not found in database.")
            else:
                try:
                    web.sendmail(
                        web.config.smtp_sendername, data["recovery_email"],
                        _("INGInious password recovery"),
                        _("""Dear {realname},

Someone (probably you) asked to reset your INGInious password. If this was you, please click on the following link :
""").format(realname=user["realname"]) + web.ctx.home + "/register?reset=" +
                        reset_hash)
                    msg = _(
                        "An email has been sent to you to reset your password."
                    )
                except:
                    error = True
                    msg = _(
                        "Something went wrong while sending you reset email. Please contact the administrator."
                    )

        return msg, error
Ejemplo n.º 34
0
def send_response(to, i, form_controls, response):
    """sends a mail to `to` to check if the form is submitted properly.
    """
    inputs = '\n'.join(['%s: %s' % (k, v) for k, v in i.items()])
    msg = 'Filled at watchdog.net:\n\n%s' % inputs

    form_values = "\n".join(
        ["%s: %s" % (c.name, c.value) for c in form_controls])
    msg += '\n\nFilled in the last form:\n\n%s' % form_values

    if response:
        msg += '\n\nResponse: \n\n' + response
    else:
        msg += '\n\n(Not Production click, no response)'

    subject = 'wyr mail'
    web.sendmail(from_address, to, subject, msg)
Ejemplo n.º 35
0
    def POST(self):
        user_data = web.input()
        email_form = mainForm()

        num_guests = int(user_data.num_guests)

        responses = [{
            'partyName': user_data['party_name'],
            'firstName': user_data['first_name_%d' % guest_num],
            'lastName': user_data['last_name_%d' % guest_num],
            'attending': user_data['attending_%d' % guest_num],
            'mealChoice': user_data['meal_choice_%d' % guest_num],
            'notes': user_data['notes_%d' % guest_num],
            'emailAddress': user_data['email']
        } for guest_num in range(0, num_guests)]

        if not email_form.validates():
            # ugh, stupid people, we have to go back now...
            guests = model.get_guests(user_data.party_name)
            return render.rsvp(user_data.party_name, responses, email_form)

        yay = False
        for r in responses:
            yay = True if r['attending'] == 'Yes' else yay

        # shove data into the database
        model.update_guest_responses(responses)

        # shove the responses into google spreadsheet
        model_gdata.update_guest_responses(responses)

        # send an email to the guest to let them know they successfully RSVP-ed
        web.sendmail('*****@*****.**',
                     user_data['email'],
                     'Thanks for responding!',
                     email_render.thanks_email(responses, yay),
                     headers={'Content-Type': 'text/html;charset=utf-8'})

        # send an email to ourselves
        web.sendmail('*****@*****.**',
                     '*****@*****.**',
                     'RSVP: %s' % user_data['party_name'],
                     email_render.thanks_email(responses, yay),
                     headers={'Content-Type': 'text/html;charset=utf-8'})

        return render.thanks(yay)
Ejemplo n.º 36
0
 def POST(self):
     form = addform()
     if not form.validates():
         users = model.get_users()
         return render.index(users, form)
     model.new_user(form.d.login, form.d.password, form.d.prefix,
                    form.d.firstname, form.d.lastname, form.d.email,
                    form.d.phone, form.d.addr1, form.d.addr2, form.d.city,
                    form.d.state, form.d.country, form.d.zip,
                    form.d.approved)
     mailfrom = "rhn-newuser-request@localhost"
     mailto = "root@localhost"
     subject = "New User Added"
     message = "The following user has requested access: %s" % (
         form.d.login)
     web.sendmail(mailfrom, mailto, subject, message)
     return "Thank you, an email will be sent for Approval."
Ejemplo n.º 37
0
    def sendmail(self, to, msg, cc=None):
        cc = cc or []
        subject = msg.subject.strip()
        body = web.safestr(msg).strip()

        if config.get('dummy_sendmail'):
            print >> web.debug, 'To:', to
            print >> web.debug, 'From:', config.from_address
            print >> web.debug, 'Subject:', subject
            print >> web.debug
            print >> web.debug, body
        else:
            web.sendmail(config.from_address,
                         to,
                         subject=subject,
                         message=body,
                         cc=cc)
Ejemplo n.º 38
0
 def POST(self):
     ip_addr = web.ctx.get(
         'ip')  #if someone post some information, add the history records
     msg = web.ctx.get('method')
     db.insert('history', ip=ip_addr, method=msg)
     f = myform()
     if not f.validates(
     ):  #if not validated, display the mail interface for the user again
         return render.mail(f)
     else:  #if validated, send the email and redirect the previous page
         web.config.smtp_server = 'smtp.gmail.com'  #config the stmp server
         web.config.smtp_port = 587
         web.config.smtp_username = '******'
         web.config.smtp_password = '******'
         web.config.smtp_starttls = True
         web.sendmail('*****@*****.**', f.d.Receiver, f.d.Subject,
                      f.d.Message)
         raise web.seeother('/mail')
Ejemplo n.º 39
0
Archivo: code.py Proyecto: scoot557/ah
 def POST(self):
     data = web.input()
     email = data.get('email', '').lower()
     newpassword = data.get('newpw', '')
     oldpassword = data.get('oldpw', '')
     print 'Password change attempt...'
     if email:
         if not emailregex.match(email):
             return "Invalid email."
         print 'non logged in user'
         newpassword = usermodel.resetPassword(email)
         if newpassword:
             body = '<p>Your account recently asked for a password reset.  <p>'
             body += 'Here is the new password:  %s</p>' % (newpassword)
             body += '<p>Please click here and login: <a href="http://www.actuallyheard.com/">Log In</a></p></html>'
             web.sendmail('Actually Heard',
                          email,
                          'Password Reset',
                          body,
                          headers=({
                              'Content-Type':
                              'text/html; charset="utf-8";'
                          }))
             return True
         else:
             return "No email registered."
     elif session.userid != 'none' and newpassword != '':
         oldpw = hashlib.sha256(oldpassword).hexdigest()
         if usermodel.authUser(session.email, oldpw):
             stat = usermodel.changePassword(session.userid, newpassword)
             if stat:
                 body = '<p>Your account recently changed the password to login.  <p>'
                 body += '<p>If this was unauthorized, please click <a href="http://www.actuallyheard.com/contactus">here</a> and notify us.</p></html>'
                 web.sendmail('Actually Heard',
                              session.email,
                              'Password Change',
                              body,
                              headers=({
                                  'Content-Type':
                                  'text/html; charset="utf-8";'
                              }))
                 return True
     return 'Invalid Email'
Ejemplo n.º 40
0
    def POST(self, arg1=0):
        """
        Creates password recovery request, taking argument as user_id (default) or username
        """
        try:
            uid_type = json.loads(web.data()).get('uid_type', '')
        except ValueError:
            uid_type = ''

        token = hash_utils.random_hex()

        web.header('Content-Type', 'application/json')

        if uid_type == 'username':
            user_email = users_model().request_password(
                token, users_model.get_user_id(arg1))
        elif uid_type == 'user_id' or 'uid_type' == '':
            user_email = users_model().request_password(token, int(arg1))
        else:
            return json.dumps({
                'success': False,
                'messages': ['Unknown uid type']
            })

        if user_email == '':
            return json.dumps({
                'success': False,
                'messages': ['User not found']
            })

        web.config.smtp_server = 'smtp.gmail.com'
        web.config.smtp_port = 587
        web.config.smtp_username = '******'
        web.config.smtp_password = '******'
        web.config.smtp_starttls = True
        web.sendmail(
            '*****@*****.**', user_email, 'Password recovery',
            'http://' + web.ctx.host + web.ctx.homepath +
            '/#password_change_page?token=' + token)
        return json.dumps({
            'success': True,
            'messages': ['Password recovery email sent']
        })
Ejemplo n.º 41
0
    def POST(self, path):
        book = get_book(path)
        record = get_scan_record(path)
        user = accounts.get_current_user()
        delegate.admin_login()
        q = {
            'key': '/scan_record' + path,
            'scan_status': {
                'connect': 'update',
                'value': 'WAITING_FOR_BOOK'
            },
            'sponsor': {
                'connect': 'update',
                'key': user.key
            },
            'request_date': {
                'connect': 'update',
                'value': datetime.datetime.utcnow().isoformat()
            }
        }
        try:
            web.ctx.site.write(q)
        finally:
            web.ctx.headers = []

        def get_to():
            if config.get('plugin_scod') is not None:
                return config.plugin_scod.get('email_recipients', [])
            else:
                return config.get('scan_email_recipients', [])

        to = get_to()
        if to:
            scan_record = get_scan_record(path)
            message = render.scan_request_email(book, scan_record)
            web.sendmail(config.from_address, to, message.subject.strip(),
                         message)

        to = get_email(user)
        message = render.scan_waiting_email(book, scan_record)
        web.sendmail(config.from_address, to, message.subject.strip(), message)
        return render.scan_inprogress(book)
Ejemplo n.º 42
0
    def POST(self):
        # if not support_db:
        #     return "Couldn't initialise connection to support database"
        form = web.input()
        email = form.get("email", "")
        topic = form.get("topic", "")
        description = form.get("question", "")
        url = form.get("url", "")
        user = accounts.get_current_user()
        useragent = web.ctx.env.get("HTTP_USER_AGENT", "")
        if not all([email, topic, description]):
            return ""

        default_assignees = config.get("support_default_assignees", {})
        topic_key = str(topic.replace(" ", "_").lower())
        if topic_key in default_assignees:
            # This is set to False to prevent cases from being created
            # even if there is a designated assignee. This prevents
            # the database from being updated.
            create_case = False
            assignee = default_assignees.get(topic_key)
        else:
            create_case = False
            assignee = default_assignees.get("default", "*****@*****.**")
        if create_case:
            c = support_db.create_case(
                creator_name=user and user.get_name() or "",
                creator_email=email,
                creator_useragent=useragent,
                creator_username=user and user.get_username() or "",
                subject=topic,
                description=description,
                url=url,
                assignee=assignee)
            stats.increment("support.all")
        else:
            stats.increment("support.all")
            subject = "Support case *%s*" % topic
            message = "A new support case has been filed\n\nTopic: %s\n\nDescription:\n%s" % (
                topic, description)
            web.sendmail(email, assignee, subject, message)
        return render_template("email/case_created", assignee)
Ejemplo n.º 43
0
def main():
    parser = OptionParser()
    parser.add_option("--email",
                      dest="email",
                      help="address to send email",
                      action="append")
    options, args = parser.parse_args()

    dir, date = args

    msg = process_errors(dir, date)
    if options.email:
        web.sendmail(
            from_address='Open Library Errors<*****@*****.**>',
            to_address=options.email,
            subject=msg.subject,
            message=web.safestr(msg))
        print "email sent to", ", ".join(options.email)
    else:
        print msg
Ejemplo n.º 44
0
 def POST(self):
     i = web.input(email='')
     web.header('Content-Type', 'application/json')
     user = model.User()
     user_id = user.matched_id(email=i.email)
     if user_id:
         status = user.status(user_id) # 获取当前状态
         temp_password = status['password_hash'][0:8] # 使用原来密码的“MD5值前8位”作为临时密码
         # 发送邮件
         subject = '请尽快修改您的密码——来自论坛网站'
         message = '''尊敬的%s:
                          您的临时密码是"%s",请用该密码登录后,尽快修改密码,谢谢!
                   ''' % (status['username'], temp_password)
         try:
             web.sendmail(settings.SITE_SMTP_USERNAME, i.email, subject, message)
         except Exception, e: # 发送失败
             print e
         else: # 发送成功
             if user.update(user_id, password=temp_password): # 设置临时密码
                 return json.dumps({'result': True})
Ejemplo n.º 45
0
def send_mail_to_set_password(email):
    token = get_secret_token(email, validity=365)
    url = set_password_url(email, token)
    subject = 'Set your watchdog.net password'
    msg = """\
Thanks for using watchdog.net. We've created an account
for you with this email address -- but we don't have
a password for it. So that you can log in later, please
set your password at:

%s

If you've already set a password, then don't worry about
it and sorry for the interruption. If you think you received
this email in error, please hit reply and let us know.

Thanks,
watchdog.net
""" % (url)
    web.sendmail(config.from_address, email, subject, msg)
Ejemplo n.º 46
0
 def POST(self):
     i = web.input()
     emailform, loadcontactsform = forms.emailform(
     ), forms.loadcontactsform()
     if emailform.validates(i):
         url, msg, subject = i.url, i.body, i.subject
         emails = [e.strip() for e in i.emails.strip(', ').split(',')]
         u = helpers.get_user_by_email(helpers.get_loggedin_email()
                                       or helpers.get_unverified_email())
         from_address = u and "%s %s <%s>" % (
             u.fname, u.lname, u.email) or config.from_address
         for email in emails:
             web.sendmail(from_address, email, subject, msg)
         page_or_petition = url.startswith('/c/') and 'petition' or 'page'
         helpers.set_msg('Thanks for sharing this %s with your friends!' %
                         page_or_petition)
         raise web.seeother(url)
     else:
         return self.GET(emailform=emailform,
                         loadcontactsform=loadcontactsform)
Ejemplo n.º 47
0
def send_mail(send_to,
              subject,
              body,
              smtp_server,
              username,
              password,
              cc=None,
              bcc=None):
    try:
        web.config.smtp_server = 'smtp.' + smtp_server  ##邮件发送服务器
        web.config.smtp_port = 25  ##不设置将使用默认端口
        web.config.smtp_username = username  ##邮件服务器的登录名
        web.config.smtp_password = password  ##邮件服务器的登录密码
        web.config.smtp_starttls = True
        send_from = username  ##发送的邮件
        web.sendmail(send_from, send_to, subject, body, cc=cc, bcc=bcc)
        return 1  #pass
    except Exception, error:
        print error
        return -1  #fail
Ejemplo n.º 48
0
    def GET(self):
        username = session.username

        email = db.select('users', where='username=$username',
                          vars=locals())[0]["emailaddress"]

        emailhash = ''.join(
            random.choice(string.ascii_lowercase + string.digits)
            for _ in range(24))

        db.update('users',
                  where="username=$username",
                  emailhash=emailhash,
                  vars=locals())

        web.sendmail(
            'Moodboard', email, 'Verify Your Account',
            'Hi %s, here is your new verification link: http://127.0.0.1:8080/verify?email=%s&hash=%s'
            % (username, email, emailhash))

        return homepage_render.message("Verification Email Sent", session, "")
Ejemplo n.º 49
0
    def POST(self):
        form = web.input(username="", email="", password="")
        make_new_user(form.username)

        new_user_folder = os.path.join("static", form.username)

        # Hash Password
        passwordhash, passwordsalt = hash_password(form.password)

        makeuser = db.insert('users',
                             username=form.username,
                             emailaddress=form.email,
                             passwordhash=passwordhash,
                             salt=passwordsalt,
                             userfolder=new_user_folder,
                             datejoined=get_logtime())

        web.sendmail('Moodboard', form.email, 'Welcome!',
                     'Welcome to Moodboard, %s' % form.username)
        return homepage_render.welcome(form.username, form.password,
                                       passwordhash, passwordsalt)
Ejemplo n.º 50
0
def email_sponsor(recipient, book):
    url = 'https://openlibrary.org%s' % book.key
    resp = web.sendmail(
        "*****@*****.**",
        recipient,
        "Internet Archive: Your Open Library Book Sponsorship is Ready",
        ('<p>' + '<a href="%s">%s</a> ' %
         (url, book.title) + 'is now available to read on Open Library!' +
         '</p>' + '<p>Thank you,</p>' +
         '<p>The <a href="https://openlibrary.org">Open Library</a> Team</p>'),
        headers={'Content-Type': 'text/html;charset=utf-8'})
    return resp
Ejemplo n.º 51
0
    def _batch_job_done_callback(self,
                                 batch_job_id,
                                 retval,
                                 stdout,
                                 stderr,
                                 file,
                                 send_mail=None):
        """ Called when the batch job with id jobid has finished.
            :param retval: an integer, the return value of the command in the container
            :param stdout: stdout of the container
            :param stderr: stderr of the container
            :param file: tgz as bytes. Can be None if retval < 0
        """

        result = {
            "retval": retval,
            "stdout": stdout,
            "stderr": stderr,
        }
        if file is not None:
            result["file"] = self._gridfs.put(file)

        # Save submission to database
        self._database.batch_jobs.update({"_id": batch_job_id},
                                         {"$set": {
                                             "result": result
                                         }})

        # Send a mail to user
        if send_mail is not None:
            try:
                web.sendmail(
                    web.config.smtp_sendername, send_mail,
                    "Batch job {} finished".format(batch_job_id),
                    """This is an automated message.

The batch job you launched on INGInious is done. You can see the results on the "batch operation" page of your course
administration.""")
            except Exception as e:
                self._logger.error("Cannot send mail: " + str(e))
Ejemplo n.º 52
0
    def POST(self):
        data = web.input()
        logging.debug(data)
        # If there is no txn_id in the received arguments don't proceed
        if not "txn_id" in data:
            logging.debug("No txn_id")
            return "No Parameters"

        # Verify the data received with Paypal
        if not verify_ipn(data):
            logging.debug("Verification failed")
            return "CALLBACK_FAILED"
        logging.debug("IPN verification pass")

        # If verified, store desired information about the transaction
        transaction_data = {
            "txn": data["txn_id"],
            "amount": data["mc_gross"],
            "fee": data["mc_fee"],
            "email": data["payer_email"],
            "name": data["first_name"] + " " + data["last_name"],
            "status": data["payment_status"],
            "payment_date": data["payment_date"]
            }
        logging.debug("CART_ID %s" % (data["invoice"], ))
        logging.debug(transaction_data)
        # Update DB
        db.callbackBadge(data["invoice"], transaction_data)

        # Send email
        web.sendmail(config.email["debug_from"], config.email["debug"],
                     "IPN", transaction_data)
        hashEmail = hashlib.sha1()
        hashEmail.update(transaction_data["email"])
        hashEmail.update(config.salt)
        logging.debug("Sending confirmation email to %s" % (transaction_data["email"], ))
        web.sendmail(config.email["notice_from"], data["payer_email"],
                     "G-Anime Pre-Registration", render.e_val(data["invoice"], hashEmail.hexdigest(), transaction_data))
        return "CALLBACK_COMPLETE"
Ejemplo n.º 53
0
    def POST(self, path):
        if not self.is_scan_user():
            return permission_denied('Permission denied.')

        book = web.ctx.site.get(path)
        i = web.input("scan_status", _comment=None)

        q = {
            'key': '/scan_record' + path,
            'scan_status': {
                'connect': 'update',
                'value': i.scan_status
            }
        }
        web.ctx.site.write(q, i._comment)

        def get_email(user):
            try:
                delegate.admin_login()
                return web.utf8(web.ctx.site.get_user_email(user.key).email)
            finally:
                web.ctx.headers = []

        scan_record = get_scan_record(path)
        to = scan_record.sponsor and get_email(scan_record.sponsor)
        cc = getattr(config, 'scan_email_recipients', [])
        if to:
            if i.scan_status == 'SCAN_IN_PROGRESS':
                message = render.scan_inprogress_email(book, scan_record,
                                                       i._comment)
            else:
                message = render.scan_book_notfound_email(
                    book, scan_record, i._comment)
            web.sendmail(config.from_address,
                         to,
                         message.subject.strip(),
                         str(message),
                         cc=cc)
        raise web.seeother(web.changequery(query={}))
Ejemplo n.º 54
0
    def POST(self):
        i = web.input()
        f = forms.forgot_password()
        if not f.validates(i):
            return render.forgot_password(f)
        else:
            from infogami.infobase.client import ClientException
            try:
                delegate.admin_login()
                d = web.ctx.site.get_reset_code(i.email)
            except ClientException as e:
                f.note = str(e)
                web.ctx.headers = []
                return render.forgot_password(f)
            else:
                # clear the cookie set by delegate.admin_login
                # Otherwise user will be able to work as admin user.
                web.ctx.headers = []

            msg = render.password_mailer(web.ctx.home, d.username, d.code)
            web.sendmail(config.from_address, i.email, msg.subject.strip(), str(msg))
            return render.passwordsent(i.email)
Ejemplo n.º 55
0
    def GET(self, id):
        try:
            user = User.get(rfid=id)
            amount = settings.CONSUMPTION_UNIT
            Operation.new(user_id=user.id,
                          amount=-amount,
                          date=datetime.datetime.now()).save()
            user.balance -= float(amount)
            user.save()

            return "OK"
        except Entry.DoesNotExist:
            body = settings.MAIL_TPL_UNKNOWN_CARD.format(
                new_user_url=urlize('/users/add/?rfid={}'.format(id)),
                existing_user_url=urlize('/users/rfid/{}'.format(id)),
                hour=datetime.datetime.now().strftime('%H:%M'))

            web.sendmail(settings.MAIL_ADDRESS,
                         settings.SECRETARY_MAIL_ADDRESS,
                         '[INGIfet] Carte inconnue {}'.format(id), body)

            raise web.notfound()
Ejemplo n.º 56
0
    def POST(self):
        i = web.input()
        form = forms.forgot_password()
        if form.validates(i):
            token = get_secret_token(i.email)
            reset_url = set_password_url(i.email, token)
            subject = 'Reset your watchdog.net password'
            msg = """\
You asked to reset your password on watchdog.net.
You can do so at:

%s

but you have to do it within the next 7 days.

Thanks,
watchdog.net
""" % (reset_url)
            web.sendmail(config.from_address, i.email, subject, msg)
            helpers.set_msg('Check your email to reset your password.')
            raise web.seeother('/u/forgot_password', absolute=True)
        else:
            return self.GET(form)
Ejemplo n.º 57
0
def send_message(user, message, subject=None):
    # sending email
    # print "User:"******"Email") != -1:
        # doing email
        receiver_email = user.get('email')
        web.sendmail(sender_email,
                     receiver_email,
                     subject,
                     message,
                     headers=email_headers)
        pass
    elif notification.find("HTTP") != -1:
        # doing post
        httpurl = user.get('httpurl')
        number = user.get('number')
        print "Fake post to user Number:%s URL:%s Message:%s" % (
            number, httpurl, message)
        pass
    else:
        # nothing to do
        pass
Ejemplo n.º 58
0
    def POST(self):
        cur_form = new_user_form()
        if cur_form.validates():

            username = cur_form['username'].value
            password = cur_form['password'].value
            email = cur_form['email'].value

            if username not in db.select('users', what='username'):

                # Make user folders
                make_new_user(username)

                new_user_folder = os.path.join("static", username)

                # Hash Password
                passwordhash, passwordsalt = hash_password(password)

                makeuser = db.insert('users',
                                     username=username,
                                     emailaddress=email,
                                     passwordhash=passwordhash,
                                     salt=passwordsalt,
                                     userfolder=new_user_folder,
                                     datejoined=get_logtime())

                web.sendmail('Moodboard', email, 'Welcome!',
                             'Welcome to Moodboard, %s' % username)
                return homepage_render.welcome(
                    username, password, passwordhash, passwordsalt,
                    session._initializer['loggedin'])
            else:
                # Error username taken
                return message_render.message('Username Taken')
        else:
            return homepage_render.newuser("New User", cur_form,
                                           session._initializer['loggedin'])
Ejemplo n.º 59
0
def _sendmail(to, msg, cc=None, frm=None):
    cc = cc or []
    frm = frm or config.from_address
    if config.get('dummy_sendmail'):
        message = (
            ''
            + 'To: '
            + to
            + '\n'
            + 'From:'
            + config.from_address
            + '\n'
            + 'Subject:'
            + msg.subject
            + '\n'
            + '\n'
            + web.safestr(msg)
        )

        print("sending email", message, file=web.debug)
    else:
        web.sendmail(
            frm, to, subject=msg.subject.strip(), message=web.safestr(msg), cc=cc
        )
Ejemplo n.º 60
0
    def POST(self, path):
        if not self.is_scan_user():
            return permission_denied('Permission denied.')

        book = get_book(path, check_scanned=False, check_ocaid=False)
        i = web.input("ocaid",
                      volumes=None,
                      multivolume_work=None,
                      _comment=None)

        q = [{
            'key': path,
            'ocaid': {
                'connect': 'update',
                'value': i.ocaid
            }
        }, {
            'key': '/scan_record' + path,
            'scan_status': {
                'connect': 'update',
                'value': 'SCAN_COMPLETE'
            },
            'completion_date': {
                'connect': 'update',
                'value': datetime.datetime.utcnow().isoformat()
            }
        }]

        if i.multivolume_work:

            def volume(index, ia_id):
                return {
                    'type': {
                        'key': '/type/volume'
                    },
                    'volume_number': index,
                    'ia_id': ia_id
                }

            volumes = i.volumes and i.volumes.split() or []
            q[0]['volumes'] = {
                'connect': 'update_list',
                'value':
                [volume(index + 1, v) for index, v in enumerate(volumes)]
            }
            q[0]['ocaid'] = {'connect': 'update', 'value': ''}

        web.ctx.site.write(q, i._comment)

        scan_record = get_scan_record(path)
        to = scan_record.sponsor and get_email(scan_record.sponsor)
        cc = getattr(config, 'scan_email_recipients', [])
        if to:
            message = render.scan_complete_email(book, scan_record, i._comment)
            web.sendmail(config.from_address,
                         to,
                         message.subject.strip(),
                         str(message),
                         cc=cc)

        raise web.seeother(web.changequery(query={}))