def make_lines_for_book(book): title = wrap(book['title'], 37) lines = [] for line in title.split('\n'): lines.append([ ('string', line), ('bold', 'true'), ('align', 'left'), ('font', 'modern'), ]) authors = book['authors'] if len(authors) == 1: by = 'By %s' % authors[0] elif len(authors) == 2: by = 'By %s and %s' % (authors[0], authors[1]) else: try: by = 'By %s and %s' % (', '.join(authors[:-1]), authors[-1]) except IndexError: by = None if by: by = wrap(by, 37) for line in by.split('\n'): lines.append([ ('string', line), ]) lines.append([ ('string', 'ISBN: %s' % book['isbn']), ]) return lines
def prepare_mail(template, name, title, url, initiator): from django.conf import settings abuse = settings.ABUSE_EMAIL site = settings.SITE_DOMAIN # Plain text email body_params = { 'name': name, 'title_and_link': '{{ title_and_link }}', 'abuse_address': abuse, 'site_name': settings.SITE_NAME, 'site_link': settings.SITE_BASE + '/', 'initiator': initiator } body = render_to_string(template, body_params) body = re.sub('\n(\n)+', '\n\n', body) body = wrap(body.strip(), 74) + '\n' body = body.replace('{{ title_and_link }}', ' %s\n %s' % (title, url)) # HTML email name = escape(name) title = escape(title) initiator = escape(initiator) html_params = { 'name': name, 'title_and_link': ' <a href="%s" style="color:blue"><b>%s</b></a>' % (url, title), 'abuse_address': '<a href="mailto:%s" style="color:blue">%s</a>' % (abuse, abuse), 'site_name': settings.SITE_NAME, 'site_link': '<a href="%s/" style="color:blue">%s</a>' % (settings.SITE_BASE, settings.SITE_DOMAIN), 'initiator': initiator } html = render_to_string(template, html_params) html = re.sub('\n(\n)+', '\n\n', html.strip()) html = html.replace('\n\n', '<p>').replace('\n', '<br>') html = '<div style="font:14px Arial,sans-serif;color:#000;background:#fff;max-width:420px"><p><img src="%s" alt="%s"><p>%s</div>\n' % (settings.EMAIL_LOGO, settings.SITE_NAME, html) return {'body': body, 'html': html}
def _send_email(data): message = EmailMessage() message.subject = data.get('subject') message.body = wrap( render_to_string('share_page/email.txt', {'data': data}), 75) message.to = [data.get('to_address')] message.send()
def wordwrap(value, arg): """ Wraps words at specified line length. Argument: number of characters to wrap the text at. """ return wrap(value, int(arg))
def email_confirmation(self, email): body = wrap(render_to_string('gift_registry/email_thanks.txt', {'gift': self.gift, 'giver': self, 'site': Site.objects.get_current()}), 70) send_mail( settings.GIFT_REGISTRY_SETTINGS['EVENT_NAME'], body, settings.DEFAULT_FROM_EMAIL, [email], fail_silently=False)
def wrap_up_email(to, text): text = wrap(strip_tags(text), 70) text += "\n\n" text += u"URL: %s" % (settings.IDTRACKER_BASE_URL + group.about_url()) send_mail_text(request, to, None, u"Milestones changed for %s %s" % (group.acronym, group.type.name), text)
def quote_post(self, post): """ Returns a raw post body which quotes the given Post. """ return u'%s wrote:\n\n%s\n\n' % ( escape(post.user.username), quote_post_re.sub('> ', wrap(normalize_newlines(post.body), 80)), )
def wordwrap(value, arg): """ Wraps words at specified line length. Argument: number of characters to wrap the text at. """ from django.utils.text import wrap return wrap(value, int(arg))
def format_quote(sender, body): lines = wrap(body, 60).split('\n') for i, line in enumerate(lines): lines[i] = "> %s" % line quote = '\n'.join(lines) return ugettext(u"%(sender)s wrote:\n%(body)s") % { 'sender': sender, 'body': quote }
def wrap_up_email(to, text): text = wrap(strip_tags(text), 70) text += "\n\n" text += u"URL: %s" % (settings.IDTRACKER_BASE_URL + urlreverse( "wg_charter", kwargs=dict(acronym=group.acronym))) send_mail_text( request, to, None, u"Milestones changed for %s %s" % (group.acronym, group.type.name), text)
def format_quote(text): """ Wraps text at 55 chars and prepends each line with `> `. Used for quoting messages in replies. """ lines = wrap(text, 55).split('\n') for i, line in enumerate(lines): lines[i] = "> %s" % line return '\n'.join(lines)
def format_quote(sender, body): """ Wraps text at 55 chars and prepends each line with `> `. Used for quoting messages in replies. """ lines = wrap(body, 55).split("\n") for i, line in enumerate(lines): lines[i] = "> %s" % line quote = "\n".join(lines) return ugettext(u"%(sender)s wrote:\n%(body)s") % {"sender": sender, "body": quote}
def test_wrap(self): digits = "1234 67 9" self.assertEqual(text.wrap(digits, 100), "1234 67 9") self.assertEqual(text.wrap(digits, 9), "1234 67 9") self.assertEqual(text.wrap(digits, 8), "1234 67\n9") self.assertEqual(text.wrap("short\na long line", 7), "short\na long\nline") self.assertEqual(text.wrap("do-not-break-long-words please? ok", 8), "do-not-break-long-words\nplease?\nok") long_word = "l%sng" % ("o" * 20) self.assertEqual(text.wrap(long_word, 20), long_word) self.assertEqual(text.wrap("a %s word" % long_word, 10), "a\n%s\nword" % long_word) self.assertEqual(text.wrap(lazystr(digits), 100), "1234 67 9")
def wrap_up_email(addrs, text): subject = u"Milestones changed for %s %s" % (group.acronym, group.type.name) if re.search("Added .* for review, due",text): subject = u"Review Required - " + subject text = wrap(strip_tags(text), 70) text += "\n\n" text += u"URL: %s" % (settings.IDTRACKER_BASE_URL + group.about_url()) send_mail_text(request, addrs.to, None, subject, text, cc=addrs.cc)
def test_wrap(self): digits = '1234 67 9' self.assertEqual(text.wrap(digits, 100), '1234 67 9') self.assertEqual(text.wrap(digits, 9), '1234 67 9') self.assertEqual(text.wrap(digits, 8), '1234 67\n9') self.assertEqual(text.wrap('short\na long line', 7), 'short\na long\nline') self.assertEqual(text.wrap('do-not-break-long-words please? ok', 8), 'do-not-break-long-words\nplease?\nok') long_word = 'l%sng' % ('o' * 20) self.assertEqual(text.wrap(long_word, 20), long_word) self.assertEqual(text.wrap('a %s word' % long_word, 10), 'a\n%s\nword' % long_word) self.assertEqual(text.wrap(lazystr(digits), 100), '1234 67 9')
def format_quote(sender, body): """ Wraps text at 55 chars and prepends each line with `> `. Used for quoting messages in replies. """ lines = wrap(body, 55).split('\n') for i, line in enumerate(lines): lines[i] = "> %s" % line quote = '\n'.join(lines) return u"%(sender)s wrote:\n%(body)s" % {'sender': sender, 'body': quote}
def format_quote(sender, body): """ Wraps text at 55 chars and prepends each line with `> `. Used for quoting messages in replies. """ lines = wrap(body, 55).split('\n') for i, line in enumerate(lines): lines[i] = "> %s" % line return _(u"%(sender)s wrote:\n%(body)s") % { 'sender': sender, 'body': quote, }
def format_field(case, field): """ Format long-form text as required by the discipline module, making substitutions as appropriate. """ text = eval("case."+field) if text is None or text.strip() == "": return mark_safe('<p class="empty">None</p>') if field == 'contact_email_text': # special case: contact email is plain text return mark_safe("<pre>" + escape(wrap(case.substitite_values(unicode(text)), 78)) + "</pre>") else: return mark_safe(textile_restricted(case.substitite_values(unicode(text))))
def email_confirmation(self, email): body = wrap( render_to_string( "gift_registry/email_thanks.txt", {"gift": self.gift, "giver": self, "site": Site.objects.get_current()} ), 70, ) send_mail( settings.GIFT_REGISTRY_SETTINGS["EVENT_NAME"], body, settings.DEFAULT_FROM_EMAIL, [email], fail_silently=False, )
def _email_student_note(note): """ Email advising note to student. """ subject = "SFU Advising Note" from_email = note.advisor.email() email = note.student.email() content = wrap(note.text, 72) attach = [] if note.file_attachment: note.file_attachment.open() attach = [(note.attachment_filename(), note.file_attachment.read(), note.file_mediatype)] mail = EmailMessage(subject, content, from_email, [email], cc=[from_email], attachments=attach) mail.send()
def send_contact_email(self): """ Send contact email to the student and CC instructor """ body = wrap(self.substitite_values(self.contact_email_text), 72) email = EmailMessage( subject='Academic dishonesty in %s' % (self.get_origsection()), body=body, from_email=self.owner.email(), to=[self.student.email()], cc=[self.owner.email()], ) email.send(fail_silently=False)
def send_contact_email(self): """ Send contact email to the student and CC instructor """ body = wrap(self.substitite_values(self.contact_email_text), 72) email = EmailMessage( subject='Academic dishonesty in %s' % (self.offering), body=body, from_email=self.owner.email(), to=[self.student.email()], cc=[self.owner.email()], ) email.send(fail_silently=False)
def test_wrap(self): digits = "1234 67 9" self.assertEqual(text.wrap(digits, 100), "1234 67 9") self.assertEqual(text.wrap(digits, 9), "1234 67 9") self.assertEqual(text.wrap(digits, 8), "1234 67\n9") self.assertEqual(text.wrap("short\na long line", 7), "short\na long\nline") self.assertEqual( text.wrap("do-not-break-long-words please? ok", 8), "do-not-break-long-words\nplease?\nok", ) long_word = "l%sng" % ("o" * 20) self.assertEqual(text.wrap(long_word, 20), long_word) self.assertEqual(text.wrap("a %s word" % long_word, 10), "a\n%s\nword" % long_word) self.assertEqual(text.wrap(lazystr(digits), 100), "1234 67 9")
def quote_email(text): """ wrap and add leading '>'s to a message """ s = wrap(text, 75) return '\n'.join(['> %s' % l for l in s.split('\n')])
def write_text(self, text): wrapped_text = wrap(strip_tags(text), 80) for line in wrapped_text.splitlines(): self.write_line(line)
"""Default variable filters."""
from django.template import Variable, Library from django.conf import settings from django.utils.translation import ugettext, ungettext from django.utils.encoding import force_unicode, iri_to_uri from django.utils.safestring import mark_safe, SafeData import urllib import urllib2 import urlparse import html2text from django.utils.text import wrap for i in range(1,10): value = " , Ehrhardt-Martinex, Karen; November 2008, Report # E87," arg = 2 dogma = html2text.name2cp(value) print dogma a=1 print wrap(value, int(arg))
def mail_org(self, org): members = org.engagement_set.filter(org_admin=True) if members: member = org.engagement_set.filter(org_admin=True)[0] if member.person.user is not None: return person = member.person username = (person.first_name.strip() + '.' + person.last_name.strip())[:30] else: #print u'Pas de membre pour %s' % org.label() person = None username = org.label().lower() username = username.replace('association ', '') username = username.replace('assoc ', '') username = username[:12] try: email = (person and member.email) or org.contacts.filter(contact_medium__label='Email')[0].content except IndexError: #print u'Pas d\'email pour %s' % org.label() return username = unicodedata.normalize('NFKD', unicode(username)) username = username.encode('ASCII', 'ignore') username = username.lower() username = username.replace(' ', '_') username = re.sub(r'[^a-z0-9_\.-]', '-', username) username = re.sub(r'[_.-]+$', '', username) for i in range(0, 10): if i == 0: _username = username else: _username = username + '%u' % i if not User.objects.filter(username=_username).exists(): username = _username break #print 'L\'identifiant %s existe déjà' % _username password = ''.join([random.choice(string.digits + string.letters) for i in range(0, 6)]).lower() if person is None: person = Person.objects.create(last_name=u'Votre nom', first_name=u'Votre prénom', username=username) member = Engagement.objects.create(person=person, email=email, organization=org, org_admin = True) user = User( first_name=person.first_name[:30], last_name=person.last_name[:30], email=email, username=username ) user.set_password(password) user.save() person.user = user person.save() print u'Envoi effectué à %s, %s, %s:%s' % (email, org.label(), username, password) #print '%s;%s' % (username, password) context = {'username': username, 'password': password, 'sender': self.sender} subject = u'Accédez à votre fiche dans achetons-solidaires-paca.com' text = wrap(render_to_string('mailing-%s.txt' % self.slug, context), 72) html = render_to_string('mailing-%s.html' % self.slug, context) #send_html_mail(subject, email, context, template='mailing.html', sender=self.sender) msg = EmailMultiRelated(subject, text, self.sender, [email]) msg.attach_alternative(html, 'text/html') soup = BeautifulSoup(html) for index, tag in enumerate(soup.findAll(image_finder)): if tag.name == u'img': name = 'src' msg.attach_related_file(settings.PROJECT_PATH + '/coop_local/static/img/' + tag[name]) msg.send()
def test_wrap(inp): text.wrap(inp, 8)
def send_plea_email(context_data): """ Sends a plea email. All addresses, content etc. are defined in settings. context_data: dict populated by form fields """ case = Case.objects.filter( urn__iexact=context_data["case"]["urn"].upper(), sent=False, imported=True).first() if not case: case = Case.objects.create(urn=context_data["case"]["urn"].upper(), sent=False, imported=False) court_obj = Court.objects.get_court(context_data["case"]["urn"], ou_code=case.ou_code) email_address = context_data.get("your_details", {}).get("email", False) email_address = email_address or context_data.get("company_details", {}).get("email", False) context_data["email"] = email_address # add DOH / name to the email subject for compliance with the current format if not context_data["notice_type"]["sjp"]: if isinstance(context_data["case"]["date_of_hearing"], basestring): date_of_hearing = parser.parse(context_data["case"]["date_of_hearing"]) else: date_of_hearing = context_data["case"]["date_of_hearing"] context_data["email_date_of_hearing"] = date_of_hearing.strftime("%Y-%m-%d") if context_data["case"]["plea_made_by"] == "Defendant": first_name = context_data["your_details"]["first_name"] middle_name = context_data["your_details"]["middle_name"] last_name = context_data["your_details"]["last_name"] else: first_name = context_data["company_details"]["first_name"] middle_name = "" last_name = context_data["company_details"]["last_name"] if "date_of_birth" in context_data["case"]: context_data["your_details"]["date_of_birth"] = context_data["case"]["date_of_birth"] context_data["email_name"] = " ".join([last_name.upper(), first_name, middle_name]).strip() # Add Welsh flag if journey was completed in Welsh if translation.get_language() == "cy": context_data["welsh_language"] = True if context_data["notice_type"]["sjp"]: case.initiation_type = "J" case.language = translation.get_language().split("-")[0] case.name = standardise_name(first_name, last_name) case.completed_on = dt.datetime.now() if context_data["case"]["plea_made_by"] == "Company representative": if case.extra_data and "OrganisationName" in case.extra_data: case.extra_data["OrganisationName"] = context_data.get("company_details", {}).get("company_name") else: case.extra_data = {"OrganisationName": context_data.get("company_details", {}).get("company_name")} if email_address: case.email = email_address case.send_user_email = True case.save() if getattr(settings, "STORE_USER_DATA", False): encrypt_and_store_user_data(case.urn, case.id, context_data) if not court_obj.test_mode: # don't add test court entries to the anon stat data email_count = CourtEmailCount() email_count.get_from_context(context_data, court=court_obj) email_count.save() email_count_id = email_count.id else: # use a fake email count ID as we're using a test record email_count_id = "XX" email_send_court.delay(case.id, email_count_id, context_data) if court_obj.plp_email: email_send_prosecutor.delay(case.id, context_data) if email_address: data = { "urn": format_for_region(context_data["case"]["urn"]), "plea_made_by": context_data["case"]["plea_made_by"], "number_of_charges": context_data["case"]["number_of_charges"], "contact_deadline": context_data["case"]["contact_deadline"], "plea_type": get_plea_type(context_data), "court_name": court_obj.court_name, "court_email": court_obj.court_email } email_template = "emails/user_plea_confirmation" try: if context_data["notice_type"]["sjp"]: email_template = "emails/user_plea_confirmation_sjp" except KeyError: pass html_body = render_to_string(email_template + ".html", data) txt_body = wrap(render_to_string(email_template + ".txt", data), 72) subject = _("Online plea submission confirmation") email_send_user.delay(case.id, email_address, subject, html_body, txt_body) else: case.add_action("No email entered, user email not sent", "") return True
def wordwrap(value, arg): """Wrap words at `arg` line length.""" return wrap(value, int(arg))
def truncatedDescription(self, obj): lines = wrap(obj.description, 200).split('\n') lines = [line[:200] for line in lines] return '<br/>'.join(lines)
data = { "urn": format_for_region(context_data["case"]["urn"]), "plea_made_by": context_data["case"]["plea_made_by"], "number_of_charges": context_data["case"]["number_of_charges"], "contact_deadline": context_data["case"]["contact_deadline"], "plea_type": get_plea_type(context_data), "court_address": court_obj.court_address, "court_email": court_obj.court_email } email_template = "emails/user_plea_confirmation" try: if context_data["notice_type"]["sjp"]: email_template = "emails/user_plea_confirmation_sjp" except KeyError: pass html_body = render_to_string(email_template + ".html", data) txt_body = wrap(render_to_string(email_template + ".txt", data), 72) subject = _("Online plea submission confirmation") email_send_user.delay(case.id, email_address, subject, html_body, txt_body) else: case.add_action("No email entered, user email not sent", "") return True
def wordwrap(value, arg): """Wrap words at `arg` line length.""" # 按照行的长度来打包单词 return wrap(value, int(arg))
def wordwrapwithindent(value, arg): lines = wrap(value, int(arg)).split('\n') return ' ' + '\n '.join(lines)
def mail_org(self, org): members = org.engagement_set.filter(org_admin=True) if members: member = org.engagement_set.filter(org_admin=True)[0] if member.person.user is not None: return person = member.person username = (person.first_name.strip() + '.' + person.last_name.strip())[:30] else: #print u'Pas de membre pour %s' % org.label() person = None username = org.label().lower() username = username.replace('association ', '') username = username.replace('assoc ', '') username = username[:12] try: email = (person and member.email) or org.contacts.filter( contact_medium__label='Email')[0].content except IndexError: #print u'Pas d\'email pour %s' % org.label() return username = unicodedata.normalize('NFKD', unicode(username)) username = username.encode('ASCII', 'ignore') username = username.lower() username = username.replace(' ', '_') username = re.sub(r'[^a-z0-9_\.-]', '-', username) username = re.sub(r'[_.-]+$', '', username) for i in range(0, 10): if i == 0: _username = username else: _username = username + '%u' % i if not User.objects.filter(username=_username).exists(): username = _username break #print 'L\'identifiant %s existe déjà' % _username password = ''.join([ random.choice(string.digits + string.letters) for i in range(0, 6) ]).lower() if person is None: person = Person.objects.create(last_name=u'Votre nom', first_name=u'Votre prénom', username=username) member = Engagement.objects.create(person=person, email=email, organization=org, org_admin=True) user = User(first_name=person.first_name[:30], last_name=person.last_name[:30], email=email, username=username) user.set_password(password) user.save() person.user = user person.save() print u'Envoi effectué à %s, %s, %s:%s' % (email, org.label(), username, password) #print '%s;%s' % (username, password) context = { 'username': username, 'password': password, 'sender': self.sender } subject = u'Accédez à votre fiche dans achetons-solidaires-paca.com' text = wrap(render_to_string('mailing-%s.txt' % self.slug, context), 72) html = render_to_string('mailing-%s.html' % self.slug, context) #send_html_mail(subject, email, context, template='mailing.html', sender=self.sender) msg = EmailMultiRelated(subject, text, self.sender, [email]) msg.attach_alternative(html, 'text/html') soup = BeautifulSoup(html) for index, tag in enumerate(soup.findAll(image_finder)): if tag.name == u'img': name = 'src' msg.attach_related_file(settings.PROJECT_PATH + '/coop_local/static/img/' + tag[name]) msg.send()
def generate_images(self): """ Creates images for promotion of the talk """ speaker = self.submission.speakers.all()[0] if speaker.avatar: avatar = get_thumbnail(speaker.avatar, '160x160', crop='center', quality=80) avatar = Image.open(avatar.storage.path(avatar.name)) elif speaker.get_gravatar: r = requests.get( "https://www.gravatar.com/avatar/" + speaker.gravatar_parameter, allow_redirects=True ) if r.status_code == 200: avatar = Image.open(BytesIO(r.content)) avatar = avatar.resize((160, 160), Image.ANTIALIAS) else: avatar = Image.new('RGBA', (160, 160), 0) else: avatar = Image.new('RGBA', (160, 160), 0) # Now turn the avatar circular bigsize = (avatar.size[0] * 3, avatar.size[1] * 3) mask = Image.new('L', bigsize, 0) draw = ImageDraw.Draw(mask) draw.ellipse((0, 0) + bigsize, fill=255) mask = mask.resize(avatar.size, Image.ANTIALIAS) avatar.putalpha(mask) data_dir = os.path.join(os.path.dirname(__file__), "some_banners") background = Image.open( os.path.join(data_dir, "some_twitter_card.png") ) new_card = Image.new('RGBA', background.size, (0, 0, 0, 0)) # Add the background new_card.paste(background, (0, 0)) # Add the avatar new_card.paste(avatar, (58, 77), mask) # Write the speaker names draw = ImageDraw.Draw(new_card) font = ImageFont.truetype(os.path.join(data_dir, "fonts", "Poppins-SemiBold.ttf"), 56) offset = 60 speaker_lines = wrap(self.speakers, 30).split("\n") for line in speaker_lines: draw.text((280, offset), line, (230, 28, 93), font=font) offset += 65 font = ImageFont.truetype(os.path.join(data_dir, "fonts", "Poppins-SemiBold.ttf"), 56) title = self.submission.title if self.keynote: title = "Keynote: " + title title_lines = wrap(title, 30).split("\n") lines_available = 5 - len(speaker_lines) if len(title_lines) > lines_available: title_lines[lines_available - 1] += "..." if lines_available < 0: lines_available = 0 for line in title_lines[:lines_available]: draw.text((280, offset), line, (255, 255, 255), font=font) offset += 65 # Render it to screen # new_card.show() image_path = twitter_card_path(self, "blahblah.png") full_path = os.path.join(settings.MEDIA_ROOT, image_path) new_card.save(full_path, format='png') self.twitter_card_image = image_path self.save()
def break_text(s,num=60,sep="<br />"): """ Return string s with separator every num words.""" from django.utils.text import wrap from django.utils.safestring import mark_safe return wrap(mark_safe(s), num).replace('\n', sep)