Пример #1
0
 def new(self):
     user = None
     if "repoze.who.identity" in request.environ:
         user = request.environ.get('repoze.who.identity')['user']
     values= dict(request.params)
     for email in session['site_settings']['contactusmail'].split(','):
         if user:
             message = Message(user.emails[0].email_address,
                 email,
                 "contactus from %s"%values['email'],
                 encoding='utf-8')
             message.plain = "%s"%values['message']
             message.send()
         else:
             message = Message(values['email'],
                               
                 email,
                 "contactus asked to reply to %s"%values['email'],
                 encoding='utf-8')
             message.plain = "%s"%values['message']
             message.send()
     h.flash(_("Your message was sent successfully."))
     return redirect(h.url(controller='contactus',action='index'))
             
         
     
Пример #2
0
    def _reset(self, username=None):
        username = username or request.environ.get('REMOTE_USER', False)
        if not username:
            abort(401)

        try:
            user = h.get_user(username)
        except:
            abort(400)
            
        new_password = user.reset_password()


        msg = Message("*****@*****.**", user.email,
                      "InPhO password reset")
        msg.plain = """
%(name)s, your password at the Indiana Philosophy Ontology (InPhO) has been changed to:
Username: %(uname)s
Password: %(passwd)s

The Indiana Philosophy Ontology (InPhO) Team
[email protected]
                       """ % {'passwd' : new_password,
                              'uname' : user.username,
                              'name' : user.fullname or user.username or ''}
        msg.send()

        Session.commit()

        h.redirect(h.url(controller='account', action='reset_result'))
Пример #3
0
 def feedback(self):
     try:
         vars = self.request.json_body
         sanitized_description = bleach.clean(vars['description'])
         html_body = u"<h3>L\'utilisateur <a href=\"mailto:{0}\">{0}</a> " \
             u"a remarqué le problème suivant:</h3><p>{1}</p>" \
             u"<p><a href=\"{3}\">Ouvrir le lien vers la carte</a></p>" \
             u"<h3>La couche suivante est concernée:</h3>" \
             u"<p>{2}</p>" \
             .format(vars['email'],
                     sanitized_description,
                     vars['layer'],
                     vars['url']
                     )
         support_email = self.config.get('feedback.support_email',
                                         '*****@*****.**')
         message = Message(author=vars['email'],
                           to=support_email,
                           subject=u'Un utilisateur a signalé un problème')
         message.plain = html_body
         message.rich = html_body
         message.encoding = 'utf-8'
         message.send()
     except Exception as e:
         log.exception(e)
         return HTTPNotFound()
     return {'success': True}
Пример #4
0
 def request_enable(self, id=None):
     if id is None:
         abort(404)
     user = h.get_object_or_404(User, id=id)
     admins = User.query.filter_by(superuser=True).all()
     app_name = config['application_name']
     from_addr = config['error_email_from']
     suffix = config['email_suffix']
     subject = "New user request for "+app_name
     requested_courses = request.params["requested_course_name"]
     user.requested_courses = requested_courses
     if not request.environ.has_key('REMOTE_ADDR'):
         request.environ['REMOTE_ADDR'] = "127.0.0.1" #must be debugging locally on paste
     ip = request.environ['REMOTE_ADDR']
     for admin in admins:
         to_addr = admin.name + "@" + suffix
         body = "Dear "+admin.name+",\n\nA new user has requested an account on "+app_name+".\n\nDetails:\n\n"
         body += "username: "******"\n"
         body += "requested course(s): "+requested_courses+"\n"
         body += "timestamp: "+str(datetime.datetime.today())+"\n"
         body += "remote ip: "+ip+"\n\n\n"
         body += "Please login to https://comoto.cs.illinois.edu to approve or deny this request\n\n"
         body += "Thanks\n\n"
         body += "The "+app_name+" Team\n\n\n\n"
         body += "Please do not reply to this message, as this account is not monitored"
         message = Message(from_addr, to_addr, subject)
         message.plain = body
         message.send()
     session['flash'] = "Request Acknowledged"
     session.save()
     Session.commit()
     redirect_to(controller="login", action="index", id=None)
Пример #5
0
def send_email(sender, truename, emails, title, plain, rich):
    """
    notify using email
    sending alert email to followers
    """
    """
    rand send email 
    """
    day_str = datetime.datetime.strftime(datetime.datetime.today(),"%d%H")
    sender = 'Knowing <*****@*****.**>' % day_str
    
    logging.debug('Send email %s' % ', '.join((truename, str(emails), title, plain, rich)))

    try:
        mail = Message()
        mail.subject = title
        mail.sender = sender
        mail.to = u'%s <%s>' % (truename, emails[0])
        if len(emails) > 1:
            mail.cc = u','.join(emails[1:])
        mail.encoding = 'utf-8'
        mail.plain = plain
        mail.rich = rich
        mail.send()

    except Exception, e:
        logging.exception('Fail to send email.')
 def feedback(self):
     try:
         vars = self.request.json_body
         sanitized_description = bleach.clean(vars['description'])
         html_body = u"<h3>L\'utilisateur <a href=\"mailto:{0}\">{0}</a> " \
             u"a remarqué le problème suivant:</h3><p>{1}</p>" \
             u"<p><a href=\"{3}\">Ouvrir le lien vers la carte</a></p>" \
             u"<h3>La couche suivante est concernée:</h3>" \
             u"<p>{2}</p>" \
             .format(vars['email'],
                     sanitized_description,
                     vars['layer'],
                     vars['url']
                     )
         support_email = self.config.get('feedback.support_email',
                                         '*****@*****.**')
         message = Message(
             author=vars['email'],
             to=support_email,
             subject=u'Un utilisateur a signalé un problème')
         message.plain = html_body
         message.rich = html_body
         message.encoding = 'utf-8'
         message.send()
     except Exception as e:
         log.exception(e)
         return HTTPNotFound()
     return {'success': True}
Пример #7
0
 def test_mail_encoding_is_used_as_fallback(self):
     interface.config['mail.encoding'] = 'ISO-8859-1'
     message = Message('*****@*****.**', '*****@*****.**', 'Test')
     message.plain = 'Hello world!'
     msg = email.message_from_string(str(message))
     self.assertEqual('text/plain; charset="iso-8859-1"', msg['Content-Type'])
     self.assertEqual('quoted-printable', msg['Content-Transfer-Encoding'])
Пример #8
0
    def submit(self):
        ''' 
        This function validates the submitted registration form and creates a
        new user. Restricted to ``POST`` requests. If successful, redirects to 
        the result action to prevent resubmission.
        ''' 
        
        user = User(
            self.form_result['username'],
            self.form_result['password'],
            email=self.form_result['email'],
            first_area_id=self.form_result['first_area'],
            first_area_level=self.form_result['first_area_level'],
            second_area_id=self.form_result['second_area'],
            second_area_level=self.form_result['second_area_level']
        )


        Session.add(user) 
        Session.commit()

        msg = Message("*****@*****.**", self.form_result['email'], 
                      "InPhO registration")
        msg.plain = """%s, thank you for registering with the Indiana Philosophy
                        Ontology Project (InPhO). You can access your """ % self.form_result['username'] 
        msg.send()

        h.redirect(h.url(controller='account', action='result'))
Пример #9
0
    def _reset(self, username=None):
        username = username or request.environ.get('REMOTE_USER', False)
        if not username:
            abort(401)

        try:
            user = h.get_user(username)
        except:
            abort(400)
            
        new_password = user.reset_password()


        msg = Message("*****@*****.**", user.email,
                      "InPhO password reset")
        msg.plain = """
%(name)s, your password at the Indiana Philosophy Ontology (InPhO) has been changed to:
Username: %(uname)s
Password: %(passwd)s

The Indiana Philosophy Ontology (InPhO) Team
[email protected]
                       """ % {'passwd' : new_password,
                              'uname' : user.username,
                              'name' : user.fullname or user.username or ''}
        msg.send()

        Session.commit()

        h.redirect(h.url(controller='account', action='reset_result'))
Пример #10
0
 def test_message_instantiation_with_positional_parameters(self):
     message = Message('*****@*****.**', '*****@*****.**', 'Test')
     message.plain = 'Hello world!'
     msg_string = str(message)
     self.failUnless('From: [email protected]' in msg_string)
     self.failUnless('To: [email protected]' in msg_string)
     self.failUnless('Subject: Test' in msg_string)
Пример #11
0
    def submit(self):
        ''' 
        This function validates the submitted registration form and creates a
        new user. Restricted to ``POST`` requests. If successful, redirects to 
        the result action to prevent resubmission.
        '''

        user = User(self.form_result['username'],
                    self.form_result['password'],
                    email=self.form_result['email'],
                    first_area_id=self.form_result['first_area'],
                    first_area_level=self.form_result['first_area_level'],
                    second_area_id=self.form_result['second_area'],
                    second_area_level=self.form_result['second_area_level'])

        Session.add(user)
        Session.commit()

        msg = Message("*****@*****.**", self.form_result['email'],
                      "InPhO registration")
        msg.plain = """%s, thank you for registering with the Indiana Philosophy
                        Ontology Project (InPhO). You can access your """ % self.form_result[
            'username']
        msg.send()

        h.redirect(h.url(controller='account', action='result'))
Пример #12
0
def send_email(sender, truename, emails, title, plain, rich):
    """
    notify using email
    sending alert email to followers
    """
    """
    rand send email 
    """
    day_str = datetime.datetime.strftime(datetime.datetime.today(), "%d%H")
    sender = "Knowing <*****@*****.**>" % day_str

    logging.debug("Send email %s" % ", ".join((truename, str(emails), title, plain, rich)))

    try:
        mail = Message()
        mail.subject = title
        mail.sender = sender
        mail.to = u"%s <%s>" % (truename, emails[0])
        if len(emails) > 1:
            mail.cc = u",".join(emails[1:])
        mail.encoding = "utf-8"
        mail.plain = plain
        mail.rich = rich
        mail.send()

    except Exception, e:
        logging.exception("Fail to send email.")
Пример #13
0
    def _send_email_entry(self, entry):
        sender = self.request.registry.settings.get('mail.message.author',
                                                    '*****@*****.**')
        recipient = entry.form.user.email
        subject = _("[MootiroForm] Entry #%(entry_number)d for the form %(form_title)s") \
                    % {"entry_number": entry.entry_number,
                       "form_title": entry.form.name}
        labels = [f.label for f in entry.form.fields]
        value = [f.value(entry) for f in entry.form.fields]
        fields = [{
            'label': labels[i],
            'value': value[i]
        } for i in range(len(labels))]
        try:
            rendered = self.request.registry.settings['genshi_renderer'] \
                .fragment('email_entry.genshi',
                    dict(entry=entry, fields=fields, url=self.url))
        except KeyError as e:
            raise KeyError(
                "Simon says: cd mootiro_web; git pull; ./setup.py develop")
        # TODO: Remove this except block after developers have updated.
        # 2011-08-11

        msg = Message(sender, recipient, self.tr(subject))
        msg.rich = rendered
        msg.plain = "We've collected an entry for you form. Visit us to see."
        msg.send()
Пример #14
0
 def do_email_students(self):
     log.debug(str(request.params))
     user = h.get_user(request.environ)
     student_ids_str = request.params['student_ids']
     student_ids = ah.fileset_id_string_to_id_list(student_ids_str)
     students = Student.query.filter(Student.id.in_(student_ids)).all()
     students = filter(lambda student: request.params.has_key(str(student.id)), students)
     for student in students:
         check_student_access(student)
     subject = request.params['subject']
     body = request.params['body']
     from_addr = (user.givenName+" "+user.surName,user.name + '@illinois.edu')
     reply_to = user.name + '@illinois.edu'
     to_addrs = map(lambda student: (student.displayName, student.netid + "@illinois.edu"), students)
     from turbomail import Message
     message = Message()
     message.subject = subject
     message.plain = body
     message.author = from_addr
     message.reply_to = reply_to
     message.to = to_addrs
     message.cc = from_addr
     message.send()
     if request.params.has_key('assignment_id'):
         return redirect_to(controller='view_analysis', action='view', id=request.params['assignment_id'])
     else:
         return redirect_to(controller='view_analysis', action='list')
Пример #15
0
 def email_test(self):
     from turbomail import Message
     msg = Message('*****@*****.**', '*****@*****.**', 'Subject')
     msg.plain = "Foo Bar"
     try:
         msg.send()   # Message will be sent through the configured manager/transport.
     except Exception, err:
         print err
Пример #16
0
 def email_test(self):
     from turbomail import Message
     msg = Message('*****@*****.**', '*****@*****.**', 'Subject')
     msg.plain = "Foo Bar"
     try:
         msg.send()   # Message will be sent through the configured manager/transport.
     except Exception, err:
         print err
Пример #17
0
 def test_message_instantiation_with_tuples(self):
     message = Message(('Foo Bar', '*****@*****.**'), 
                       ('To', '*****@*****.**'), 'Test')
     message.plain = 'Hello world!'
     msg_string = str(message)
     self.failUnless('From: Foo Bar <*****@*****.**>' in msg_string)
     self.failUnless('To: To <*****@*****.**>' in msg_string)
     self.failUnless('Subject: Test' in msg_string)
Пример #18
0
 def test_message_instantiation_with_keyword_parameters(self):
     message = Message(sender='*****@*****.**', recipient='*****@*****.**',
                       subject='Test')
     message.plain = 'Hello world!'
     msg_string = str(message)
     self.failUnless('From: [email protected]' in msg_string)
     self.failUnless('To: [email protected]' in msg_string)
     self.failUnless('Subject: Test' in msg_string)
Пример #19
0
 def test_message_enqueue(self):
     config = {'mail.on': True}
     fake_setuptools =  {'immediate': ImmediateManager,
                         'debug': DebugTransportFactory}
     interface.start(config, extra_classes=fake_setuptools)
     
     message = Message('*****@*****.**', '*****@*****.**', 'Test')
     message.plain = 'Hello world!'
     turbomail.enqueue(message)
Пример #20
0
 def on_success(cls, request, values):
     g = request.globals
     config = g.getMailConfig()
     interface.start(config)
     msg = Message(config['mail.smtp.username'], g.mailRecipient, "Contact", encoding ='utf-8')
     msg.plain = u'\n\n'.join( map(lambda s: s.format(**values), [u'First Name: {name}', u'Email: {email}', u'Message: {message}']) )
     msg.send()
     interface.stop(force=True)
     return {'success':True, 'redirect':request.fwd_url('website_home')}
Пример #21
0
 def test_use_sender_for_author_if_no_author_given(self):
     message = Message(sender='*****@*****.**', to='*****@*****.**', 
                       subject='Test')
     self.assertEqual('*****@*****.**', str(message.sender))
     message.plain = 'Hello world!'
     msg_string = str(message)
     self.failUnless('From: [email protected]' in msg_string)
     self.failUnless('To: [email protected]' in msg_string)
     self.failUnless('Subject: Test' in msg_string)
     self.failIf('Sender: ' in msg_string)
     self.assertEqual('*****@*****.**', str(message.sender))
Пример #22
0
    def send(self, mfrom, mto, subject, html_part):

        interface.start(self.turbomail_config)

        message = Message(mfrom, mto, subject=subject)
        #message.cc =('idea','*****@*****.**')
        message.encoding = 'gb2312'
        message.plain = "Mabotech"
        message.rich = html_part
        message.send()

        interface.stop()
Пример #23
0
def __notify(chart, message):
    """
    notify using email

    chart: Charts data row
    message: message body

    sending alert email to owner and followers
    """
    config = __get_config('webapp')

    mail_config = {}
    mail_config['mail.on'] = config['turbomail']['enable']
    mail_config['mail.manager'] = config['turbomail']['manager']
    mail_config['mail.transport'] = config['turbomail']['transport']
    mail_config['mail.smtp.server'] = config['turbomail']['server']

    sender = config['turbomail']['sender']
    """
    rand send email 
    """
    day_str = datetime.datetime.strftime(datetime.datetime.today(), "%d%H")
    sender = 'Knowing <*****@*****.**>' % day_str

    subject = message

    u = session.query(Users).filter(Users.username == chart.owner)

    addressee = ''
    if u:
        for i in u:
            if i.mobile:
                addressee = i.mobile + '@139.com'
            else:
                logger.warning("no mobile set for user \"%s\"" % i.username)
                return

    interface.start(mail_config)
    now = str(datetime.datetime.now())[0:19]

    chart_url = 'http://knowing.corp.anjuke.com/chart/%d' % chart.id

    html_part = u"<html><body><h1>Look, %s</h1><p>时间: %s</p><p>详细信息: %s</p><p><a href='%s'>%s</a></p><p>This mail is sent by Knowing</p></body></html>"
    html_part %= (chart.name, now, message, chart_url, chart_url)
    text_part = u"[critical] 时间: %s 详细信息: %s"
    text_part %= (now, message)

    mail = Message(sender, addressee, subject)
    mail.encoding = 'utf-8'
    mail.plain = message
    mail.rich = html_part
    flag = mail.send()
Пример #24
0
def __notify(chart, message):
    """
    notify using email

    chart: Charts data row
    message: message body

    sending alert email to owner and followers
    """
    config = __get_config('webapp')

    mail_config = {}
    mail_config['mail.on'] = config['turbomail']['enable']
    mail_config['mail.manager'] = config['turbomail']['manager']
    mail_config['mail.transport'] = config['turbomail']['transport']
    mail_config['mail.smtp.server'] = config['turbomail']['server']

    sender = config['turbomail']['sender']
    """
    rand send email 
    """
    day_str = datetime.datetime.strftime(datetime.datetime.today(),"%d%H")
    sender = 'Knowing <*****@*****.**>' % day_str

    subject = message

    u = session.query(Users).filter(Users.username == chart.owner)

    addressee = ''
    if u:
        for i in u:
            if i.mobile:
                addressee = i.mobile + '@139.com'
            else:
                logger.warning("no mobile set for user \"%s\"" % i.username)
                return

    interface.start(mail_config)
    now = str(datetime.datetime.now())[0:19]

    chart_url = 'http://knowing.corp.anjuke.com/chart/%d' % chart.id

    html_part = u"<html><body><h1>Look, %s</h1><p>时间: %s</p><p>详细信息: %s</p><p><a href='%s'>%s</a></p><p>This mail is sent by Knowing</p></body></html>"
    html_part %= (chart.name, now, message, chart_url, chart_url)
    text_part = u"[critical] 时间: %s 详细信息: %s"
    text_part %= (now, message)

    mail = Message(sender, addressee, subject)
    mail.encoding = 'utf-8'
    mail.plain = message
    mail.rich = html_part
    flag = mail.send()
Пример #25
0
 def test_message_properties(self):
     message = Message('*****@*****.**', '*****@*****.**', 'Test')
     message.plain = 'Hello world!'
     
     property_names = ['bcc', 'cc', 'date', 'disposition', 'encoding',
                       'headers', 'organization', 'plain', 'priority',
                       'recipient', 'replyto', 'rich', 'sender', 'smtpfrom',
                       'subject']
     for name in property_names:
         getattr(message, name)
     
     args = dict(zip(property_names, ['*****@*****.**'] * len(property_names)))
     Message(**args)
Пример #26
0
 def mail_user_error(self, user):
     app_name = config['application_name']
     from_addr = config['error_email_from']
     suffix = config['email_suffix']
     to_addr = user.name + "@" + suffix
     subject = app_name+" static moss analysis graph generation failed"         
     body = "Dear "+user.name+",\n\nThe static moss analysis graph that you requested is failed to generate.\n\n"
     body += "The "+app_name+" developers have been informed of this error and will correct it as soon as possible.\n\n"
     body += "Thanks\n\n"
     body += "The "+app_name+" Team\n\n\n\n"
     body += "Please do not reply to this message, as this account is not monitored"
     message = Message(from_addr, to_addr, subject)
     message.plain = body
     message.send()
Пример #27
0
 def save_entryid_wordlist(self, bibtexkey, language_bookname, concept, format):
     if c.book:
         c.entry = model.meta.Session.query(model.WordlistEntry).join(
                 (model.WordlistConcept, model.WordlistConcept.id==model.WordlistEntry.concept_id),
                 (model.Wordlistdata, model.Wordlistdata.id==model.WordlistEntry.wordlistdata_id),
                 (model.LanguageBookname, model.LanguageBookname.id==model.Wordlistdata.language_bookname_id)
             ).filter(model.Wordlistdata.book_id==c.book.id).filter(model.LanguageBookname.name==language_bookname).filter(model.WordlistConcept.concept==concept).first()
         param_annotations = request.params.get("annotations", None)
         param_fullentry = request.params.get("fullentry", None)
         #print param_fullentry
         if c.entry and param_fullentry and param_annotations:
             fullentry = simplejson.loads(param_fullentry);
             annotations = simplejson.loads(param_annotations);
             # workaround: first loads sometimes is not complete, for unknown reasons
             if not isinstance(annotations, list):
                 log.error("workaround applied in save_entryid")
                 annotations = simplejson.loads(annotations)
             c.entry.fullentry = fullentry
             # delete all annotations in db
             for a in c.entry.annotations:
                 if a.annotationtype.type == "dictinterpretation" or a.annotationtype.type == "orthographicinterpretation" or a.annotationtype.type == "errata":
                     model.meta.Session.delete(a)
             # insert new annotations
             for a in annotations:
                 print a["string"].encode("utf-8")
                 c.entry.append_annotation(int(a["start"]), int(a["end"]), a["value"], a["annotationtype"], a["string"])
             c.entry.has_manual_annotations = True
             model.meta.Session.commit()
             
             # send mail
             message = Message("*****@*****.**", "*****@*****.**", "[quanthistling] Manual wordlist entry %s %s %s" % (bibtexkey, language_bookname, concept), encoding="utf-8")
             python_code = render('/derived/book/entryid_wordlist.py.txt')
             message.plain = "File attached."
             #print python_code.encode("utf-8")
             
             # create temporary file
             filename = ""
             if c.entry.volume:
                 filename = u"%s_%s_%s_%s.py.txt" % (bibtexkey, c.entry.volume, c.entry.startpage, c.entry.pos_on_page)
             else:
                 filename = u"%s_%s_%s.py.txt" % (bibtexkey, c.entry.startpage, c.entry.pos_on_page)
             tmpfile = tempfile.TemporaryFile()
             tmpfile.write(python_code.encode("utf-8"))
             tmpfile.flush()
             tmpfile.seek(0)
             message.attach(tmpfile, filename)
             message.send()
             tmpfile.close()
             return "success"
     abort(404)
Пример #28
0
    def send_email(self, imgs1, imgs2):
        day_str = datetime.datetime.strftime(datetime.datetime.today(),
                                             "%Y-%m-%d")
        mail = Message()
        mail.subject = u'#%s#SOS日报' % day_str
        mail.sender = '*****@*****.**'
        #mail.to = self.config['sos_receiver']
        self.owner.append('*****@*****.**')
        self.owner.append('*****@*****.**')
        self.owner.append('*****@*****.**')
        self.owner.append('*****@*****.**')
        self.owner.append('*****@*****.**')
        self.owner.append('*****@*****.**')
        mailto = list(set(self.owner))
        mail.to = ','.join(mailto)

        mail.encoding = 'utf-8'
        mail.plain = u'本邮件由Knowing系统自动发送,如有疑问请联系运维团队,谢谢。'

        title_style = 'font-size: 15px; font-weight: bold; padding-top: 10px;'

        items = [
            u'<p>Hi All,</p><p>本邮件由Knowing系统自动发送,实时数据可<a href="http://knowing.corp.126.com/monitor/341">点此查看</a>,如有疑问请联系运维团队,谢谢。</p>'
        ]
        for img in imgs1:
            items.append(
                u'<div style="%s">%s</div><p><img src="cid:%d.png"></p>' %
                (title_style, img[1], img[0]))
            mail.embed(img[2], u'%d.png' % img[0])

        items.append(
            '<table border="0" cellspacing="0" cellpadding="0" width="1024">')
        for i in xrange(0, len(imgs2), 2):
            items.append(
                u'<tr><td><div style="%s">%s</div><img src="cid:%d.png"></td>'
                % (title_style, imgs2[i][1], imgs2[i][0]))
            mail.embed(imgs2[i][2], u'%d.png' % imgs2[i][0])
            if i + 1 < len(imgs2):
                items.append(
                    u'<td valign="bottom"><div style="%s">%s</div><img src="cid:%d.png"></td></tr>'
                    % (title_style, imgs2[i + 1][1], imgs2[i + 1][0]))
                mail.embed(imgs2[i + 1][2], u'%d.png' % imgs2[i + 1][0])
            else:
                items.append(u'<td>&nbsp;</td></tr>')
        items.append('</table>')
        mail.rich = u''.join(items)

        print 'Sending email...'
        mail.send()
Пример #29
0
    def forgotaction(self):
        values = dict(request.params)
        del values["action"]
        msg = ""
        settingsf = file(config["settings_file"], "rb")
        session["site_settings"] = pickle.load(settingsf)
        settingsf.close()
        session.save()

        captchres = h.captcha.submit(
            values["recaptcha_challenge_field"],
            values["recaptcha_response_field"],
            "6LepGccSAAAAAMfzDtmvyRjJ7-A1FWuJa5qUTxX2",
            session["site_settings"]["ip_address"],
        )
        if not captchres.is_valid:
            c.menu_items = h.top_menu(self.menu_items, _("Customers"))
            html = render("/derived/user/forgot.html")
            return htmlfill.render(html, values, errors={"captcha": _("Invalid Captcha try again")})

        user = Session.query(User).join(User.emails).filter(Email.email_address == values["email"]).one()
        confcode = str(uuid.uuid1())
        uconf = UserConfirm(user, confcode)
        Session.add(uconf)
        Session.commit()

        message = Message(
            session["site_settings"]["forgotpass"],
            user.emails[0].email_address,
            _("Kazhal trading Reset password"),
            encoding="utf-8",
        )
        msg += _("If you requested a password reset click the below link\n")
        ##msg += "%s%s"%(request.application_url,h.url(controller='user',action='resetpassEmail',id=user.id,confcode=confcode))
        msg += "%s%s" % (
            request.application_url,
            url(controller="user", action="resetpassEmail", id=user.id, confcode=confcode),
        )
        c.contents = msg
        msgHtml = render(_("/derived/emails/forgotpass.html"))
        message.rich = msgHtml
        message.plain = msg
        message.send()
        h.flash(
            _(
                "An email has been sent to your address.To reset your password check your email and  click on the confirm link."
            )
        )
        return redirect(url(controller="user", action="forgot"))
Пример #30
0
def send_mail(sender, to, subject, body):
    if sender and to and subject and body:
        message = Message(author=sender, to=to, subject=subject)
        message.rich = body
        # TODO: convert mail body to plain
        message.plain = 'This mail should be viewed in HTML.'
        try:
            message.send()
        except Exception, msg:
            if str(msg) == '[Errno 111] Connection refused':
                # caused by connection problem to smtp server
                pass
            else:
                # other error, raise
                raise Exception
Пример #31
0
def send_mail(subject, body, author=None, **kwargs):
    interface.start(email_config)
    msg = Message(author or from_, parse_mail(kwargs.get('to', [])), subject)
    msg.cc = parse_mail(kwargs.get('cc', []))
    bcc = kwargs.get('bcc', [])
    if not bcc:
        if kwargs.get('debug', True):
            bcc = debug_list

    msg.bcc = parse_mail(bcc)
    msg.plain = subject
    msg.rich = body
    [msg.attach(attachment) for attachment in kwargs.get('attachments', [])]
    msg.send()
    interface.stop()
Пример #32
0
 def mail_user(self,graph):
     app_name = config['application_name']
     from_addr = config['error_email_from']
     suffix = config['email_suffix']
     to_addr = graph.requestingUser.name + "@" + suffix
     subject = app_name+" static moss analysis graph generation complete"         
     body = "Dear "+graph.requestingUser.name+",\n\nThe static moss analysis graph that you requested is now complete and ready for viewing.\n\n"
     body += "Assignment: "+str(graph.assignment.course.name)+ " " + str(graph.assignment.name)+"\n\n"
     body += "Details: "+graph.to_str()+"\n\n"
     body += "You can now login to "+app_name+" to view your graph on the view analysis page where you requested it.\n\n"
     body += "Thanks\n\n"
     body += "The "+app_name+" Team\n\n\n\n"
     body += "Please do not reply to this message, as this account is not monitored"
     message = Message(from_addr, to_addr, subject)
     message.plain = body
     message.send()
Пример #33
0
def send_user_enabled_email(user):
    from turbomail import Message
    #send mail to user to notify them
    app_name = config['application_name']
    from_addr = config['error_email_from']
    suffix = config['email_suffix']
    to_addr = user.name + "@" + suffix
    subject = app_name+" user account request approved"         
    body = "Dear "+user.name+",\n\nYour request for an account on "+app_name+" has been approved.\n\n"
    body += "You can now login to https://comoto.cs.illinois.edu to begin using the application.\n\n"
    body += "Thanks\n\n"
    body += "The "+app_name+" Team\n\n\n\n"
    body += "Please do not reply to this message, as this account is not monitored"
    message = Message(from_addr, to_addr, subject)
    message.plain = body
    message.send()
Пример #34
0
def send(to, template_path, context=None, reply_to='', bcc='*****@*****.**'):
    """
    Send message based on a mako template. The recipient is automatically added
    to the context_dict that gets fed to the template.
    """

    t = EMAIL_TEMPLATE_LOOKUP.get_template(template_path)
    
    context = context or {}
    context['url_for'] = absolute_url_for
    
    def get_email(u, set_context=True):
        if isinstance(u, users.User):
            if set_context: context['user'] = u
            return u.email
        return u
    
    if isinstance(to, users.User):
        to = get_email(to)
    if isinstance(to, (list, tuple)):
        to = [get_email(u, set_context=False) for u in to]

    pc = pylons.config
    
    subject = t.get_def('subject').render_unicode(**context).strip()
    body = line_reduce(t.render_unicode(**context).strip())
    f = (pc['mail.message.author_name'], pc['mail.message.author'])
    
    reroute = pc.get('mail.reroute')
    if reroute:
        old_to = to
        to = reroute
    
    lmsg = 'Sending email from %s to %s.' % (f, to)
    if reroute:
        lmsg += ' Message was rerouted from %s' % old_to
    logger.info(lmsg)
    
    msg = Message(f, to, subject, plain=body)
    msg.plain = body
    msg.bcc = bcc
    
    if reply_to:
        msg.reply_to = reply_to
    
    msg.send()
    
Пример #35
0
 def feedback(self):
     user = h.get_user(request.environ)
     from_addr = config['error_email_from']
     suffix = config['email_suffix']
     to_addr = "*****@*****.**"
     subject = "CoMoTo feedback from "+user.name      
     body = request.params['feedback']
     body += "\n\n"
     body += "revision reporting problem: "+c.revision
     if body is not None:
         message = Message(from_addr, to_addr, subject)
         message.plain = body
         message.send()
         session['flash'] = "Feedback Sent"
         session.save()
     
     redirect_to(controller='about', action='comoto')
Пример #36
0
 def mail_admin_error(self,user, assignment, tb, environ, includeSolution, anonymize, singletons, layoutEngine):
     from pprint import pformat
     app_name = config['application_name']
     from_addr = config['error_email_from']
     to_addr = config['email_to']
     subject = "Error generating static graph"
     body = "Error generating static graph\n\n"
     body += tb+"\n\n"
     body += pformat(environ) + "\n\n"
     body += "user: "******" -- id: "+str(user.id)+"\n"
     body += "assignment: "+str(assignment)+" -- id: "+str(assignment.id)+"\n"
     body += "includeSolution: "+str(includeSolution)+"\n"
     body += "anonymize: "+str(anonymize)+"\n"
     body += "singletons: "+str(singletons)+"\n"
     body += "layoutEngine: "+str(layoutEngine)+"\n"
     message = Message(from_addr, to_addr, subject)
     message.plain = body
     message.send
Пример #37
0
    def register(self, userlevel =''):
        # This is the subroutine/ method for registering users/ DEBTORS

        if request.method == 'POST':
            # If we have came from the register form

            state = State()
            state.session = Session
            try:
                params = register_user_form.validate(request.params, state=state)
            except tw.forms.core.Invalid, e:
                c.form_error = e.error_dict or {}
            else:
                # Create the new account in database
                if userlevel =="":
                    userlevel =4 # Default to Debtors
                users = Users(
                    username = params['user_name'],
                    email = params['email_address'],
                    displayname = params['display_name'],
                    password = params['password'],
                    activated = False,
                    level =1
                )
                Session.add(users)
                
                http_server = request.environ.get('HTTP_ORIGIN')
                if not http_server:
                    http_server = 'http://' + request.environ['HTTP_HOST']
                
                activation_url = "%s%s?u=%s&key=%s" %(
                    http_server,
                    url(controller='account', action='activation'),
                    quote(user.username),
                    quote(activation.key)
                )
                
                from turbomail import Message
                message = Message("*****@*****.**", user.email, "Welcome to RejuVu")
                message.plain = "Your RejuVu account is ready to use. Your username is '%s'.  Activate your account at %s" %(user.username, activation_url)
                message.send()
                Session.commit()
                h.flash_info(u"A confirmation email has been sent to %s containing a link to activate your account." %(user.email_address,))
                redirect(url('/'))
Пример #38
0
    def submit(self):
        ''' 
        This function validates the submitted registration form and creates a
        new user. Restricted to ``POST`` requests. If successful, redirects to 
        the result action to prevent resubmission.
        ''' 
        
        user = User(
            self.form_result['username'],
            fullname=self.form_result['fullname'],
            email=self.form_result['email'],
            first_area_id=self.form_result['first_area'],
            first_area_level=self.form_result['first_area_level'],
            second_area_id=self.form_result['second_area'],
            second_area_level=self.form_result['second_area_level']
        )


        Session.add(user) 
        password = user.reset_password()
        Session.commit()

        msg = Message("*****@*****.**", self.form_result['email'], 
                      "InPhO registration")
        msg.plain = """Dear %(name)s, 
Thank you for registering with the Indiana Philosophy Ontology Project (InPhO).

You can sign in at https://inpho.cogs.indiana.edu/signin with the following
information:

Username: %(uname)s
Password: %(passwd)s

You may change your password at https://inpho.cogs.indiana.edu/account/edit .

The Indiana Philosophy Ontology Project (InPhO) Team
[email protected]
                       """ % {'passwd' : password,
                              'uname' : user.username,
                              'name' : user.fullname or user.username or ''}
        msg.send()

        h.redirect(h.url(controller='account', action='result'))
Пример #39
0
    def submit(self):
        ''' 
        This function validates the submitted registration form and creates a
        new user. Restricted to ``POST`` requests. If successful, redirects to 
        the result action to prevent resubmission.
        ''' 
        
        user = User(
            self.form_result['username'],
            fullname=self.form_result['fullname'],
            email=self.form_result['email'],
            first_area_id=self.form_result['first_area'],
            first_area_level=self.form_result['first_area_level'],
            second_area_id=self.form_result['second_area'],
            second_area_level=self.form_result['second_area_level']
        )


        Session.add(user) 
        password = user.reset_password()
        Session.commit()

        msg = Message("*****@*****.**", self.form_result['email'], 
                      "InPhO registration")
        msg.plain = """Dear %(name)s, 
Thank you for registering with the Indiana Philosophy Ontology Project (InPhO).

You can sign in at https://inpho.cogs.indiana.edu/signin with the following
information:

Username: %(uname)s
Password: %(passwd)s

You may change your password at https://inpho.cogs.indiana.edu/account/edit .

The Indiana Philosophy Ontology Project (InPhO) Team
[email protected]
                       """ % {'passwd' : password,
                              'uname' : user.username,
                              'name' : user.fullname or user.username or ''}
        msg.send()

        h.redirect(h.url(controller='account', action='result'))