def sendMail(self, mailFrom='*****@*****.**', mailTo=None, mailCC=None, mailBCC=None, replyTo=None, subject=None, bodyHTML=None, bodyText=None): surpress = (EmailSuppression.objects.filter(suppression_date=date.today()).count() > 0) if surpress: log.warn("Surpressing e-mail") return if bodyText and bodyHTML: message = EmailMultiAlternatives() message.body = bodyText message.attach_alternative(transform(bodyHTML), "text/html") elif bodyText: message = EmailMessage() message.body = bodyText elif bodyHTML: message = EmailMessage() message.body = transform(bodyHTML) message.content_subtype = "html" else: raise TypeError("bodyHTML or bodyText must be set") if not (mailTo or mailCC or mailBCC): raise TypeError("Message must have at least one recipient") if subject: message.subject = subject overrideEmail = None #Try to get override email from settings try: overrideEmail = [settings.ENRICHMENT_OVERRIDE_EMAIL] except AttributeError: pass #Take presidence on the parameter if self.overrideEmail: overrideEmail = self.overrideEmail if not overrideEmail: if mailTo: message.to = list(mailTo) if mailCC: message.cc = list(mailCC) if mailBCC: message.bcc = list(mailBCC) else: message.to = overrideEmail if replyTo: message.reply_to = list(replyTo) message.from_email = mailFrom message.send()
def invite_post(request): if not request.user.can_invite: return render(request, 'errors/403.html', status=403) email = request.POST.get('email') try: user = User.objects.get(email=email) if user.account: return HttpResponseRedirect( reverse('accounts_invite') + '?success=0') user.account = request.user.account except User.DoesNotExist: user = User(email=email, account=request.user.account) if request.POST.get('send') == 'yes': subject = 'Welcome to a colorful world!' body = transform( loader.render_to_string( 'emails/invite.html', dict(user=user, me=request.user, message=request.POST.get('message')))) email_message = EmailMultiAlternatives( subject, body, 'Master Yoda <*****@*****.**>', [user.email]) html_email = transform( loader.render_to_string( 'emails/invite.html', dict(user=user, me=request.user, message=request.POST.get('message')))) email_message.attach_alternative(html_email, 'text/html') email_message.send() user.save() return HttpResponseRedirect(reverse('accounts_invite') + '?success=1')
def get_body_html(self): html = "" if self.body_html: html = transform(self.render_text_template(self.body_html)) elif self.body_html_template: html = transform(self.render_template(self.body_html_template)) return html
def invite_post(request): if not request.user.can_invite: return render(request, "errors/403.html", status=403) email = request.POST.get("email") try: user = User.objects.get(email=email) if user.account: return HttpResponseRedirect(reverse("accounts_invite") + "?success=0") user.account = request.user.account except User.DoesNotExist: user = User(email=email, account=request.user.account) if request.POST.get("send") == "yes": subject = "Welcome to a colorful world!" body = transform( loader.render_to_string( "emails/invite.html", dict(user=user, me=request.user, message=request.POST.get("message")) ) ) email_message = EmailMultiAlternatives(subject, body, "Master Yoda <*****@*****.**>", [user.email]) html_email = transform( loader.render_to_string( "emails/invite.html", dict(user=user, me=request.user, message=request.POST.get("message")) ) ) email_message.attach_alternative(html_email, "text/html") email_message.send() user.save() return HttpResponseRedirect(reverse("accounts_invite") + "?success=1")
def buildCardsAndDeck(path: Path): global AnkiNotes, AnkiModels, Anki_Collections, totalCardCount, FAILED_DECKS conn = sqlite3.connect(path.joinpath("collection.anki2").as_posix()) cursor = conn.cursor() cursor.execute( "SELECT * FROM cards ORDER BY factor ASC") # min ease would at rows[0] and max index would be at rows[-1] rows = cursor.fetchall() with IncrementalBar("\tBuilding Cards and deck", max=len(rows)) as bar: for row in rows: cid, nid, did, ordi, mod, usn, crtype, queue, due, ivl, factor, reps, lapses, left, odue, odid, flags, data = row reqNote = AnkiNotes[str(nid)] genCard = None if reqNote.model.type == 0: reqTemplate = getTemplateofOrd(reqNote.model.tmpls, int(ordi)) questionTg = "<style> " + buildCssForOrd(reqNote.model.css, ordi) \ + "</style><section class='card' style=\" height:100%; width:100%; margin:0; \">" \ + mustache.render(reqTemplate.qfmt, buildStubbleDict(reqNote)) + "</section>" answerTag = "<style> " + buildCssForOrd(reqNote.model.css, ordi) \ + "</style><section class='card' style=\" height:100%; width:100%; margin:0; \">" \ + mustache.render(reqTemplate.afmt, buildStubbleDict(reqNote)) + "</section>" questionTg = premailer.transform(questionTg) answerTag = premailer.transform(answerTag) genCard = Card(cid, questionTg, answerTag) elif reqNote.model.type == 1: reqTemplate = getTemplateofOrd(reqNote.model.tmpls, 0) mustache.filters["cloze"] = lambda txt: Formatters.cloze_q_filter(txt, str(int(ordi) + 1)) css = reqNote.model.css css = buildCssForOrd(css, ordi) if css else "" questionTg = "<style> " + css + " </style><section class='card' style=\" height:100%; width:100%; margin:0; \">" \ + mustache.render(reqTemplate.qfmt, buildStubbleDict(reqNote)) + "</section>" mustache.filters["cloze"] = lambda txt: Formatters.cloze_a_filter(txt, str(int(ordi) + 1)) answerTag = "<section class='card' style=\" height:100%; width:100%; margin:0; \">" \ + mustache.render(reqTemplate.afmt, buildStubbleDict(reqNote)) + "</section>" questionTg = premailer.transform(questionTg) answerTag = premailer.transform(answerTag) genCard = Card(cid, questionTg, answerTag) if genCard is not None: reqDeck = getDeckFromID(Anki_Collections, str(did)) if reqDeck is not None: reqDeck.cards.append(genCard) else: if did not in FAILED_DECKS: FAILED_DECKS.append(did) else: if did not in FAILED_DECKS: FAILED_DECKS.append(did) totalCardCount += 1 bar.next() bar.finish()
def user_send_invitation(request, user_id): user = get_object_or_404(User, pk=user_id) subject = 'Welcome to a colorful world!' body = transform(loader.render_to_string('emails/invite.html', dict(user=user))) email_message = EmailMultiAlternatives(subject, body, 'Master Yoda <*****@*****.**>', [user.email]) html_email = transform(loader.render_to_string('emails/invite.html', dict(user=user, me=request.user))) email_message.attach_alternative(html_email, 'text/html') email_message.send() return redirect(user_show, user_id=user.id)
def generate_html(md_source, template_name, sender_name, sender_email): """Produce the HTML necessary for an email, without inlining images.""" rendered = render_mail_template(md_source, template_name, sender_name, sender_email) transformed = transform(rendered) # We transform-minify-transform so that the minifier can see the styles # inlined by the transformer and the transformer can ensure that the # minifier's output is email-compatible minified = transform(minify(transformed, remove_comments=True)) return minified
def compile2html(file, render_dict=None, classes="table", base_url="http://quantsrv/"): assert os.path.exists(file), "File {0} does not exist.".format(file) t = __getTemplate(tpl_path=file) if render_dict: for key, item in render_dict.items(): if isinstance(item, pd.DataFrame): render_dict[key] = __frame2html(item, classes=classes) return transform(t.render(render_dict), base_url=base_url) else: return transform(t, base_url=base_url)
def generate_html(credit_score, networth, txs_html, accts_html): pd.set_option('colheader_justify', 'center') with open('email_template.html', 'r') as file: email_template = file.read() today = date.today().strftime("%d/%m/%Y") return email_template.format( date_time=today, networth=networth, score=credit_score, transactions= transform(txs_html), accounts=transform(accts_html))
def user_send_invitation(request, user_id): user = get_object_or_404(User, pk=user_id) subject = 'Welcome to a colorful world!' body = transform( loader.render_to_string('emails/invite.html', dict(user=user))) email_message = EmailMultiAlternatives(subject, body, 'Master Yoda <*****@*****.**>', [user.email]) html_email = transform( loader.render_to_string('emails/invite.html', dict(user=user, me=request.user))) email_message.attach_alternative(html_email, 'text/html') email_message.send() return redirect(user_show, user_id=user.id)
def send_email(from_email, subject, to_email, txt_content=None, html_content=None, from_name=None, attachments=None): if not from_name: from_name = settings.HACKATHON_NAME if not from_email: logging.error("No from_email found while sending emails") raise RuntimeError("No from_email") sg_mail = Mail() sg_mail.from_email = Email(from_email, from_name) personalization = Personalization() personalization.add_to(Email(to_email)) personalization.subject = subject sg_mail.add_personalization(personalization) transform(html_content) if txt_content is None and html_content is None: raise ValueError('Must send some type of content') if txt_content: sg_mail.add_content(Content('text/plain', txt_content)) if html_content: sg_mail.add_content(Content('text/html', transform(html_content))) if attachments: for attachment in attachments: sg_attachment = Attachment() sg_attachment.content = attachment['encoded'] sg_attachment.filename = attachment['filename'] sg_attachment.type = attachment['file_type'] sg_attachment.disposition = 'attachment' sg_attachment.content_id = attachment['encoded'] sg_mail.add_attachment(sg_attachment) mail_body = sg_mail.get() try: response = sg.client.mail.send.post(request_body=mail_body) except Exception as e: logging.error("Error mailing using SendGrid, message: {}".format( e.message)) logging.error("error body: {}".format(e.body)) logging.error("email: {}".format(mail_body)) raise e if response.status_code != 202: raise RuntimeError # TODO: Get a proper error on this
def send_notification(to_address, subject, content_text, content_html, uid): msg = MIMEMultipart('alternative') plain = MIMEText(content_text, 'plain', _charset='utf-8') html = MIMEText(transform(content_html), 'html', _charset='utf-8') msg.attach(plain) msg.attach(html) msg['Subject'] = Header(SUBJECT_PREFIX + " " + subject, 'utf-8') msg['From'] = config.MAIL_FROM msg['To'] = to_address msg['Date'] = formatdate(time.time(), localtime=True) msg['Message-id'] = make_msgid() msg['X-LDAP-ID'] = uid logger.info("Mailing %s: '%s'", to_address, subject) logger.debug("Content: ---\n%s\n---", content_text) if config.NO_MAILS: logger.info("skipping mail, because config.NO_MAILS") return s = smtplib.SMTP(config.MAIL_HOST) s.connect(host=config.MAIL_HOST, port=config.MAIL_PORT) s.ehlo() s.starttls() s.login(user=config.MAIL_FROM, password=config.MAIL_PW) s.sendmail(config.MAIL_FROM, [to_address], msg.as_string()) s.quit()
def generate_and_send_email(self): """ Generate Cloudmapper Email and send via AWS SES Transformations are done on the report.html file to support CSS and JS functionality """ subject = (f'[cloudmapper {self.account_name}]' ' Cloudmapper audit findings') body_text = 'Please see the attached file for cloudmapper results.' with open(self.report_source, 'r') as f_in: html_data = f_in.read() # Inject JS file contents into HTML html_data = self.js_replace(html_data) # Run premailer transformation to inject CSS data directly in HTML html_data = transform(html_data, base_path=self.BASE_PATH) # Fix CSS post-premailer html_data = self.css_js_fix(html_data) cloudmapper_filename = datetime.datetime.now().strftime( 'cloudmapper_report_%Y-%m-%d.html') attachments = {cloudmapper_filename: html_data} logger.info("Sending SES Email.") self.ses.send_email(self.sender, self.recipient, subject, body_text, html_data, attachments)
def render(self, context, template_name): context_temp = sm_settings.CONTEXT.copy() context_temp.update(context) context_temp.update({ 'title': Template(self.title).render(Context(context_temp)), 'button_label': Template(self.button_label).render(Context(context_temp)), 'button_link': Template(self.button_link).render(Context(context_temp)), 'body': Template(self.body).render(Context(context_temp)), }) if template_name is None: try: template_name = sm_settings.TEMPLATE except AttributeError: raise ImproperlyConfigured('TEMPLATE Should be configured') html = loader.render_to_string(template_name, context_temp) html = transform(html, base_url=sm_settings.BASE_URL) h = html2text.HTML2Text() h.ignore_images = True h.ignore_tables = True text = h.handle(html) response = { 'subject': Template(self.subject).render(Context(context_temp)), 'message': text, 'html_message': html, } return response
def send_new_talk_available(submission): talk = submission.talk subject = f'New talk uploaded - {submission.talk.title}' msg = Message(subject) msg.html = transform( env.get_template('new_talk_available.html').render( subject=subject, talk=talk, domain=app.config['TALKY_DOMAIN'])) # Send notifications to the members of this and flagged experiments recipients = [] for user in schema.User.query.all(): if user.experiment == talk.experiment: recipients.append(user.email) elif user.experiment in talk.interesting_to: recipients.append(user.email) # Send notifications to members of flagged categories for category in talk.categories: recipients.extend([c.email for c in category.contacts]) # Remove duplicates recipients = list(set(recipients)) # Sent the email msg.bcc = _validate_emails(recipients) thr = Thread(target=send_async_email, args=[app, msg]) thr.start()
def send_email(**kwargs): msg = MIMEMultipart('alternative') msg['Subject'] = kwargs['subject'] msg['From'] = kwargs['sender'] # format: "sender name <sender@email>" msg['To'] = kwargs['to'] text = "К сожалению, наша рассылка поддерживает только HTML формат письма" part1 = MIMEText(text, 'plain') activate('ru') html = transform( get_template(kwargs['template']).render(Context(kwargs['context']))) part2 = MIMEText(html, 'html') username = MANDRILL_USERNAME password = MANDRILL_PASSWORD msg.attach(part1) msg.attach(part2) s = smtplib.SMTP('smtp.mandrillapp.com', 587) s.login(username, password) s.sendmail(msg['From'], msg['To'], msg.as_string()) s.quit()
def send_error_message(error_message): email_template = os.path.join(templates_directory, 'email_message.html') with open(email_template, 'r') as html_template: html_template_string = html_template.read() css_template = os.path.join(templates_directory, 'email_bootstrap.min.css') with open(css_template, 'r') as css: css_string = css.read() template = Template(html_template_string) message = ''' <div class="alert alert-danger" role="alert"> {0} </div>'''.format(error_message) html_body = template.render(title='Error Updating Bank Information', css=css_string, message=message).encode('utf-8') html_body = transform(html_body).encode('utf-8') msg = Message('Error Updating Bank Information', recipients=[current_app.config['MAIL_USERNAME']], html=html_body) mail.send(msg)
def agency_activation_change_to_promotor(modeladmin, request, queryset): queryset.update(agency_validated=False) queryset.update(promoter_validated=True) queryset.update(user_type='P') for user in queryset: # Change from agency to promotor values user.promoter_room_or_event_name = user.agency_name user.promoter_company_name = user.agency_company_name user.promoter_cif = user.agency_cif user.promoter_additional_info = user.agency_additional_info user.agency_name = user.agency_company_name = user.agency_cif = user.agency_additional_info = '' user.save() # Send mail email = user.email subject, from_email = 'Solicitud de agencia no aprobada, validado como promotor', 'Directo al Artista <*****@*****.**>' message = render_to_string('email/agency_activation_promoter_validated.html', { 'user': user, }) html_content = render_to_string('email/global/template.html', { 'email_title': 'Solicitud de agencia no aprobada, validado como promotor', 'email_content': message, }) html_content = transform(html_content) text_content = strip_tags(html_content) msg = EmailMultiAlternatives(subject, text_content, from_email, [email]) msg.attach_alternative(html_content, "text/html") msg.send(fail_silently=True)
def paypal_validate_plan_signup(sender, **kwargs): ipn_obj = sender valid = True trans = TransactionSubscription.objects.get(id=int(ipn_obj.invoice)) if ipn_obj.period3 != '1 M': valid = False elif ipn_obj.recurring != '1': valid = False elif ipn_obj.mc_amount3 != trans.gross_amount: valid = False if not valid: subject, from_email = 'DA admin - Paypal subscription error', 'Directo al Artista <*****@*****.**>' message = render_to_string('email/paypal_subs_error.html', { 'trans': trans, 'object': ipn_obj.item_name, }) html_content = render_to_string( 'email/global/template.html', { 'email_title': 'DA admin - Paypal subscription error', 'email_content': message, }) html_content = transform(html_content) text_content = strip_tags(html_content) msg = EmailMultiAlternatives(subject, text_content, from_email, ['*****@*****.**']) msg.attach_alternative(html_content, "text/html") msg.send(fail_silently=True) return valid
def run(iterations): def raw(s): return re.sub(r">\s+<", "><", s.replace("\n", "")) print(samples) for i in range(iterations): random.shuffle(samples) for sample in samples: with open(os.path.join(sample, "input.html")) as f: input_html = f.read() with open(os.path.join(sample, "output.html")) as f: output_html = f.read() try: with open(os.path.join(sample, "options.json")) as f: options = json.load(f) except FileNotFoundError: options = {} options["pretty_print"] = False got_html = transform(input_html, **options) got_html_raw = raw(got_html) output_html_raw = raw(output_html) if got_html_raw != output_html_raw: print("FAIL!", sample) print("GOT ".ljust(80, "-")) print(got_html) # print(repr(got_html_raw)) print("EXPECTED ".ljust(80, "-")) print(output_html) # print(repr(output_html_raw)) print() assert 0, sample
def render_templated_mail(request: Request, template: str, context: dict) -> t.Tuple[str, str, str]: """Render an email that is divided to three template files. The email is assembled from three different templates: * Read subject from a subject specific template $template.subject.txt * Generate HTML email from HTML template, $template.body.html * Generate plain text email from HTML template, $template.body.txt Make sure you have configured your template engine (Jinja 2) to read TXT templates beside HTML. HTML body goes through Premailer transform step, inlining any CSS styles. :param template: Template filename base string for template tripled (subject, HTML body, plain text body). For example ``email/my_message`` would map to templates ``email/my_message.subject.txt``, ``email/my_message.body.txt``, ``email/my_message.body.html`` :param context: Template context dictionary passed to the rendererer :return: Tuple(subject, text_body, html_body) """ subject = render(template + ".subject.txt", context, request=request) subject = subject.strip() html_body = render(template + ".body.html", context, request=request) text_body = render(template + ".body.txt", context, request=request) # Inline CSS styles html_body = premailer.transform(html_body) return subject, text_body, html_body
def test_basic_html_shortcut_function(self): """test the plain transform function""" html = """<html> <head> <title>Title</title> <style type="text/css"> h1, h2 { color:red; } strong { text-decoration:none } </style> </head> <body> <h1>Hi!</h1> <p><strong>Yes!</strong></p> </body> </html>""" expect_html = """<html> <head> <title>Title</title> </head> <body> <h1 style="color:red">Hi!</h1> <p><strong style="text-decoration:none">Yes!</strong></p> </body> </html>""" result_html = transform(html) compare_html(expect_html, result_html)
def send_mail(user, template_name, values, txt): fromaddrs = "*****@*****.**" #env = Environment(loader=FileSystemLoader('./')) env = Environment(loader=PackageLoader('packages', 'templates')) tpl = "./"+template_name template = env.get_template(tpl) html = template.render(stats=values) html = transform(html) if template_name == "crawl.html": title = "CrawText | %s | Crawl StatS" %values["project_name"] else: title = "CrawText | %s |%s Report" %(values["project_name"], template_name) msg = createhtmlmail(html, txt, title, fromaddrs) # The actual mail send server = smtplib.SMTP('smtp.gmail.com:587') server.starttls() server.login(username,passw) if type(user) == list: for u in user: server.sendmail(fromaddrs, u, msg) else: server.sendmail(fromaddrs, user, msg) server.quit() return True
def sanitize(note): debug('Sanitizing note content...', 2) if get_setting('evernote/sanitize/@applytemplate') == 'True': with open(get_setting('evernote/sanitize/template/text()'), 'r') as file: template = file.read() template = template.replace('{content}', note['content']) note['content'] = transform(template) preservedElements = [] preservePattern = get_setting('evernote/sanitize/preserve/pattern/text()') preserves = get_setting('evernote/sanitize/preserve/elements/text()').split(',') for preserve in preserves: matches = re.findall(preservePattern.format(preserve), note['content']) for match in matches: placeholder = '{%s}' % uuid.uuid4().hex preservedElements.append({'placeholder': placeholder, 'element': match}) note['content'] = note['content'].replace(match, placeholder, 1) note['content'] = re.sub(get_setting('evernote/sanitize/attributes/empty/text()'), '', note['content']) note['content'] = re.sub(get_setting('evernote/sanitize/attributes/prohibited/text()'), '', note['content']) note['content'] = re.sub(get_setting('evernote/sanitize/elements/text()'), '', note['content']) note['content'] = note['content'].encode('utf-8', errors='ignore') (note['content'], errors) = tidy_document(note['content']) for element in preservedElements: note['content'] = note['content'].replace(element['placeholder'], element['element']) if note['title'] != None: note['title'] = note['title'].replace('\n', ' ').replace('\r', '').replace(' ', ' ') else: note['title'] = get_setting('evernote/sanitize/defaulttitle/text()')
def send_new_comment(comment): talk = comment.talk subject = f'New comment received on {comment.talk.title}' msg = Message(subject) msg.html = transform( env.get_template('new_comment.html').render( subject=subject, talk=talk, comment=comment, domain=app.config['TALKY_DOMAIN'])) # Always sent notification if replies to the speaker recipients = [talk.speaker] # TODO Send notification of the replies to any parent commentators # Remove duplicates recipients = list(set(recipients)) # Remove the commenter if they are in the recipients if comment.email in recipients: recipients.pop(recipients.index(comment.email)) # Sent the email msg.bcc = _validate_emails(recipients) thr = Thread(target=send_async_email, args=[app, msg]) thr.start()
def html_email_user(self, subject, message, from_email=None): from premailer import transform from django.core.mail.message import EmailMultiAlternatives inlined_mail = transform(message) mail = EmailMultiAlternatives(subject, '', settings.SERVER_EMAIL, [self.email, ], ) mail.attach_alternative(inlined_mail, 'text/html') mail.send(fail_silently=True)
def render(self, _type, data): """Return a dict containing `text` and optional `html` formatted message for notification *_type*. """ text_template = self.env.get_template('%s.txt' % _type) html_template = None try: html_template = self.env.get_template('%s.html' % _type) except jinja2.exceptions.TemplateNotFound: pass # the subject is defined by the first line of the text # template with the format: subject=<subject> text = text_template.render(_type=_type, **data) line_break = text.index('\n') first_line = text[0:line_break] text = text[line_break + 1:] if first_line[0:8] != 'subject=': raise MalformedTemplate('Missing subject= line') subject = first_line[8:] if subject == '': raise MalformedTemplate('Subject missing') retval = {'subject': subject, 'text': text, 'html': None} if html_template is not None: html = html_template.render(type=_type, subject=subject, **data) # inline css with premailer html = transform(html) retval['html'] = html return retval
def make_mail(subject, text_template, html_template, context_vars, from_email, to_email, headers=None, **extra_kwargs): """Return an instance of EmailMultiAlternative with both plaintext and html versions.""" default_headers = { 'Reply-To': settings.DEFAULT_REPLY_TO_EMAIL, } if headers is not None: default_headers.update(headers) headers = default_headers mail = EmailMultiAlternatives(subject, render_email(text_template, context_vars), from_email, [to_email], headers=headers, **extra_kwargs) if html_template: html = transform(render_email(html_template, context_vars), 'https://' + Site.objects.get_current().domain) mail.attach_alternative(html, 'text/html') return mail
def _render(self, template_path, kwargs=None): params = {} if kwargs: params.update(kwargs) template = self.env.get_template(template_path) html = template.render(params) return premailer.transform(html)
def prepare_email(schedule): visualization = schedule.visualization err = None try: job = Job.objects.filter(completed_at__isnull=False, query__visualization=visualization, cached_until__gte=timezone.now()).order_by('-start_at')[:1].get() if job.query_checksum != job.query.checksum: err, job = execute_query(schedule.created_by, visualization) except Job.DoesNotExist: err, job = execute_query(schedule.created_by, visualization) if not err: rows, schema = job.get_rows() header = rows.pop(0) num_indexes = [i for i, v in enumerate(schema) if v.get('type') in ['FLOAT', 'INTEGER']] integer_indexes = [i for i, v in enumerate(schema) if v.get('type') in ['INTEGER']] totals = None if schedule.show_sum: totals = [reduce(lambda x,y: x + y, list(map(lambda x: x[i], rows)), 0) if v.get('type') in ['FLOAT', 'INTEGER'] else None for i, v in enumerate(schema)] body = transform(loader.render_to_string('emails/visualization.html', dict(visualization=visualization, job=job, rows=rows, absolute_url=settings.MAIN_HOST + reverse('visualizations_show', kwargs=dict(visualization_id=visualization.id)), schema=schema, num_indexes=num_indexes, integer_indexes=integer_indexes, header=header, schedule=schedule, totals=totals,))) return body
def generate_report_html(self, group, report_data): # Pre-set email with style information and header all_html = """ <style> h1 { margin: 0; padding: 0; } h2 { margin: 0; padding: 30px 0 10px 0; } th { text-align: left; } th, td { padding: 0 12px; } td { text-align: right; white-space: nowrap; } td:first-child { text-align: left; white-space: nowrap; } </style> <h1>Weekly Add-on %sReviews Report</h1> <h3>%s - %s</h3> """ % (('Content ' if group == 'content' else ''), self.week_begin, self.week_end) # For each group, execute the individual SQL reports # and build the HTML email. for section in report_data: all_html += '<h2>%s</h2>\n' % section[0] table_html = '<table>\n' table_html += '<tr><th>' + '</th><th>'.join( [header for header in section[1]]) + '</th></tr>\n' for row in section[2]: table_html += '<tr><td>' + '</td><td>'.join( [entry for entry in row]) + '</td></tr>\n' table_html += '</table>\n' all_html += table_html # Some email clients (e.g. GMail) require all styles to be inline. # 'transform' takes the file-wide styles defined above and transforms # them to be inline styles. return transform(all_html)
def render_email(request): try: template, variation, locale, inline, formats, payload = \ get_request_content(request) except: return JsonResponse({ 'success': False, 'error': "Invalid JSON in payload." }) try: rich_text = render_to_string( name_to_file(template), payload) plain_text = html2text.html2text(rich_text) if inline: rich_text = transform(rich_text) if formats == 'text': rich_text = None except: return JsonResponse({ 'success': False, 'error': "Template render error." }) return JsonResponse({ 'success': True, 'content': rich_text or plain_text, 'subject': payload["subject"], 'plainText': formats == 'text' })
def email(request, visualization_id): visualization = get_object_or_404(Visualization, pk=visualization_id, account=request.user.account) err = None try: job = Job.objects.filter(completed_at__isnull=False, query__visualization=visualization, cached_until__gte=timezone.now()).order_by('-start_at')[:1].get() if job.query_checksum != job.query.checksum: err, job = execute_query(request, visualization) except Job.DoesNotExist: err, job = execute_query(request, visualization) if err: return HttpResponse(err, 'application/json', status=404) subject = 'Colors: Your report ' + visualization.name + ' is ready. [' + timezone.now().isoformat() + ']' user = request.user rows, schema = job.get_rows() header = rows.pop(0) num_indexes = [i for i, v in enumerate(schema) if v.get('type') in ['FLOAT', 'INTEGER']] body = transform(loader.render_to_string('emails/visualization.html', dict(user=request.user, visualization=visualization, job=job, rows=rows, absolute_url=visualization.absolute_url(request), schema=schema, num_indexes=num_indexes, header=header))) email_message = EmailMultiAlternatives(subject, body, visualization.name + ' <colors+' + str(visualization.id) + '@luxola.com>', [user.email], reply_to=['*****@*****.**']) html_email = body email_message.attach_alternative(html_email, 'text/html') #email_message.send() return HttpResponse(html_email)
def send_number_email(competition, participants, application=None): if application: email = application.email else: email = participants[0].email context = { 'participants': participants, 'domain': settings.MY_DEFAULT_DOMAIN, 'competition': competition, 'application': True, } template = transform(render_to_string('registration/email/rm2015/number_email.html', context)) template_txt = render_to_string('registration/email/rm2015/number_email.txt', context) if len(participants) == 1: subject = u'Reģistrācijas apliecinājums - ELKOR Rīgas Velomaratons - %s' % participants[0].full_name else: subject = u'Reģistrācijas apliecinājums - ELKOR Rīgas Velomaratons' email_data = { 'em_to': email, 'subject': subject, 'html': template, 'text': template_txt, 'content_object': application or participants[0], } MailgunEmail.objects.create(**email_data) return True
def extend_email_template(template, context={}): t = get_template(template) http = 'https' if django_settings.DEBUG: http = 'http' base_url = '%s://%s' % (http, Site.objects.get_current().domain) return transform(t.render(context), base_url=base_url)
def send_email(user_emails, site, ping): """ Envia una notificación por email """ log.info('::send_email::') htmly = get_template('email/site-down.html') d = Context({ 'site': site.name, 'ping': ping }) html_content = htmly.render(d) email_html_content = transform(html_content) asunto = u'El sitio se ha caido' mail = 'Uptime Monitor<{0}>'.format(settings.DEFAULT_FROM_EMAIL) # recipients list if settings.UPTIME_ADMIN_EMAIL: log.debug('UPTIME_ADMIN_EMAIL') to = [settings.UPTIME_ADMIN_EMAIL] cc = user_emails else: log.debug('NO UPTIME_ADMIN_EMAIL') to = user_emails cc = [] msg = EmailMessage(asunto, email_html_content, mail, to, cc) msg.content_subtype = "html" msg.send()
def handle(self, *args, **options): self.options = options testing = True if 1 < len(args) else False sys.stdout = Unbuffered(sys.stdout) issue_number = args[0] context = read_newsletter_context(issue_number) # context['imgpath_prefix'] = 'cid:' newsletter_context_vars(context, issue_number) # subject = Header((u'[試寄] ' if testing else '') + context['params']['title'], 'utf-8') from_email = '"Mozilla Taiwan" <*****@*****.**>' text_content = render_to_string('newsletter/%s/mail.txt' % issue_number, context) html_content = render_to_string('newsletter/%s/index.html' % issue_number, context) mail_content = premailer.transform(html_content) soup = BeautifulSoup(html_content) subject = Header((u'[測試] ' if testing else '') + soup.title.string, 'utf-8') # headers = {'Reply-To': '*****@*****.**'} headers = {} # charset = 'utf-8' # image_path = 'bedrock/newsletter/templates/newsletter/%s/images/' % issue_number # images = [f for f in listdir(image_path) if not f.startswith('.') and isfile(join(image_path, f))] if not testing: with open('subscriptions.txt') as file: subscriptions = file.readlines() for subscription in subscriptions: self.send_mail(subject, headers, from_email, (subscription.rstrip(), ), text_content, mail_content, issue_number) sleep(10) elif args[1] == 'presend': for mail_address in NEWSLETTER_PRESEND_LIST: self.send_mail(subject, headers, from_email, (mail_address, ), text_content, mail_content, issue_number) sleep(10) else: self.send_mail(subject, headers, from_email, (args[1], ), text_content, mail_content, issue_number)
def _send_email(recipient, subject_line, template, extra_context=None, sender=None, admin=False): # CREATE THE MESSAGE BODY FROM THE TEMPLATE AND CONTEXT extra_context = extra_context or {} email_signature = render_to_string( 'emails/email_signature.txt', {'site_name': settings.SITE_NAME, 'site_url': settings.SITE_URL,} ) html_email_signature = render_to_string( 'emails/email_signature.html', {'site_name': settings.SITE_NAME, 'site_url': settings.SITE_URL,} ) context = { 'EMAIL_SIGNATURE': email_signature, 'HTML_EMAIL_SIGNATURE': html_email_signature, 'static_url': settings.STATIC_URL, 'SITE_NAME': settings.SITE_NAME, 'site_name': settings.SITE_NAME, 'SITE_URL': settings.SITE_URL, 'site_url': settings.SITE_URL, 'SUBJECT_LINE': subject_line, 'email_base_template': settings.EMAIL_BASE_HTML_TEMPLATE } context = dict(context.items() + extra_context.items()) # MODIFY THE RECIPIENTS IF ITS AN ADMIN EMAIL if admin: recipient = [x[1] for x in settings.NOTIFICATIONS_GROUP] else: recipient = [recipient] # WHO IS SENDING IT? if sender: sender = sender else: sender = settings.SITE_EMAIL # CHECK IF THERE'S AN HTML TEMPLATE? text_content = render_to_string(template, context) html_content = None try: html_template_name = template.replace('.txt', '.html') html_content = render_to_string(html_template_name, context) except TemplateDoesNotExist: pass # HERE IS THE ACTUAL MESSAGE NOW msg = EmailMultiAlternatives(subject_line, text_content, sender, recipient) if html_content: # USING PREMAILER TO PUT STYLES INLINE FOR CRAPPY YAHOO AND AOL WHO STRIP STYLES from premailer import transform html_content = transform(html_content) msg.attach_alternative(html_content, "text/html") # msg.content_subtype = "html" # DONT DO THIS! msg.send() return True
def send_email(self, text, html): """TODO: add docstring""" self.cur.execute('SELECT * FROM jobs WHERE id != \'TRACKER\'') new_opps = self.cur.fetchall() self.cur.execute('SELECT * FROM jobs WHERE id != \'TRACKER\'') old_opps = self.cur.fetchall() msg = MIMEMultipart('alternative') msg['Subject'] = 'Job updates!' html = ps.render(html, {'new': new_opps, 'old': old_opps}) text = ps.render(text, {'new': new_opps, 'old': old_opps}) html = premailer.transform(html) part1 = MIMEText(text, 'plain') part2 = MIMEText(html, 'html') msg.attach(part1) msg.attach(part2) msg['From'] = self.cfg['smtp']['user'] msg['To'] = self.cfg['recipient']['email'] context = ssl.create_default_context() with smtplib.SMTP_SSL(self.cfg['smtp']['url'], self.cfg['smtp']['port'], context=context) as server: server.login(self.cfg['smtp']['user'], self.cfg['smtp']['passwd']) server.sendmail(self.cfg['smtp']['user'], self.cfg['recipient']['email'], msg.as_string()) print('Database updated, email sent')
def generate_templates( project, html_template, text_template, current_date, current_time_utc): '''Generates the templates using Jinja2 templates :param html_template: The filename of the HTML template in the templates folder :param text_template: The filename of the text template in the templates folder :param current_date: The current date. ''' env = Environment( loader=FileSystemLoader('templates'), trim_blocks=True, lstrip_blocks=True, autoescape=True) env.filters['last_comment'] = last_comment env.filters['most_recent_comments'] = most_recent_comments env.filters['comments_within_lookback'] = comments_within_lookback env.filters['as_date'] = as_date log.info('Rendering HTML Template') html = env.get_template(html_template) rendered_html = premailer.transform(html.render( project=project, current_date=current_date, current_time_utc=current_time_utc)) log.info('Rendering Text Template') env.autoescape = False plaintext = env.get_template(text_template) rendered_plaintext = plaintext.render( project=project, current_date=current_date, current_time_utc=current_time_utc) return (rendered_html, rendered_plaintext)
def send(recipient, subject, title, content, button_link, button_caption): email_template = Environment(loader=FileSystemLoader(cfg['template_dir'])).get_template('email.html') html = transform(email_template.render( body=plain_text_to_html(content), title=title, button_caption=button_caption, button_link=button_link )) sender = MAIL_SENDER data = { "from": sender, "to": recipient, "subject": subject, "html": html, "text": "Please enable HTML emails." } requests.post( MAIL_SERVER, auth=MAIL_AUTH, data=data )
def generate_templates(project, html_template, text_template, current_date, current_time_utc, skip_inline_css=False): """Generates the templates using Jinja2 templates :param html_template: The filename of the HTML template in the templates folder :param text_template: The filename of the text template in the templates folder :param current_date: The current date. """ env = Environment(loader=FileSystemLoader("templates"), trim_blocks=True, lstrip_blocks=True, autoescape=True) env.filters["last_comment"] = last_comment env.filters["most_recent_comments"] = most_recent_comments env.filters["comments_within_lookback"] = comments_within_lookback env.filters["as_date"] = as_date log.info("Rendering HTML Template") html = env.get_template(html_template) if skip_inline_css: rendered_html = html.render(project=project, current_date=current_date, current_time_utc=current_time_utc) else: rendered_html = premailer.transform( html.render(project=project, current_date=current_date, current_time_utc=current_time_utc) ) log.info("Rendering Text Template") env.autoescape = False plaintext = env.get_template(text_template) rendered_plaintext = plaintext.render(project=project, current_date=current_date, current_time_utc=current_time_utc) return (rendered_html, rendered_plaintext)
def _render_message_body_as_html(self, context): """ Transform CSS into in-line style attributes. """ import premailer html = super(InlineCSSMixin, self)._render_message_body_as_html(context) return premailer.transform(html) if html else html
def mailer(aims, parent): msg = MIMEMultipart('alternative') msg['Subject'] = "Today in Treasure Seekers" msg['From'] = "Nathan Fisher <*****@*****.**>" # Your from name and email address msg['To'] = parent['email'] html = transform(render_template('email.html', body=gethtmlContent(aims, parent))) part1 = MIMEText(html, 'html') #html = "<em>Mandrill speaks <strong>HTML</strong></em>" #part2 = MIMEText(html, 'html') username = os.environ['MANDRILL_USERNAME'] password = os.environ['MANDRILL_PASSWORD'] msg.attach(part1) #msg.attach(part2) s = smtplib.SMTP('smtp.mandrillapp.com', 587) s.login(username, password) print "Sending mail..to " + parent['email'] if msg['To']: s.sendmail(msg['From'], msg['To'], msg.as_string()) s.quit()
def paypal_validate_plan_signup(sender, **kwargs): ipn_obj = sender valid = True trans = TransactionSubscription.objects.get(id=int(ipn_obj.invoice)) if ipn_obj.period3 != '1 M': valid = False elif ipn_obj.recurring != '1': valid = False elif ipn_obj.mc_amount3 != trans.gross_amount: valid = False if not valid: subject, from_email = 'DA admin - Paypal subscription error', 'Directo al Artista <*****@*****.**>' message = render_to_string('email/paypal_subs_error.html', { 'trans': trans, 'object': ipn_obj.item_name, }) html_content = render_to_string('email/global/template.html', { 'email_title': 'DA admin - Paypal subscription error', 'email_content': message, }) html_content = transform(html_content) text_content = strip_tags(html_content) msg = EmailMultiAlternatives(subject, text_content, from_email, ['*****@*****.**']) msg.attach_alternative(html_content, "text/html") msg.send(fail_silently=True) return valid
def send_email_to_af_user_on_assignment_by_hl(cls, request=None, request_assignment=None): context_data = { "request": request, "request_assignment": request_assignment } subject = "A volunteer has started working on your request." text_body = render_to_string( template_name= "email_templates/email_notify_af_about_hl_assigned_request.txt", context=context_data, ) html_body = render_to_string( "email_templates/email_notify_af_about_hl_assigned_request.html", context_data, ) html_body_transformed = transform(html_body, exclude_pseudoclasses=False) msg = EmailMultiAlternatives( subject=subject, to=[request.owner.user.email], bcc=[settings.BCC_ADDRESS_FOR_ALL_EMAILS], body=text_body, ) msg.attach_alternative(html_body_transformed, "text/html") msg.send() return True
def send(recipient, subject, title, content, button_link, button_caption): email_template = Environment(loader=FileSystemLoader(cfg['template_dir'])).get_template('email.html') html = transform(email_template.render( body=plain_text_to_html(content), title=title, button_caption=button_caption, button_link=button_link )) # TODO - remove this recipient = '*****@*****.**' # sender = MAIL_SENDER sender = '*****@*****.**' data = { "from": sender, "to": recipient, "subject": subject, "html": html, "text": "" } requests.post( MAIL_SERVER, auth=MAIL_AUTH, data=data )
def generate_content( md_content: str, theme: str = os.path.join(os.path.dirname(os.path.abspath(__file__)), "style.css"), context: Optional[dict] = None, ): """ Generates the content of an email to be sent. This method actually renders two templates: 1. The extremely simple local template, which writes the stylesheet, header and user-provided md_content to the message 2. The result of 1. is also treated as a jinja template, and rendered using the arguments provided in the context parameter Apart from rendering the template, this method also does two other things: 1. Applies an additional highlight renderer with better support for code blocks 2. Uses premailer.transform to bake the css into the HTML """ if not context: context = {} with open(theme) as f: theme = f.read() markdown = mistune.Markdown(renderer=HighlightRenderer()) with open( os.path.join(os.path.dirname(os.path.abspath(__file__)), "template.jinja2"), ) as t: template = Template(t.read()) content = transform( template.render(content=markdown(md_content), stylesheet=theme)) t = Template(content) return t.render(context)
def send_templated_mail(request, recipients, template, context, sender=None): """Send out templatized HTML and plain text emails. Each HTML email should have a plain text fallback. Premailer package is used to convert any CSS styles in HTML email messages to inline, so that email clients display them. The email is assembled from three different templates: * Read subject from a subject specific template $template.subject.txt * Generate HTML email from HTML template, $template.body.html * Generate plain text email from HTML template, $template.body.txt Make sure you have configured your template engine (Jinja 2) to read TXT templates beside HTML. :param request: HTTP request, passed to the template engine. Request configuration is used to get hold of the configured mailer. :param recipients: List of recipient emails :param template: Template filename base string for template tripled (subject, HTML body, plain text body). For example ``email/my_message`` would map to templates ``email/my_message.subject.txt``, ``email/my_message.body.txt``, ``email/my_message.body.html`` :param context: Template context variables as a dict :param sender: Override the sender email - if not specific use the default set in the config as ``mail.default_sender`` """ assert recipients assert len(recipients) > 0 assert type( recipients) != str, "Please give a list of recipients, not a string" for r in recipients: assert r, "Received empty recipient when sending out email {}".format( template) subject = render(template + ".subject.txt", context, request=request) subject = subject.strip() html_body = render(template + ".body.html", context, request=request) text_body = render(template + ".body.txt", context, request=request) if not sender: sender = request.registry.settings["mail.default_sender"] # Add enveloped From: sender_name = request.registry.settings.get("mail.default_sender_name") if sender_name: sender = formataddr((str(Header(sender_name, 'utf-8')), sender)) # Inline CSS styles html_body = premailer.transform(html_body) message = Message(subject=subject, sender=sender, recipients=recipients, body=text_body, html=html_body) mailer = get_mailer(request) mailer.send(message)
def render(self, context={}, template=None): config_context = SimpleMailConfig.get_singleton().context config_context['banner_url'] = self.banner_url config_context.update(context) config_context.update({ 'title': Template(self.title).render(Context(context)), 'subject': Template("{%% autoescape off %%}%s{%% endautoescape %%}" % self.subject).render(Context(context)), 'footer_content': Template(config_context.get('footer_content')).render( Context(context)), 'button_label': Template(self.button_label).render(Context(context)), 'button_link': Template(self.button_link).render(Context(context)), 'body': Template(self.body).render(Context(context)), }) if template is None: template = getattr(settings, 'SIMPLE_MAIL_DEFAULT_TEMPLATE', 'simple_mail/default.html') html = loader.render_to_string(template, config_context) html = transform(html) h = html2text.HTML2Text() h.ignore_images = True h.ignore_tables = True text = h.handle(html) response = { 'subject': config_context.get('subject'), 'message': text, 'html_message': html } return response
def promoter_validation_accept(modeladmin, request, queryset): for user in queryset: transactions = TransactionContact.objects.filter(proprietary_member=user).filter(payment_complete=True) for trans in transactions: transitem = TransactionContactItem.objects.get(transaction=trans) artist_profile = ArtistProfile.objects.get(id=transitem.artist_profile.id) contact = GenericUser.objects.get(id=artist_profile.proprietary_user.id) # Send mail email = user.email subject, from_email = 'Contacto de artista', 'Directo al Artista <*****@*****.**>' message = render_to_string('email/promoter_validation_accepted.html', { 'user': user, 'artist_profile': artist_profile, 'contact': contact, }) html_content = render_to_string('email/global/template.html', { 'email_title': 'Contacto de artista', 'email_content': message, }) html_content = transform(html_content) text_content = strip_tags(html_content) msg = EmailMultiAlternatives(subject, text_content, from_email, [email]) msg.attach_alternative(html_content, "text/html") msg.send(fail_silently=True) transactions.update(contact_provided=True) queryset.update(promoter_validated=True)
def send_finalized_email(fileset): subject = 'Preview: {}'.format(str(fileset)) template_name = 'finalized_email.html' watchers = fileset.project.list_watchers() if not watchers: return emails = [watcher.user.email for watcher in watchers] if not emails: return kwargs = { 'appengine_config': appengine_config, 'config': appengine_config.jetway_config, 'fileset': fileset, } if fileset.commit and fileset.commit.author: kwargs['author'] = users.User.get_by_email(fileset.commit.author.email) sender = appengine_config.EMAIL_SENDER template = _env.get_template(template_name) content = template.render(kwargs) html = premailer.transform(content) fp = cStringIO.StringIO() fp.seek(0) emails = [email for email in emails if email is not None] message = mail.EmailMessage(sender=sender, subject=subject) message.to = list(set([email.strip() for email in emails[:10]])) message.html = html message.send()
def _get_email(bot, db, title, additional_content=None): """ Return the content to be used for the newsletter. """ # Get urls from the db bot.lock.acquire() urls = serialize.read_state(db) bot.lock.release() entries = [ entry for entry in _get_email_content(bot, urls[:]) if len(entry['url']) != 0 ] context = {'title': title} for entry in entries: if 'github.com/punchagan/childrens-park' in entry['url']: context.setdefault('code_updates', []).append(entry) else: context.setdefault('shared_links', []).append(entry) if additional_content is not None: context.update(additional_content) template = join(HERE, 'data', 'newsletter_template.html') return transform(render_template(template, context))
def render_email(request): try: template, variation, locale, inline, formats, payload = \ get_request_content(request) except: return JsonResponse({ 'success': False, 'error': "Invalid JSON in payload." }) try: rich_text = render_to_string(name_to_file(template), payload) plain_text = html2text.html2text(rich_text) if inline: rich_text = transform(rich_text) if formats == 'text': rich_text = None except: return JsonResponse({ 'success': False, 'error': "Template render error." }) return JsonResponse({ 'success': True, 'content': rich_text or plain_text, 'subject': payload["subject"], 'plainText': formats == 'text' })
def html(self): """ Returns HTML formatted and styled version of body """ html = markdown.markdown('\n'.join(self.body)) if self.style: return premailer.transform('<style>\n' + self.style + '\n</style>\n' + html) return html
def handler(): in_path = posixpath.join( pathlib.Path(__file__).parent.absolute(), "./raw/") out_path = posixpath.join( pathlib.Path(__file__).parent.absolute(), "./minified/") for file_name in files: print("processing %s" % (file_name)) template = open(posixpath.join(in_path, file_name), encoding="utf-8", mode="r").read() replaced = transform( template, base_path=in_path, disable_validation=True, cache_css_parsing=False, disable_link_rewrites=True, exclude_pseudoclasses=True, ) replaced = re.sub(r"#([a-z_]+)#", r"{{\1}}", replaced) replaced = re.sub(r"\u00A0", "", replaced) f = open( posixpath.join(out_path, file_name), encoding="utf-8", mode="w", ) f.write(replaced) f.close()
def __call__(self): html = self.render() soup = BeautifulSoup(html) for img in soup.findAll('img', {'class' : 'leadimage'}): img['hspace'] = 8 img['vspace'] = 8 utm = self.getUTM(source='newsletter', medium='email', campaign=self.newsletter_title); for a in soup.findAll('a'): if '?' in a['href']: a['href'] = '%s&%s' % (a['href'], utm) else: a['href'] = '%s?%s' % (a['href'], utm) html = premailer.transform(soup.prettify()) tags = ['dl', 'dt', 'dd'] for tag in tags: html = html.replace("<%s" % tag, "<div") html = html.replace("</%s" % tag, "</div") return html