Пример #1
0
    def test_attach_as_body_and_html_latin1(self):
        from pyramid_mailer.message import Message
        from pyramid_mailer.message import Attachment

        charset = 'iso-8859-1'
        text_encoded = b'LaPe\xf1a'
        text = text_encoded.decode(charset)
        html_encoded = b'<p>' + text_encoded + b'</p>'
        html_text = html_encoded.decode(charset)
        transfer_encoding = 'quoted-printable'
        body = Attachment(data=text, transfer_encoding=transfer_encoding)
        html = Attachment(data=html_text, transfer_encoding=transfer_encoding)
        msg = Message(
            subject="testing",
            sender="*****@*****.**",
            recipients=["*****@*****.**"],
            body=body,
            html=html,
        )
        message = msg.to_message()
        body_part, html_part = message.get_payload()

        self.assertEqual(body_part['Content-Type'],
                         'text/plain; charset="iso-8859-1"')
        self.assertEqual(body_part['Content-Transfer-Encoding'],
                         transfer_encoding)
        payload = body_part.get_payload()
        self.assertEqual(payload, _qencode(text_encoded).decode('ascii'))

        self.assertEqual(html_part['Content-Type'],
                         'text/html; charset="iso-8859-1"')
        self.assertEqual(html_part['Content-Transfer-Encoding'],
                         transfer_encoding)
        payload = html_part.get_payload()
        self.assertEqual(payload, _qencode(html_encoded).decode('ascii'))
Пример #2
0
def notify_user_activation(user, request=None):
    """Send mail for user activation"""
    security = query_utility(ISecurityManager)
    settings = INotificationSettings(security)
    if not settings.enable_notifications:  # pylint: disable=assignment-from-no-return
        LOGGER.info("Security notifications disabled, no message sent...")
        return
    mailer = settings.get_mailer()  # pylint: disable=assignment-from-no-return
    if mailer is None:
        LOGGER.warning("Can't find mailer utility, no notification message sent!")
        return
    if request is None:
        request = check_request()
    translate = request.localizer.translate
    i18n_settings = II18n(settings)
    message_text, template_name = None, None
    if user.self_registered:
        # pylint: disable=assignment-from-no-return
        message_text = i18n_settings.query_attribute('registration_template', request=request)
        if not message_text:
            template_name = 'templates/register-message.pt'
    elif user.wait_confirmation:
        # pylint: disable=assignment-from-no-return
        message_text = i18n_settings.query_attribute('confirmation_template', request=request)
        if not message_text:
            template_name = 'templates/register-info.pt'
    site = get_parent(request.context, ISite)
    if message_text is not None:
        message_text = message_text.format(**user.to_dict())
    elif template_name is not None:
        message_text = render(template_name, request=request, value={
            'user': user,
            'site': site,
            'settings': settings
        })
    html_body = render('templates/register-body.pt', request=request, value={
        'user': user,
        'site': site,
        'settings': settings,
        'message': message_text
    })
    message = Message(
        subject=translate(_("{prefix}Please confirm registration")).format(
            prefix="{prefix} ".format(prefix=settings.subject_prefix)
            if settings.subject_prefix else ''),
        sender='{name} <{email}>'.format(name=settings.sender_name,
                                         email=settings.sender_email),
        recipients=("{firstname} {lastname} <{email}>".format(firstname=user.firstname,
                                                              lastname=user.lastname,
                                                              email=user.email),),
        html=Attachment(data=html_body,
                        content_type='text/html; charset=utf-8',
                        disposition='inline',
                        transfer_encoding='quoted-printable'),
        body=Attachment(data=html_to_text(html_body),
                        content_type='text/plain; charset=utf-8',
                        disposition='inline',
                        transfer_encoding='quoted-printable'))
    mailer.send(message)
Пример #3
0
    def test_attach_as_body_and_html_utf8(self):
        from pyramid_mailer.message import Message
        from pyramid_mailer.message import Attachment

        charset = 'utf-8'
        # greek small letter iota with dialtyika and tonos; this character
        # cannot be encoded to either ascii or latin-1, so utf-8 is chosen
        text_encoded =  b'\xce\x90'
        text = text_encoded.decode(charset)
        html_encoded = b'<p>' + text_encoded + b'</p>'
        html_text = html_encoded.decode(charset)
        transfer_encoding = 'quoted-printable'
        body = Attachment(
            data=text,
            transfer_encoding=transfer_encoding,
            )
        html = Attachment(
            data=html_text,
            transfer_encoding=transfer_encoding,
            )
        msg = Message(
            subject="testing",
            sender="*****@*****.**",
            recipients=["*****@*****.**"],
            body=body,
            html=html,
            )
        message = msg.to_message()
        body_part, html_part = message.get_payload()

        self.assertEqual(
            body_part['Content-Type'],
            'text/plain; charset="utf-8"'
            )
        
        self.assertEqual(
            body_part['Content-Transfer-Encoding'],
            transfer_encoding
            )

        payload = body_part.get_payload()
        self.assertEqual(
            payload,
            _qencode(text_encoded).decode('ascii')
            )

        self.assertEqual(
            html_part['Content-Type'],
            'text/html; charset="utf-8"'
            )
        self.assertEqual(
            html_part['Content-Transfer-Encoding'],
            transfer_encoding
            )
        payload = html_part.get_payload()
        self.assertEqual(
            payload,
            _qencode(html_encoded).decode('ascii')
            )
Пример #4
0
def mailer_send(subject="!",
                sender=None,
                recipients=[],
                body=None,
                html=None,
                attachments=[]):
    try:
        request = get_current_request()
        if sender is None:
            sender = request.registry.settings['lac.admin_email']

        mailer = get_mailer(request)
        message = Message(subject=subject,
                          sender=sender,
                          recipients=recipients,
                          body=body,
                          html=html)
        for attachment in attachments:
            attachment = Attachment(attachment.title, attachment.mimetype,
                                    attachment)
            message.attach(attachment)

        if transaction.get().status == Status.COMMITTED:
            mailer.send_immediately(message)
        else:
            mailer.send(message)

    except Exception:
        pass
Пример #5
0
    def test_to_message_multipart_with_b64encoding(self):
        from pyramid_mailer.message import Message, Attachment

        response = Message(recipients=['To'],
                           sender='From',
                           subject='Subject',
                           body='Body',
                           html='Html')

        this = os.path.abspath(__file__)
        with open(this, 'rb') as data:
            attachment = Attachment(
                filename=this,
                content_type='application/octet-stream',
                disposition='disposition',
                transfer_encoding='base64',
                data=data,
            )
            response.attach(attachment)
            message = response.to_message()
            payload = message.get_payload()[1]
        self.assertEqual(payload.get('Content-Transfer-Encoding'), 'base64')
        self.assertEqual(
            payload.get_payload(),
            _bencode(self._read_filedata(this, 'rb')).decode('ascii'))
Пример #6
0
def accountant_mail(appstruct):
    """
    this function returns a message object for the mailer

    it consists of a mail body and an attachment attached to it
    """
    unencrypted = make_mail_body(appstruct)
    #print("accountant_mail: mail body: \n%s") % unencrypted
    #print("accountant_mail: type of mail body: %s") % type(unencrypted)
    encrypted = encrypt_with_gnupg(unencrypted)
    #print("accountant_mail: mail body (enc'd): \n%s") % encrypted
    #print("accountant_mail: type of mail body (enc'd): %s") % type(encrypted)

    message_recipient = appstruct['message_recipient']

    message = Message(subject="[C3S] Yes! a new member",
                      sender="*****@*****.**",
                      recipients=[message_recipient],
                      body=encrypted)
    #print("accountant_mail: csv_payload: \n%s") % generate_csv(appstruct)
    #print(
    #    "accountant_mail: type of csv_payload: \n%s"
    #) % type(generate_csv(appstruct))
    csv_payload_encd = encrypt_with_gnupg(generate_csv(appstruct))
    #print("accountant_mail: csv_payload_encd: \n%s") % csv_payload_encd
    #print(
    #    "accountant_mail: type of csv_payload_encd: \n%s"
    #) % type(csv_payload_encd)

    attachment = Attachment("C3S-SCE-AFM.csv.gpg",
                            "application/gpg-encryption", csv_payload_encd)
    message.attach(attachment)

    return message
Пример #7
0
    def test_create_message_with_attachments(self):
        request = testing.DummyRequest()

        attachment = Attachment('foo.txt', 'text/plain', 'test')

        message = create_message(
            request,
            'yithlibraryserver.tests:templates/email_test',
            {
                'name': 'John',
                'email': '*****@*****.**'
            },
            'Testing message',
            ['*****@*****.**'],
            attachments=[attachment],
        )
        self.assertEqual(message.subject, 'Testing message')
        self.assertEqual(
            message.html,
            '<p>Hello John,</p>\n\n<p>this is your email address: [email protected]</p>'
        )
        self.assertEqual(
            message.body,
            'Hello John,\n\nthis is your email address: [email protected]\n')
        self.assertEqual(message.recipients, ['*****@*****.**'])
        self.assertEqual(message.extra_headers, {})
        self.assertEqual(len(message.attachments), 1)
        a = message.attachments[0]
        self.assertEqual(a.filename, 'foo.txt')
        self.assertEqual(a.content_type, 'text/plain')
        self.assertEqual(a.data, 'test')
Пример #8
0
def send_passwords(request, user, preferences_link, backups_link):
    passwords = get_user_passwords(user)
    if not passwords:
        return False

    context = {
        'user': user,
        'preferences_link': preferences_link,
        'backups_link': backups_link,
    }

    today = datetime.date.today()
    attachment = Attachment(get_backup_filename(today), "application/yith",
                            compress(passwords))

    send_email(
        request,
        'yithlibraryserver.backups:templates/email_passwords',
        context,
        "Your Yith Library's passwords",
        [user.email],
        attachments=[attachment],
    )

    return True
Пример #9
0
    def test_data_from_file_obj(self):

        from StringIO import StringIO
        from pyramid_mailer.message import Attachment

        a = Attachment(data=StringIO("foo"))
        self.assert_(a.data == "foo")
Пример #10
0
    def test_attach(self):

        from pyramid_mailer.message import Message
        from pyramid_mailer.message import Attachment

        msg = Message(
            subject="testing",
            recipients=["*****@*****.**"],
            sender='sender',
            body="testing"
            )

        attachment = Attachment(
            data=b"this is a test",
            content_type="text/plain"
            )

        msg.attach(attachment)

        a = msg.attachments[0]

        self.assertTrue(a.filename is None)
        self.assertEqual(a.disposition, 'attachment')
        self.assertEqual(a.content_type, "text/plain")
        self.assertEqual(a.data, b"this is a test")
Пример #11
0
    def test_to_message_multipart(self):
        from pyramid_mailer.message import Message, Attachment
        response = Message(recipients=['To'],
                           sender='From',
                           subject='Subject',
                           body='Body',
                           html='Html')
        attachment_type = 'text/html'
        this = os.path.abspath(__file__)
        attachment = Attachment(filename=this,
                                content_type=attachment_type,
                                data='data'.encode('ascii'),
                                disposition='disposition')
        response.attach(attachment)
        message = response.to_message()
        self.assertEqual(message['Content-Type'], 'multipart/mixed')

        payload = message.get_payload()
        self.assertEqual(len(payload), 2)
        self.assertEqual(payload[0]['Content-Type'], 'multipart/alternative')
        self.assertTrue(payload[1]['Content-Type'].startswith(attachment_type))

        alt_payload = payload[0].get_payload()
        self.assertTrue(
            alt_payload[0]['Content-Type'].startswith('text/plain'))
        self.assertTrue(alt_payload[1]['Content-Type'].startswith('text/html'))
Пример #12
0
def send_salary_sheet(request,
                      email,
                      company_id,
                      filename,
                      filepath,
                      force=False,
                      message=None,
                      subject=None):
    """
    Send a salarysheet to the given company's e-mail

    :param obj request: A pyramid request object
    :param str company_mail: The mail to send it to
    :param int company_id: The id of the associated company
    :param str filepath: The path to the filename
    :param bool force: Whether to force sending this file again
    :param str message: The mail message
    :param str subject: The mail subject
    :returns: A MailHistory instance
    :TypeError UndeliveredMail: When the company has no mail
    :TypeError MailAlreadySent: if the file has
        already been sent and no force option was passed
    """
    filebuf = file(filepath, 'r')
    filedatas = filebuf.read()

    if not force and check_if_mail_sent(filedatas, company_id):
        log.warn(u"Mail already sent : mail already sent")
        raise MailAlreadySent(u"Mail already sent")

    filebuf.seek(0)

    if email is None:
        log.warn(
            u"Undelivered email : no mail provided for company {0}".format(
                company_id))
        raise UndeliveredMail(
            u"no mail provided for company {0}".format(company_id))
    else:
        log.info('Sending the file %s' % filepath)
        log.info("Sending it to %s" % email)
        attachment = Attachment(filename, "application/pdf", filebuf)

        subject = subject or SALARYSHEET_MAIL_SUBJECT
        message = message or SALARYSHEET_MAIL_MESSAGE

        send_mail(
            request,
            email,
            message,
            subject,
            attachment,
        )
        return store_sent_mail(filepath, filedatas, company_id)
Пример #13
0
def send_mail(request):

    mailer = Mailer( host='smtp.gmail.com',
                     port=587, #???
                     username='******',
                     password='******',
                     tls=True)

    if request.params.get('email') is not None:
        email = request.params['email']
    else:
        email = "the email does not exist"

    send_topic = 'Welcome to join us for the seminar'
    send_er = '*****@*****.**'
    send_to = [email]
    send_this = "Thank you for signing up at our website..."

    message = Message( subject = send_topic,
                       sender = send_er,
                       recipients = send_to,
                       body = send_this )

    here = os.path.dirname(__file__)
    att1 = os.path.join(here, 'static','velur1.pdf')
    attachment = Attachment(att1, "image/jpg",
                        open(att1, "rb"))

    message.attach(attachment)

    here = os.path.dirname(__file__)
    att2 = os.path.join(here, 'static','velur2.pdf')
    attachment = Attachment(att2, "image/jpg",
                        open(att2, "rb"))

    message.attach(attachment)

   # mailer.send_immediately(message, fail_silently=False)
    mailer.send(message)
    return Response(email)
Пример #14
0
def mail_submission(context, request, appstruct):
    mailer = get_mailer(request)
    message = Message(subject=appstruct['subject'],
                      sender=appstruct['name'] + ' <' + appstruct['sender'] +
                      '>',
                      extra_headers={'X-Mailer': "kotti_contactform"},
                      recipients=[context.recipient],
                      body=appstruct['content'])
    if 'attachment' in appstruct and appstruct['attachment'] is not None:
        message.attach(
            Attachment(filename=appstruct['attachment']['filename'],
                       content_type=appstruct['attachment']['mimetype'],
                       data=appstruct['attachment']['fp']))
    mailer.send(message)
Пример #15
0
def send_mail(request):

    mailer = Mailer(
        host='smtp.gmail.com',
        port=587,  #???
        username='******',
        password='******',
        tls=True)

    if request.params.get('email') is not None:
        email = request.params['email']
    else:
        email = "the email does not exist"

    send_topic = 'Welcome to join us for the seminar'
    send_er = '*****@*****.**'
    send_to = [email]
    send_this = "Thank you for signing up at our website..."

    message = Message(subject=send_topic,
                      sender=send_er,
                      recipients=send_to,
                      body=send_this)

    attachment = Attachment("velur1.pdf", "image/jpg",
                            open("velur1.pdf", "rb"))

    message.attach(attachment)

    attachment = Attachment("velur2.pdf", "image/jpg",
                            open("velur2.pdf", "rb"))

    message.attach(attachment)

    # mailer.send_immediately(message, fail_silently=False)
    mailer.send(message)
    return Response(email)
Пример #16
0
def accountant_mail(appstruct):

    unencrypted = make_mail_body(appstruct)

    message = Message(subject="[c3s] Yes! a new letter of intent",
                      sender="*****@*****.**",
                      recipients=["*****@*****.**"],
                      body=unicode(encrypt_with_gnupg((unencrypted))))

    attachment = Attachment("foo.gpg", "application/gpg-encryption",
                            unicode(encrypt_with_gnupg(u"foo to the bar!")))
    # TODO: make attachment contents a .csv with the data supplied.
    message.attach(attachment)

    return message
Пример #17
0
 def test_to_message_with_html_attachment(self):
     from pyramid_mailer.message import Message, Attachment
     response = Message(
         recipients=['To'],
         sender='From',
         subject='Subject',
         body='Body',
     )
     attachment = Attachment(data=b'data', content_type='text/html')
     response.attach(attachment)
     message = response.to_message()
     att_payload = message.get_payload()[1]
     self.assertEqual(att_payload['Content-Type'],
                      'text/html; charset="us-ascii"')
     self.assertEqual(att_payload.get_payload(),
                      _bencode(b'data').decode('ascii'))
Пример #18
0
 def test_to_message_with_binary_attachment(self):
     from pyramid_mailer.message import Message, Attachment
     response = Message(
         recipients=['To'],
         sender='From',
         subject='Subject',
         body='Body',
     )
     data = os.urandom(100)
     attachment = Attachment(
         data=data,
         content_type='application/octet-stream',
     )
     response.attach(attachment)
     message = response.to_message()
     att_payload = message.get_payload()[1]
     self.assertEqual(att_payload['Content-Type'],
                      'application/octet-stream')
     self.assertEqual(att_payload.get_payload(),
                      _bencode(data).decode('ascii'))
Пример #19
0
    def test_attach(self):

        from pyramid_mailer.message import Message
        from pyramid_mailer.message import Attachment

        msg = Message(subject="testing",
                      recipients=["*****@*****.**"],
                      body="testing")

        msg.attach(Attachment(data="this is a test",
                              content_type="text/plain"))

        a = msg.attachments[0]

        self.assert_(a.filename is None)
        self.assert_(a.disposition == 'attachment')
        self.assert_(a.content_type == "text/plain")
        self.assert_(a.data == "this is a test")

        response = msg.get_response()

        self.assert_(len(response.attachments) == 1)
Пример #20
0
    def test_data_from_string(self):

        from pyramid_mailer.message import Attachment

        a = Attachment(data="foo")
        self.assert_(a.data == "foo")
Пример #21
0
def client_register(request):
	if authenticated_userid(request):
		return HTTPSeeOther(location=request.route_url('access.cl.home'))
	cur_locale = locale_neg(request)
	loc = request.localizer
	cfg = request.registry.settings
	comb_js = asbool(cfg.get('netprofile.client.combine_js', False))
	can_reg = asbool(cfg.get('netprofile.client.registration.enabled', False))
	must_verify = asbool(cfg.get('netprofile.client.registration.verify_email', True))
	must_recaptcha = asbool(cfg.get('netprofile.client.registration.recaptcha.enabled', False))
	min_pwd_len = int(cfg.get('netprofile.client.registration.min_password_length', 8))
	rate_id = int(cfg.get('netprofile.client.registration.rate_id', 1))
	state_id = int(cfg.get('netprofile.client.registration.state_id', 1))
	maillogin = asbool(cfg.get('netprofile.client.email_as_username', False))
	csrf = request.POST.get('csrf', '')
	errors = {}
	if not can_reg:
		return HTTPSeeOther(location=request.route_url('access.cl.login'))
	if must_recaptcha:
		rc_private = cfg.get('netprofile.client.recaptcha.private_key')
		rc_public = cfg.get('netprofile.client.recaptcha.public_key')
		if (not rc_private) or (not rc_public):
			# TODO: log missing reCAPTCHA keys
			must_recaptcha = False
	if 'submit' in request.POST:
		sess = DBSession()
		if csrf != request.get_csrf():
			errors['csrf'] = _('Error submitting form')
		elif must_recaptcha:
			try:
				rcresp = verify_recaptcha(rc_private, request)
			except ValueError as e:
				errors['recaptcha'] = str(e)
			else:
				if rcresp and not rcresp.valid:
					errors['recaptcha'] = rcresp.text()
		if len(errors) == 0:
			login = request.POST.get('user', '')
			passwd = request.POST.get('pass', '')
			passwd2 = request.POST.get('pass2', '')
			email = request.POST.get('email', '')
			name_family = request.POST.get('name_family', '')
			name_given = request.POST.get('name_given', '')
			name_middle = request.POST.get('name_middle', '')
			l = len(email)
			if (l == 0) or (l > 254):
				errors['email'] = _('Invalid field length')
			elif not _re_email.match(email):
				errors['email'] = _('Invalid e-mail format')
			if maillogin:
				login = email
			else:
				l = len(login)
				if (l == 0) or (l > 254):
					errors['user'] = _('Invalid field length')
				elif _re_login.match(login):
					errors['user'] = _('Invalid character used in username')
			l = len(passwd)
			if l < min_pwd_len:
				errors['pass'] = _('Password is too short')
			elif l > 254:
				errors['pass'] = _('Password is too long')
			if passwd != passwd2:
				errors['pass2'] = _('Passwords do not match')
			l = len(name_family)
			if (l == 0) or (l > 254):
				errors['name_family'] = _('Invalid field length')
			l = len(name_given)
			if (l == 0) or (l > 254):
				errors['name_given'] = _('Invalid field length')
			l = len(name_middle)
			if l > 254:
				errors['name_middle'] = _('Invalid field length')
			if 'user' not in errors:
				# XXX: currently we check across all entity types.
				login_clash = sess.query(func.count('*'))\
					.select_from(Entity)\
					.filter(Entity.nick == login)\
					.scalar()
				if login_clash > 0:
					errors['user'] = _('This username is already taken')
		if len(errors) == 0:
			ent = PhysicalEntity()
			ent.nick = login
			ent.email = email
			ent.name_family = name_family
			ent.name_given = name_given
			if name_middle:
				ent.name_middle = name_middle
			ent.state_id = state_id

			stash = Stash()
			stash.entity = ent
			stash.name = loc.translate(_('Primary Account'))

			acc = AccessEntity()
			acc.nick = login
			acc.password = passwd
			acc.stash = stash
			acc.rate_id = rate_id
			acc.state_id = state_id
			ent.children.append(acc)

			sess.add(ent)
			sess.add(stash)
			sess.add(acc)

			if must_verify:
				link_id = int(cfg.get('netprofile.client.registration.link_id', 1))
				rand_len = int(cfg.get('netprofile.client.registration.code_length', 20))
				queue_mail = asbool(cfg.get('netprofile.client.registration.mail_queue', False))
				sender = cfg.get('netprofile.client.registration.mail_sender')

				acc.access_state = AccessState.block_inactive.value
				link = AccessEntityLink()
				link.entity = acc
				link.type_id = link_id

				chars = string.ascii_uppercase + string.digits
				try:
					rng = random.SystemRandom()
				except NotImplementedError:
					rng = random
				link.value = ''.join(rng.choice(chars) for i in range(rand_len))
				link.timestamp = datetime.datetime.now()
				sess.add(link)

				mailer = get_mailer(request)

				tpldef = {
					'cur_loc' : cur_locale,
					'entity'  : ent,
					'stash'   : stash,
					'access'  : acc,
					'link'    : link
				}
				request.run_hook('access.cl.tpldef.register.mail', tpldef, request)
				msg_text = Attachment(
					data=render('netprofile_access:templates/email_register_plain.mak', tpldef, request),
					content_type='text/plain; charset=\'utf-8\'',
					disposition='inline',
					transfer_encoding='quoted-printable'
				)
				msg_html = Attachment(
					data=render('netprofile_access:templates/email_register_html.mak', tpldef, request),
					content_type='text/html; charset=\'utf-8\'',
					disposition='inline',
					transfer_encoding='quoted-printable'
				)
				msg = Message(
					subject=(loc.translate(_('Activation required for user %s')) % login),
					sender=sender,
					recipients=(email,),
					body=msg_text,
					html=msg_html
				)
				if queue_mail:
					mailer.send_to_queue(msg)
				else:
					mailer.send(msg)
			return HTTPSeeOther(location=request.route_url('access.cl.regsent'))
	tpldef = {
		'cur_loc'        : cur_locale,
		'comb_js'        : comb_js,
		'must_verify'    : must_verify,
		'must_recaptcha' : must_recaptcha,
		'min_pwd_len'    : min_pwd_len,
		'maillogin'	 : maillogin,
		'errors'         : {err: loc.translate(errors[err]) for err in errors}
	}
	if must_recaptcha:
		tpldef['rc_public'] = rc_public
	request.run_hook('access.cl.tpldef.register', tpldef, request)
	return tpldef
Пример #22
0
    def test_repoze_sendmail_send_to_queue_functional(self):
        # functest that emulates the interaction between pyramid_mailer and
        # repoze.maildir.add and queuedelivery.send.

        import tempfile
        from email.generator import Generator
        from email.parser import Parser
        from pyramid_mailer.message import Message
        from pyramid_mailer.message import Attachment
        from repoze.sendmail.encoding import cleanup_message
        from repoze.sendmail.delivery import copy_message

        def checkit(msg):
            self.assertEqual(msg['Content-Type'],
                             'text/plain; charset="iso-8859-1"')
            self.assertEqual(msg['Content-Transfer-Encoding'],
                             transfer_encoding)

            payload = msg.get_payload()
            self.assertEqual(payload, expected)

        charset = 'iso-8859-1'
        text_encoded = b'LaPe\xf1a'
        text = text_encoded.decode(charset)
        expected = _qencode(text_encoded).decode('ascii')
        transfer_encoding = 'quoted-printable'
        body = Attachment(data=text, transfer_encoding=transfer_encoding)
        msg = Message(subject="testing",
                      sender="*****@*****.**",
                      recipients=["*****@*****.**"],
                      body=body)

        # done in pyramid_mailer via mailer/send_to_queue
        msg = msg.to_message()
        msg.as_string()

        checkit(msg)

        # done in repoze.sendmail via delivery/AbstractMailDelivery/send
        cleanup_message(msg)

        checkit(msg)

        # done in repoze.sendmail via
        # delivery/AbstractMailDelivery/createDataManager
        msg_copy = copy_message(msg)

        checkit(msg_copy)

        try:
            # emulate what repoze.sendmail maildir.py/add does
            fn = tempfile.mktemp()
            fd = os.open(fn, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)
            with os.fdopen(fd, 'w') as f:
                writer = Generator(f)
                writer.flatten(msg_copy)

            # emulate what repoze.sendmail.queue _parseMessage does
            with open(fn) as foo:
                parser = Parser()
                reconstituted = parser.parse(foo)
                checkit(reconstituted)

        finally:  # pragma: no cover
            try:
                os.remove(fn)
            except:
                pass
Пример #23
0
def client_restorepass(request):
	if authenticated_userid(request):
		return HTTPSeeOther(location=request.route_url('access.cl.home'))
	did_fail = True
	cur_locale = locale_neg(request)
	loc = request.localizer
	cfg = request.registry.settings
	comb_js = asbool(cfg.get('netprofile.client.combine_js', False))
	can_rp = asbool(cfg.get('netprofile.client.password_recovery.enabled', False))
	change_pass = asbool(cfg.get('netprofile.client.password_recovery.change_password', True))
	must_recaptcha = asbool(cfg.get('netprofile.client.password_recovery.recaptcha.enabled', False))
	maillogin = asbool(cfg.get('netprofile.client.email_as_username', False))

	errors = {}
	if not can_rp:
		return HTTPSeeOther(location=request.route_url('access.cl.login'))
	if must_recaptcha:
		rc_private = cfg.get('netprofile.client.recaptcha.private_key')
		rc_public = cfg.get('netprofile.client.recaptcha.public_key')
		if (not rc_private) or (not rc_public):
			# TODO: log missing reCAPTCHA keys
			must_recaptcha = False
	if 'submit' in request.POST:
		csrf = request.POST.get('csrf', '')
		if csrf != request.get_csrf():
			errors['csrf'] = _('Error submitting form')
		elif must_recaptcha:
			try:
				rcresp = verify_recaptcha(rc_private, request)
			except ValueError as e:
				errors['recaptcha'] = str(e)
			else:
				if rcresp and not rcresp.valid:
					errors['recaptcha'] = rcresp.text()
		if len(errors) == 0:
			login = request.POST.get('user', '')
			email = request.POST.get('email', '')
			l = len(email)
			if (l == 0) or (l > 254):
				errors['email'] = _('Invalid field length')
			elif not _re_email.match(email):
				errors['email'] = _('Invalid e-mail format')
			if maillogin:
				login = email
			else:
				l = len(login)
				if (l == 0) or (l > 254):
					errors['user'] = _('Invalid field length')
				elif not _re_login.match(login):
					errors['user'] = _('Invalid character used in username')
		if len(errors) == 0:
			sess = DBSession()
			for acc in sess.query(AccessEntity)\
					.filter(AccessEntity.nick == login, AccessEntity.access_state != AccessState.block_inactive.value):
				ent = acc.parent
				ent_email = None
				while ent:
					if isinstance(ent, PhysicalEntity):
						ent_email = ent.email
					elif isinstance(ent, LegalEntity):
						ent_email = ent.contact_email
					if email == ent_email:
						break
					ent = ent.parent
				if email == ent_email:
					queue_mail = asbool(cfg.get('netprofile.client.password_recovery.mail_queue', False))
					sender = cfg.get('netprofile.client.password_recovery.mail_sender')

					if change_pass:
						pwd_len = int(cfg.get('netprofile.client.password_recovery.password_length', 12))
						chars = string.ascii_lowercase + string.ascii_uppercase + string.digits
						try:
							rng = random.SystemRandom()
						except NotImplementedError:
							rng = random
						acc.password = ''.join(rng.choice(chars) for i in range(pwd_len))

					mailer = get_mailer(request)
					tpldef = {
						'cur_loc'     : cur_locale,
						'entity'      : ent,
						'email'       : ent_email,
						'access'      : acc,
						'change_pass' : change_pass
					}
					request.run_hook('access.cl.tpldef.password_recovery.mail', tpldef, request)
					msg_text = Attachment(
						data=render('netprofile_access:templates/email_recover_plain.mak', tpldef, request),
						content_type='text/plain; charset=\'utf-8\'',
						disposition='inline',
						transfer_encoding='quoted-printable'
					)
					msg_html = Attachment(
						data=render('netprofile_access:templates/email_recover_html.mak', tpldef, request),
						content_type='text/html; charset=\'utf-8\'',
						disposition='inline',
						transfer_encoding='quoted-printable'
					)
					msg = Message(
						subject=(loc.translate(_('Password recovery for user %s')) % login),
						sender=sender,
						recipients=(ent_email,),
						body=msg_text,
						html=msg_html
					)
					if queue_mail:
						mailer.send_to_queue(msg)
					else:
						mailer.send(msg)
					return HTTPSeeOther(location=request.route_url('access.cl.restoresent'))
			else:
				errors['csrf'] = _('Username and/or e-mail are unknown to us')
	tpldef = {
		'cur_loc'        : cur_locale,
		'comb_js'        : comb_js,
		'change_pass'    : change_pass,
		'must_recaptcha' : must_recaptcha,
		'maillogin'	 : maillogin,
		'errors'         : {err: loc.translate(errors[err]) for err in errors}
	}
	if must_recaptcha:
		tpldef['rc_public'] = rc_public
	request.run_hook('access.cl.tpldef.restorepass', tpldef, request)
	return tpldef
Пример #24
0
 def _makeOne(self, **kw):
     from pyramid_mailer.message import Attachment
     return Attachment(**kw)