def admin_approve(key): if key and key in app.config['ACCESSKEY_APPROVE']: p = Participant.query.get(request.form['id']) if not p: status = "No such user" else: if 'action.undo' in request.form: p.approved = False status = 'Undone!' # Remove from MailChimp if MailChimp is not None and app.config['MAILCHIMP_API_KEY'] and app.config['MAILCHIMP_LIST_ID']: mc = MailChimp(app.config['MAILCHIMP_API_KEY']) try: mc.listUnsubscribe( id = app.config['MAILCHIMP_LIST_ID'], email_address = p.email, send_goodbye = False, send_notify = False, ) pass except MailChimpError, e: status = e.msg db.session.commit() elif 'action.approve' in request.form: p.approved = True status = "Tada!" mailsent = False # 1. Make user account and activate it user = makeuser(p) user.active = True # 2. Add to MailChimp if MailChimp is not None and app.config['MAILCHIMP_API_KEY'] and app.config['MAILCHIMP_LIST_ID']: mc = MailChimp(app.config['MAILCHIMP_API_KEY']) try: mc.listSubscribe( id = app.config['MAILCHIMP_LIST_ID'], email_address = p.email, merge_vars = {'FULLNAME': p.fullname, 'JOBTITLE': p.jobtitle, 'COMPANY': p.company, 'TWITTER': p.twitter, 'PRIVATEKEY': user.privatekey, 'UID': user.uid}, double_optin = False ) except MailChimpError, e: status = e.msg if e.code == 214: # Already subscribed mailsent = True # 3. Send notice of approval if not mailsent: msg = Message(subject="Your registration has been approved", recipients = [p.email]) msg.body = render_template("approve_notice.md", p=p) msg.html = markdown(msg.body) with app.open_resource("static/doctypehtml5.ics") as ics: msg.attach("doctypehtml5.ics", "text/calendar", ics.read()) mail.send(msg) db.session.commit()
def your_view(): subject = "Mail with PDF" receiver = "*****@*****.**" mail_to_be_sent = Message(subject=subject, recipients=[receiver]) mail_to_be_sent.body = "This email contains PDF." pdf = create_pdf(render_template('your/template.html')) mail_to_be_sent.attach("file.pdf", "application/pdf", pdf.getvalue()) mail_ext.send(mail_to_be_sent) return redirect(url_for('other_view'))
def send(pic, to=app.config.get('ME')): msg = Message( 'Hello', sender=app.config.get('MAIL_USERNAME'), recipients=to) msg.body = "This is the email body" with app.open_resource(os.path.join(directory, pic)) as fp: msg.attach(pic, "image/jpg", fp.read()) mail.send(msg) return '<script type="text/javascript">window.close();</script>'
def test_attach(self): msg = Message(subject="testing", recipients=["*****@*****.**"], body="testing") msg.attach(data="this is a test", content_type="text/plain") a = msg.attachments[0] assert a.filename is None assert a.disposition == "attachment" assert a.content_type == "text/plain" assert a.data == "this is a test"
def test_attach(self): msg = Message(subject="testing", recipients=["*****@*****.**"], body="testing") msg.attach(data="this is a test", content_type="text/plain") a = msg.attachments[0] self.assertIsNone(a.filename) self.assertEqual(a.disposition, "attachment") self.assertEqual(a.content_type, "text/plain") self.assertEqual(a.data, "this is a test")
def send(file_id): recipient = request.form.get("recipient") f = get_file(file_id) msg = Message("File sent from Yaka") msg.sender = g.user.email msg.recipients = [recipient] msg.body = """The following file (%s) might be interesting to you. """ % f.name msg.attach(f.name, f.mime_type, f.data) mail.send(msg) flash("Email successfully sent", "success") return redirect(ROOT + "%d" % f.uid)
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()
def send_mail(subject,to,template=None,attachment=None,**kwargs): ''' Envia un correo y trata y loguea los errores ''' try: msg=Message(_(subject),to if isinstance(to,list) else [to],html=render_template('email/'+(template if template else subject)+'.html',**kwargs)) if attachment is not None: msg.attach(attachment[0],attachment[1],attachment[2]) mail.send(msg) return True except SMTPRecipientsRefused as e: flash("error_mail_send") # se extrae el código y el mensaje de error (code,message)=e[0].values()[0] logging.exception("%d: %s"%(code,message)) return False
def register(): form = RegistrationForm(request.form) if request.method == "POST" and form.validate(): user = User(form.fullname.data, form.email.data) db_session.add(user) db_session.commit() msg = Message( "Here are your barcodes!", sender=("Barcode Generator", "*****@*****.**"), recipients=[form.email.data], body="Enjoy.", ) msg.attach("code39.png", "image/png", gen_code39(form.fullname.data)) msg.attach("qr.png", "image/png", gen_qr(form.fullname.data)) mail.send(msg) flash("Thank you for registering! Your barcode is in your inbox.") return redirect(url_for("register")) return render_template("register.html", form=form)
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, }
def admin_approve(edition): if request.method == 'GET': tz = timezone(app.config['TIMEZONE']) return render_template('approve.html', participants=Participant.query.filter_by(edition=edition), utc=utc, tz=tz, enumerate=enumerate, edition=edition) elif request.method == 'POST': p = Participant.query.get(request.form['id']) if not p: status = "No such user" else: if 'action.undo' in request.form: p.approved = False p.user = None status = 'Undone!' # Remove from MailChimp if MailChimp is not None and app.config['MAILCHIMP_API_KEY'] and app.config['MAILCHIMP_LIST_ID']: mc = MailChimp(app.config['MAILCHIMP_API_KEY']) try: mc.listUnsubscribe( id = app.config['MAILCHIMP_LIST_ID'], email_address = p.email, send_goodbye = False, send_notify = False, ) pass except MailChimpError, e: status = e.msg db.session.commit() elif 'action.approve' in request.form: if p.approved: status = "Already approved" else: # Check for dupe participant (same email, same edition) dupe = False for other in Participant.query.filter_by(edition=p.edition, email=p.email): if other.id != p.id: if other.user: dupe = True break if dupe == False: p.approved = True status = "Tada!" # 1. Make user account and activate it user = makeuser(p) user.active = True # 2. Add to MailChimp if MailChimp is not None and app.config['MAILCHIMP_API_KEY'] and app.config['MAILCHIMP_LIST_ID']: mc = MailChimp(app.config['MAILCHIMP_API_KEY']) addmailchimp(mc, p) # 3. Send notice of approval msg = Message(subject="Your registration has been approved", recipients = [p.email]) msg.body = render_template("approve_notice_%s.md" % edition, p=p) msg.html = markdown(msg.body) with app.open_resource("static/doctypehtml5-%s.ics" % edition) as ics: msg.attach("doctypehtml5.ics", "text/calendar", ics.read()) mail.send(msg) db.session.commit() else: status = "Dupe" else: status = 'Unknown action'
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, }
def admin_approve(edition): if request.method == 'GET': tz = timezone(app.config['TIMEZONE']) return render_template( 'approve.html', participants=Participant.query.filter_by(edition=edition), utc=utc, tz=tz, enumerate=enumerate, edition=edition) elif request.method == 'POST': p = Participant.query.get(request.form['id']) if not p: status = "No such user" else: if 'action.undo' in request.form: p.approved = False p.user = None status = 'Undone!' # Remove from MailChimp if MailChimp is not None and app.config[ 'MAILCHIMP_API_KEY'] and app.config[ 'MAILCHIMP_LIST_ID']: mc = MailChimp(app.config['MAILCHIMP_API_KEY']) try: mc.listUnsubscribe( id=app.config['MAILCHIMP_LIST_ID'], email_address=p.email, send_goodbye=False, send_notify=False, ) pass except MailChimpError, e: status = e.msg db.session.commit() elif 'action.approve' in request.form: if p.approved: status = "Already approved" else: # Check for dupe participant (same email, same edition) dupe = False for other in Participant.query.filter_by(edition=p.edition, email=p.email): if other.id != p.id: if other.user: dupe = True break if dupe == False: p.approved = True status = "Tada!" # 1. Make user account and activate it user = makeuser(p) user.active = True # 2. Add to MailChimp if MailChimp is not None and app.config[ 'MAILCHIMP_API_KEY'] and app.config[ 'MAILCHIMP_LIST_ID']: mc = MailChimp(app.config['MAILCHIMP_API_KEY']) addmailchimp(mc, p) # 3. Send notice of approval msg = Message( subject="Your registration has been approved", recipients=[p.email]) msg.body = render_template("approve_notice_%s.md" % edition, p=p) msg.html = markdown(msg.body) with app.open_resource("static/doctypehtml5-%s.ics" % edition) as ics: msg.attach("doctypehtml5.ics", "text/calendar", ics.read()) mail.send(msg) db.session.commit() else: status = "Dupe" else: status = 'Unknown action'