Пример #1
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.')
Пример #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 _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()
Пример #5
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'))
Пример #6
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
Пример #7
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()
Пример #8
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()
Пример #9
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()
    
Пример #10
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'))
Пример #11
0
 def save_contact_form(self):
     '''Sends the form for sending contact emails if POSTed data validates;
     else redisplays the form with the error messages.
     '''
     controls = self.request.params.items()
     try:
         appstruct = d.Form(contact_form_schema,
                            buttons=('submit', ),
                            action=self.url('contact'),
                            formid='contactform').validate(controls)
     # If form does not validate, returns the form
     except d.ValidationFailure as e:
         return dict(pagetitle=_("Contact"), contact_form=e.render())
     # Form validation passes, so send the e-mail
     msg = Message(author=(appstruct['name'], appstruct['email']),
                   subject=appstruct['subject'],
                   plain=appstruct['message'])
     msg.send()
     self.request.override_renderer = 'contact_successful.genshi'
     return dict()
Пример #12
0
    def comment(self):
        id = self.request.matchdict.get("map_id")
        map = Map.get(id)
        if map is None:
            return HTTPNotFound()

        # read the map author's email address from LDAP
        author = self.get_user_info(map.user_login)

        comment = self.request.params.get('comment')

        if self.request.params.get('name') and self.request.params.get('mail'):
            # feedback anonymous user
            feedback_name = self.request.params.get('name')
            feedback_mail = self.request.params.get('mail')
        else:
            # feedback loggedin user
            user = self.get_user_info(self.request.user.username)
            feedback_name = user[0]
            feedback_mail = user[1]
        try:
            message = Message(
                author='*****@*****.**',
                to=author[1],
                bcc='*****@*****.**',
                subject=(u'comment_email_subject')
                    % {'title': map.title +
                       " ( http://map.geoportail.lu/?map_id="+map.uuid+" ) ",
                       'feedback_name': feedback_name,
                       'feedback_mail': feedback_mail},
                plain=comment)
        except:
            traceback.print_exc(file=sys.stdout)
            return HTTPNotFound()
        message.encoding = 'utf-8'
        message.send()
        return {'success': True}