Example #1
0
def _send_mail_to_self_registering_participant(meeting, events, form, lang='en'):
    app = flask.current_app
    mail = Mail(app)

    lang = {"en": "E", "es": "S", "fr": "F"}.get(lang, "E")
    template = app.jinja_env.get_template('participant/self_registration_mail.html')
    recipients = [ email for email in form.data['personal_email'].split() if len(email)>3 ]

    phrases = {p.data['name']: p for p in meeting.get_phrases}
    body_html = template.render({
        'meeting': meeting,
        'events': events,
        'phrases': phrases,
        'lang': lang,
        'config': app.config,
        'categories': dict(form.personal_category.choices),
        'countries': dict(form.personal_country.choices),
        'languages': dict(form.personal_language.choices),
        'person': form,
    })

    msg = Message(_(u'Registration for %(meeting)s',
                  meeting=meeting.decoded_data['info_description_%s' % lang]),
                  sender=meeting.decoded_data['info_admin_email'],
                  recipients=recipients,
                  html=body_html)
    mail.send(msg)
def send_mail_to_admin(meeting, form, person_id):
    app = flask.current_app

    mail = Mail(app)
    sender = app.config["CITES_ADMIN"]
    recipients = [meeting.data['info_media_admin_email']]
    subject = u"%s Media accreditation for %s.%s %s" % (
        meeting.data['info_description_E'],
        form.data['personal_name_title'],
        form.data['personal_first_name'],
        form.data['personal_last_name'],
    )

    template = app.jinja_env.get_template('media_participants/form_for_admin.html')
    body = template.render({
        'meeting': meeting,
        'person': form,
        'categories': dict(form.personal_category.choices),
        'countries': dict(form.personal_country.choices),
        'attending_dates': dict(form.attending_dates.choices),
        'person_id': person_id,
        'config': app.config,
    })

    msg = Message(subject, sender=sender, recipients=recipients, html=body)
    mail.send(msg)
Example #3
0
def _send_mail_to_admin(meeting, events, form, person_id):
    app = flask.current_app
    mail = Mail(app)

    recipients = [meeting.data['info_admin_email']]
    subject = u"%s registration for %s.%s %s" % (
        meeting.data['info_description_E'],
        form.data['personal_name_title'],
        form.data['personal_first_name'],
        form.data['personal_last_name'],
    )

    template = app.jinja_env.get_template('participant/form_for_admin.html')
    body = template.render({
        'meeting': meeting,
        'events': events,
        'person': form,
        'categories': dict(form.personal_category.choices),
        'countries': dict(form.personal_country.choices),
        'languages': dict(form.personal_language.choices),
        'person_id': person_id,
        'config': app.config,
    })

    msg = Message(subject, sender=meeting.data['info_admin_email'],
                  recipients=recipients, html=body)
    mail.send(msg)
Example #4
0
def send_test_email(recipient):
    mail = Mail(app)
    msg = Message("Test Message -- Candidates Emailer app",
                  [recipient],
                  sender="*****@*****.**")
    msg.body = "This is a test message from the Candidates Emailer App"
    mail.send(msg)
Example #5
0
def reset_password():
    email_to_reset_password = flask.request.form.get("email", "")

    if flask.request.method == "POST":
        try:
            staff_member = [i for i in database.find("staff", email=email_to_reset_password)]
            assert len(staff_member) == 1
            staff_member = staff_member[0]
        except AssertionError:
            flask.flash(u"Your email does not exist in our database.", "error")
        else:
            auth_token = sugar.generate_token(email_to_reset_password)

            session = database.get_session()

            staff_row = database.get_or_404("staff", id=staff_member.id)
            staff_schema = StaffSchema.from_flat(staff_row)

            staff_schema["token"].set(auth_token)

            if staff_schema.validate():
                staff_row.update(staff_schema.flatten())
                session.save(staff_row)
                session.commit()

            app = flask.current_app
            mail = Mail(app)

            settings_url = app.config.get("HOSTNAME")
            mail_msg_link = "%s/%s/change-password" % (settings_url, auth_token)

            msg_subject = "Reset your Cites password"
            msg_sender = app.config.get("DEFAULT_MAIL_SENDER")
            msg_recipients = [email_to_reset_password]
            msg_body = str(
                "Forgot your password?\n\nCites received a request "
                "to reset the password for your account.\n"
                "If you want to reset your "
                "password, click on the link below (or copy and "
                "paste the URL into your browser):\n\n%s\n\nThis "
                "link takes you to a secure page where you can "
                "change your password.\nIf you don't want to "
                "reset your password, please ignore this "
                "message. Your password will not be reset."
                "\n\nThe Cites Team" % (mail_msg_link)
            )

            msg = Message(msg_subject, sender=msg_sender, recipients=msg_recipients, body=msg_body)

            mail.send(msg)

            flash_message = str(
                "We've sent password reset instructions to your "
                "email address. Please also check your email's "
                "spam filter."
            )
            flask.flash(flash_message, "success")
Example #6
0
def _send_mail_to_user(staff_schema, password):
    app = flask.current_app
    mail = Mail(app)

    admin_email = app.config["CITES_ADMIN"]
    body = "You are now admin on Cites Meetings. Your password is %s" % password

    msg = Message("Cites Meetings Admin ",
                  sender=admin_email,
                  recipients=[staff_schema["email"].value],
                  body=body)
    mail.send(msg)
Example #7
0
def _send_mail_to_user(staff_schema, password):
    app = flask.current_app
    mail = Mail(app)

    admin_email = app.config["CITES_ADMIN"]
    body = "You have admin rights on %s. Your password is %s" % (
        app.config["HOSTNAME"], password)

    msg = Message("Administration rights ",
                  sender=admin_email,
                  recipients=[staff_schema["email"].value],
                  body=body)
    mail.send(msg)
Example #8
0
    def run(self, testing):
        mail = Mail(app)
        for user, csv_reports in generate_reports(app.config["REPORTS_DIR"]):
            context = {"user": user}
            template = Template(app.config["EMAIL_TEXT_TEMPLATE"])
            msg = Message(app.config["EMAIL_SUBJECT_LINE"],
                          recipients=[user.alternate_email] if user.use_alternate_email else [user.email],
                          sender=app.config["DEFAULT_MAIL_SENDER"])
            msg.body = template.render(context)

            for csv_filename, csv_data in csv_reports:
                msg.attach(csv_filename, "text/csv", csv_data)
                
            if not testing:
                mail.send(msg)
            else:
                print msg.get_response().to_message().as_string()
Example #9
0
class MailService():
    def __init__(self, app):
        self.app = app
        self.setupConfiguration()
        self.mail = Mail(app)
        self.lookup = TemplateLookup(directories=['mail'],
                                     output_encoding='utf-8',
                                     encoding_errors='replace')

    def setupConfiguration(self):
        self.app.config['MAIL_USERNAME'] = "******"
        self.app.config['MAIL_PASSWORD'] = "******"
        self.app.config['DEFAULT_MAIL_SENDER'] = "enjoy-events"
        self.app.config['MAIL_SERVER'] = "smtp.gmail.com"
        self.app.config['MAIL_PORT'] = "465"
        self.app.config['MAIL_USE_SSL'] = True

    def createUser(self, user):
        msg = Message("Bienvenido a Enjoy-events", recipients=[user.email])
        msg.html = self.lookup.get_template("registration.html").render(
            user=user)
        self.sendMail(msg)

    def assistance(self, assistance, user):
        msg = Message("Vas a asistir al evento %s" % assistance.event.name,
                      recipients=[user.email])
        msg.html = self.lookup.get_template("assistance.html").render(
            assistance=assistance)
        self.sendMail(msg)

    def sendMail(self, msg):
        try:

            @copy_current_request_context
            def sendMessage(self, msg):
                self.mail.send(msg)

            if self.app.config['SEND_EMAILS']:
                sender = threading.Thread(name='mailService',
                                          target=sendMessage,
                                          args=(self, msg))
                sender.start()
        except Exception as err:
            print err
Example #10
0
def resend_mail(mail_id):
    app = flask.current_app

    sent_mail = database.get_or_404('mail_log', mail_id)
    sent_mail_schema = schema.MailSchema.from_flat(sent_mail)
    if flask.request.method == 'POST':
        mail = Mail(app)
        meeting = schema.Meeting.get_or_404(sent_mail['meeting_id'])
        msg = Message(sent_mail['mail_subject'],
                      sender=meeting['info']['admin_email'],
                      recipients=[m.value for m in sent_mail_schema['to']],
                      cc=[m.value for m in sent_mail_schema['cc']],
                      body=sent_mail['mail_message'])
        mail.send(msg)
        if app.config['MAIL_SUPPRESS_SEND']:
            flask.flash(u'This is a demo, no real email was sent', 'info')
        else:
            flask.flash('Email resent.', 'success')
    return flask.redirect(flask.url_for('meeting.view_mail_log',
                          meeting_id=sent_mail['meeting_id'],
                          mail_log_id=mail_id))
def send_mail_to_media_participant(meeting, form, lang='en'):
    app = flask.current_app
    mail = Mail(app)

    lang = {"en": "E", "es": "S", "fr": "F"}.get(lang, "E")
    template = app.jinja_env.get_template('media_participants/form_for_participant.html')

    body_html = template.render({
        'meeting': meeting,
        'lang': lang,
        'config': app.config,
        'categories': dict(form.personal_category.choices),
        'countries': dict(form.personal_country.choices),
        'attending_dates': dict(form.attending_dates.choices),
        'person': form,
    })

    msg = Message(_(u'Registration for %(meeting)s',
                  meeting=meeting.decoded_data['info_description_%s' % lang]),
                  sender=meeting.decoded_data['info_media_admin_email'],
                  recipients=[form.data['personal_email']],
                  html=body_html)
    mail.send(msg)
class MailService():
	def __init__(self, app):
		self.app = app
		self.setupConfiguration()
		self.mail = Mail(app)
		self.lookup = TemplateLookup(directories=['mail'], output_encoding='utf-8', encoding_errors='replace')


	def setupConfiguration(self):
		self.app.config['MAIL_USERNAME'] = "******"
		self.app.config['MAIL_PASSWORD'] = "******"
		self.app.config['DEFAULT_MAIL_SENDER'] = "enjoy-events"
		self.app.config['MAIL_SERVER'] = "smtp.gmail.com"
		self.app.config['MAIL_PORT'] = "465"
		self.app.config['MAIL_USE_SSL'] = True
		

	def createUser(self, user):
		msg = Message("Bienvenido a Enjoy-events", recipients=[user.email])
		msg.html = self.lookup.get_template("registration.html").render(user=user)
		self.sendMail(msg)

	def assistance(self, assistance, user):
		msg = Message("Vas a asistir al evento %s" % assistance.event.name, recipients=[user.email])
		msg.html = self.lookup.get_template("assistance.html").render(assistance=assistance)
		self.sendMail(msg)

	def sendMail(self, msg):
		try:
			@copy_current_request_context
			def sendMessage(self, msg):
				self.mail.send(msg)
			if self.app.config['SEND_EMAILS']:
				sender = threading.Thread(name='mailService', target=sendMessage, args=(self, msg))
				sender.start()
		except Exception as err:
			print err
Example #13
0
def send_mail(person_id):
    app = flask.current_app
    session = database.get_session()

    person = schema.Person.get_or_404(person_id)
    phrases = {item["id"]: item["name"]  for item in
               schema._load_json("refdata/phrases.json")}

    if flask.request.method == "POST":
        mail = Mail(app)
        # populate schema with data from POST
        mail_schema = schema.MailSchema.from_flat(flask.request.form.to_dict())

        if mail_schema.validate():
            # flatten schema
            mail_data = {}
            mail_data.update(mail_schema.flatten())

            # construct recipients from "to"
            recipients = [mail_data["to"]]
            # recipients = ["*****@*****.**"]

            # send email
            msg = Message(mail_data["subject"], sender="*****@*****.**",
                          recipients=recipients, cc=[mail_data["cc"]],
                          body=mail_data["message"])

            pdf = sugar.generate_pdf_from_html(
                flask.render_template("participant/credentials.html", **{
                    "person": schema.Person.get_or_404(person_id),
                    "meeting_description": MEETING_DESCRIPTION,
                    "meeting_address": MEETING_ADDRESS,
                })
            )
            msg.attach("credentials.pdf", "application/pdf", pdf)
            mail.send(msg)

            if app.config["MAIL_SUPPRESS_SEND"]:
                flask.flash(u"This is a demo, no real email was sent", "info")
            else:
                # flash a success message
                success_msg = u"Mail sent to %s" % mail_data["to"]
                if mail_data["cc"]:
                    success_msg += u" and to %s" % mail_data["cc"]
                flask.flash(success_msg, "success")

        else:
            flask.flash(u"Errors in mail information", "error")

    else:
        # create a schema with default data
        mail_schema = schema.MailSchema({
            "to": person["personal"]["email"],
            "subject": phrases["EM_Subj"],
            "message": "\n\n\n%s" % phrases["Intro"],
        })

    return {
        "mk": sugar.MarkupGenerator(
            app.jinja_env.get_template("widgets/widgets_mail.html")
        ),
        "person": person,
        "mail_schema": mail_schema,
    }
Example #14
0
def send_mail(meeting_id, person_id):
    app = flask.current_app
    meeting = sugar.get_object_or_404(models.Meeting, id=meeting_id)
    session = database.get_session()

    person = sugar.get_person_or_404(meeting_id, person_id)
    lang_code = person.decoded_data['personal_language'] or 'en'
    labeled = schema.labels_for_values(person.data, meeting_id,
                                       in_participant_language=True)
    category = person.category_model(meeting_id)

    cc_addresses = []
    phrases = {p.data['name']: p for p in meeting.get_phrases}
    event_form = EventCitesForm(meeting_model=meeting, person=person)

    if flask.request.method == "POST":
        mail = Mail(app)

        form_data = flask.request.form.to_dict()

        if form_data['mail_to'].find(',') != -1:
            to_addresses = form_data['mail_to'].split(',')
            if form_data.get('mail_cc'):
                cc_addresses = form_data['mail_cc'].split(',')
        else:
            to_addresses = form_data["mail_to"].split(";")
            if form_data.get('mail_cc'):
                cc_addresses = form_data["mail_cc"].split(";")

        # populate schema with data from POST
        mail_schema = schema.MailSchema.from_flat(form_data)
        to_member_schema = mail_schema['to'].member_schema
        cc_member_schema = mail_schema['cc'].member_schema

        for address in to_addresses:
            mail_schema['to'].append(to_member_schema(address))

        for address in cc_addresses:
            mail_schema['cc'].append(cc_member_schema(address))

        if mail_schema.validate():
            # flatten schema
            mail_data = {}
            mail_data.update(mail_schema.flatten())
            mail_data['mail_to'] = to_addresses
            mail_data['mail_cc'] = cc_addresses

            # construct recipients from "to"
            recipients = mail_data['mail_to']

            # send email
            msg = Message(mail_data['mail_subject'],
                          sender = meeting.decoded_data['info_admin_email'],
                          recipients=recipients,
                          cc=mail_data['mail_cc'],
                          body=mail_data['mail_message'])

            # render form in participant language
            participant_lang = {"E": "en", "S": "es", "F": "fr"}.get(person.lang, "E")
            sugar.set_lang(participant_lang)

            pdf = sugar.generate_pdf_from_html(
                flask.render_template('participant/credentials.html', **{
                    'person': person,
                    'meeting': meeting,
                    'credentials_strings': refdata.credentials_strings,
                    'labeled': labeled,
                    'phrases': phrases,
                    'category': category,
                    'event_form': event_form,
                })
            )

            msg.attach('registration_details.pdf', 'application/pdf', pdf)
            mail.send(msg)

            # log mail
            mail_log_data = {
                'date': date.today(),
                'meeting_id': meeting.id,
                'person_id': person_id,
                'type': 'single_mail',
            }

            mail_log_data.update(mail_data)
            mail_log_schema = schema.MailLogSchema.from_flat(mail_log_data)

            if mail_log_schema.validate():
                mail_log_row = database.new('mail_log')
                mail_log_row.update(mail_log_schema.flatten())

                session.save(mail_log_row)
                session.commit()

            # update acknowledged date
            person.update_meeting_flags(meeting_id, {
                'meeting_flags_acknowledged': str(datetime.now().replace(
                    second=0, microsecond=0))
            })

            if app.config['MAIL_SUPPRESS_SEND']:
                flask.flash(u'This is a demo, no real email was sent', 'info')
            else:
                # flash a success message
                success_msg = u'Mail sent to %d recipients.' % (
                    len(to_addresses) + len(cc_addresses))
                flask.flash(success_msg, 'success')

                return flask.redirect(
                    flask.url_for('participant.send_mail',
                                  meeting_id=meeting_id,
                                  person_id=person_id))
        else:
            flask.flash(u'Errors in mail information', 'error')

    else:
        # create a schema with default data
        mail_schema = schema.MailSchema({
            'to': [person.data['personal_email']],
            'subject': phrases['EM_Subj'].decoded_data['description_%s' % lang_code],
            'message': '\n\n\n%s' % phrases['Intro'].decoded_data['description_%s' % lang_code],
        })

    return {
        'mk': sugar.MarkupGenerator(
            app.jinja_env.get_template('widgets/widgets_mail.html')
        ),
        'person': person,
        'category': category,
        'mail_schema': mail_schema,
        'meeting': meeting,
        'phrases': phrases,
    }
Example #15
0
from flask import Flask
from flaskext.mail import Mail

app = Flask(__name__)
mail = Mail(app)
    mail = Mail()
    msg = mail("Hello",
                  sender="*****@*****.**",
                  recipients=["*****@*****.**"])
    mail.send(msg)