def send_mails(mails): """Send multiple mails in single connection.""" filename = os.path.join(settings.STATIC_ROOT, 'email-logo.png') with open(filename, 'rb') as handle: image = MIMEImage(handle.read()) image.add_header('Content-ID', '<*****@*****.**>') image.add_header('Content-Disposition', 'inline', filename='weblate.png') connection = get_connection() try: connection.open() except Exception as error: report_error(error, prefix='Failed to send notifications') connection.close() return try: for mail in mails: email = EmailMultiAlternatives( settings.EMAIL_SUBJECT_PREFIX + mail['subject'], html2text(mail['body']), to=[mail['address']], headers=mail['headers'], connection=connection, ) email.mixed_subtype = 'related' email.attach(image) email.attach_alternative(mail['body'], 'text/html') email.send() finally: connection.close()
def test_mixed(self): body = "Testing mixed text and html attachments" html, attached_images = render_to_string('image.html', {'imgsrc': 'dummy.png'}, using='post_office') subject = "[django-SHOP unit tests] attached image" msg = EmailMultiAlternatives(subject, body, to=['*****@*****.**']) msg.attach_alternative(html, 'text/html') for attachment in attached_images: msg.attach(attachment) msg.mixed_subtype = 'related' # this message can be send by email parts = msg.message().walk() part = next(parts) self.assertIsInstance(part, SafeMIMEMultipart) part = next(parts) self.assertIsInstance(part, SafeMIMEMultipart) part = next(parts) self.assertIsInstance(part, SafeMIMEText) self.assertEqual(part.get_content_type(), 'text/plain') self.assertHTMLEqual(part.get_payload(), body) part = next(parts) self.assertIsInstance(part, SafeMIMEText) self.assertEqual(part.get_content_type(), 'text/html') self.assertHTMLEqual(part.get_payload(), html) part = next(parts) self.assertIsInstance(part, MIMEImage) self.assertEqual(part.get_content_type(), 'image/png')
def checklist_export(username, user_email, checklist_id): current_checklist = ChecklistInstance.objects.filter(checklist_id=checklist_id) header = current_checklist.first() filename = "temp_excel.xlsx" EmailHandler._createExcel(filename, header, current_checklist) output = BytesIO() with open(filename, 'rb') as fh: output = BytesIO(fh.read()) remove(filename) # cleanup subject = f"Exported {header.checklist_type} checklist for {header.tenant}" message = "Exported checklist is attached" context = { 'username': username, 'logo_name': "logo", 'checklist_type': header.checklist_type, 'tenant_name': header.tenant } msg_html = render_to_string("email_templates/export_checklist.html", context) email = EmailMultiAlternatives( subject=subject, body=message, from_email=settings.EMAIL_HOST_USER, to=[user_email] ) email.attach_alternative(msg_html, "text/html") email.mixed_subtype = "related" email.attach(f'{header.checklist_type}checklist_{header.date}_{header.tenant}.xlsx', output.getvalue(), 'application/ms-excel') with open(finders.find("assets/img/Singhealth-logo.png"), mode='rb') as f: image = MIMEImage(f.read()) image.add_header('Content-ID', "<logo>") email.attach(image) email.send()
def send_save_the_date_email(context, recipients, test_only=False): context['email_mode'] = True context['rsvp_address'] = settings.DEFAULT_WEDDING_REPLY_EMAIL context['site_url'] = settings.WEDDING_WEBSITE_URL context['couple'] = settings.BRIDE_AND_GROOM template_html = render_to_string(SAVE_THE_DATE_TEMPLATE, context=context) template_text = "Save the date for {}'s wedding! July 2, 2016. Niagata-on-the-Lake, Ontario, Canada".format( settings.BRIDE_AND_GROOM) subject = 'Save the Date!' # https://www.vlent.nl/weblog/2014/01/15/sending-emails-with-embedded-images-in-django/ msg = EmailMultiAlternatives( subject, template_text, settings.DEFAULT_WEDDING_FROM_EMAIL, recipients, reply_to=[settings.DEFAULT_WEDDING_REPLY_EMAIL]) msg.attach_alternative(template_html, "text/html") msg.mixed_subtype = 'related' for filename in (context['header_filename'], context['main_image']): attachment_path = os.path.join(os.path.dirname(__file__), 'static', 'save-the-date', 'images', filename) with open(attachment_path, "rb") as image_file: msg_img = MIMEImage(image_file.read()) msg_img.add_header('Content-ID', '<{}>'.format(filename)) msg.attach(msg_img) print('sending {} to {}'.format(context['name'], ', '.join(recipients))) if not test_only: msg.send()
def send_invitation_email(party, test_only=False, recipients=None): if recipients is None: recipients = party.guest_emails if not recipients: print '===== WARNING: no valid email addresses found for {} ====='.format(party) return print party.guest_emails context = get_invitation_context(party) context['email_mode'] = True template_html = render_to_string(INVITATION_TEMPLATE, context=context) template_text = "You're invited to Alysa and Brandon's wedding. To view this invitation, visit {} in any browser.".format( reverse('invitation', args=[context['invitation_id']]) ) #subject = "You're invited! RSVP Reminder!" subject = "You're invited! Please RSVP by Feb. 25!" # https://www.vlent.nl/weblog/2014/01/15/sending-emails-with-embedded-images-in-django/ msg = EmailMultiAlternatives(subject, template_text, 'Alysa and Brandon <*****@*****.**>', recipients) msg.attach_alternative(template_html, "text/html") msg.mixed_subtype = 'related' for filename in (context['header_filename'], context['main_image']): attachment_path = os.path.join(os.path.dirname(__file__), 'static', 'invitation', 'images', filename) with open(attachment_path, "rb") as image_file: msg_img = MIMEImage(image_file.read()) msg_img.add_header('Content-ID', '<{}>'.format(filename)) msg.attach(msg_img) print 'sending invitation to {} ({})'.format(party.name, ', '.join(recipients)) if not test_only: msg.send()
def send_dataset_suggestion_mail_task(obj_id): model = apps.get_model('suggestions', 'DatasetSubmission') obj = model.objects.filter(pk=obj_id).first() result = None if obj: conn = get_connection(settings.EMAIL_BACKEND) emails = [ config.TESTER_EMAIL ] if settings.DEBUG and config.TESTER_EMAIL else [config.CONTACT_MAIL] context = {'obj': obj, 'host': settings.BASE_URL} tmpl = 'mails/dataset-submission.html' if is_enabled( 'S39_mail_layout.be') else 'mails/dataset-suggestion.html' with override('pl'): msg_plain = render_to_string('mails/dataset-suggestion.txt', context) msg_html = render_to_string(tmpl, context) mail = EmailMultiAlternatives(_('Resource demand reported'), msg_plain, from_email=config.NO_REPLY_EMAIL, to=emails, connection=conn) mail.mixed_subtype = 'related' mail.attach_alternative(msg_html, 'text/html') result = mail.send() return { 'sent': bool(result), 'obj_id': obj.id if obj else None, }
def notify_tenant_lease_expiry(name, lease_end_date, email, time_left, connection): subject = "Upcoming Tenant Lease Expiry" message = f"""This email is to notify you on your upcoming lease expiry in {time_left} on {lease_end_date}. """ context = { 'expiry_date': lease_end_date, 'owner_name': name, 'time_left': time_left, 'logo_name': "logo" } msg_html = render_to_string("email_templates/notify_lease_expiry.html", context) email = EmailMultiAlternatives( subject=subject, body=message, from_email=settings.EMAIL_HOST_USER, to=[email], connection=connection ) email.attach_alternative(msg_html, "text/html") email.mixed_subtype = "related" with open(finders.find("assets/img/Singhealth-logo.png"), mode='rb') as f: image = MIMEImage(f.read()) image.add_header('Content-ID', "<logo>") email.attach(image) email.send()
def send_save_the_date_email(context, recipients, test_only=True): context['email_mode'] = True template_html = render_to_string(SAVE_THE_DATE_TEMPLATE, context=context) template_text = "Save the date for Steve and Allie's wedding! August 18, 18. River Falls, WI" subject = 'Save the Date for the Jarvises!' # https://www.vlent.nl/weblog/2014/01/15/sending-emails-with-embedded-images-in-django/ msg = EmailMultiAlternatives( subject, template_text, 'Steve and Allie <*****@*****.**>', recipients, reply_to=['*****@*****.**']) msg.attach_alternative(template_html, "text/html") msg.mixed_subtype = 'related' for filename in (context['header_filename'], context['main_image']): attachment_path = os.path.join(os.path.dirname(__file__), 'static', 'save-the-date', 'images', filename) with open(attachment_path, "rb") as image_file: msg_img = MIMEImage(image_file.read()) # https://github.com/sklarsa/django-sendgrid-v5/issues/21 msg_img.add_header('Content-ID', '{}'.format(filename)) msg.attach(msg_img) print 'sending {} to {}'.format(context['name'], ', '.join(recipients)) if not test_only: msg.send()
def send_mail(self): subject = "[{}] {}".format(self.target_list.name, self.newsletter.subject) html_content, attachments = self.newsletter.render(self.target_name, True, self.subscriptions_url) h = html2text.HTML2Text() h.ignore_images = True text_content = h.handle(html_content) if self.target_list.from_email != '': if self.target_list.from_name != '': from_email = "{} <{}>".format(self.target_list.from_name, self.target_list.from_email) else: from_email = self.target_list.from_email else: from_email = getattr(settings, 'HEMRES_FROM_ADDRESS', '*****@*****.**') if self.target_name != '': to_email = "{} <{}>".format(self.target_name, self.target_email) else: to_email = self.target_email msg = EmailMultiAlternatives(subject=subject, body=text_content, from_email=from_email, to=[to_email]) msg.attach_alternative(html_content, "text/html") msg.mixed_subtype = 'related' for a in attachments: msg.attach(a) if not getattr(settings, 'SKIP_EMAIL', False): msg.send() self.delete()
def dict_to_email(messagedict): messagedict = copy.deepcopy(messagedict) extra_attrs = {} if settings.CELERY_EMAIL_MESSAGE_EXTRA_ATTRIBUTES: for attr in settings.CELERY_EMAIL_MESSAGE_EXTRA_ATTRIBUTES: if attr in messagedict: extra_attrs[attr] = messagedict.pop(attr) if isinstance(messagedict, dict) and "content_subtype" in messagedict: content_subtype = messagedict["content_subtype"] del messagedict["content_subtype"] else: content_subtype = None if isinstance(messagedict, dict) and "mixed_subtype" in messagedict: mixed_subtype = messagedict["mixed_subtype"] del messagedict["mixed_subtype"] else: mixed_subtype = None if hasattr(messagedict, 'from_email'): ret = messagedict elif 'alternatives' in messagedict: ret = EmailMultiAlternatives(**messagedict) else: ret = EmailMessage(**messagedict) for attr, val in extra_attrs.items(): setattr(ret, attr, val) if content_subtype: ret.content_subtype = content_subtype messagedict["content_subtype"] = content_subtype # bring back content subtype for 'retry' if mixed_subtype: ret.mixed_subtype = mixed_subtype messagedict["mixed_subtype"] = mixed_subtype # bring back mixed subtype for 'retry' return ret
def send_save_the_date_email(context, recipients, test_only=False): context['email_mode'] = True template_html = render_to_string(SAVE_THE_DATE_TEMPLATE, context=context) template_text = "Save the date for John and Mara's wedding! September 30, 2017. Ermioni, Peloponnese, Greece" subject = 'Save the Date!' # https://www.vlent.nl/weblog/2014/01/15/sending-emails-with-embedded-images-in-django/ msg = EmailMultiAlternatives( subject, template_text, 'John and Mara <*****@*****.**>', recipients, reply_to=['*****@*****.**']) msg.attach_alternative(template_html, "text/html") msg.mixed_subtype = 'related' for filename in (context['header_filename'], context['main_image']): attachment_path = os.path.join(os.path.dirname(__file__), 'static', 'save-the-date', 'images', filename) with open(attachment_path, "rb") as image_file: msg_img = MIMEImage(image_file.read()) msg_img.add_header('Content-ID', '<{}>'.format(filename)) msg.attach(msg_img) print('sending {} to {}'.format(context['name'], ', '.join(recipients))) if not test_only: msg.send()
def send_mail(subject, html_content, text_content, recipients, expert_request=None, attach_tor=False, attach_letter=False): # control of execution if email_is_off(): return # control of environment if env_is_local(): # local env email only to secondments mail list recipients = SECONDMENTS_MAIL_LIST # test indicator to render PDF as test sample test = test_is_on() if test: # subject with TEST subject = "This is a TEST email! " + subject msg = EmailMultiAlternatives(subject, text_content, EMAIL_HOST_USER, recipients, bcc=SECONDMENTS_MAIL_LIST) msg.attach_alternative(html_content, "text/html") msg.mixed_subtype = 'related' # attachments stuff if attach_letter or attach_tor: context = {'expert_request': expert_request, 'pagesize': 'A4', 'BASE_DIR': os.path.join(BASE_DIR, 'crppdmt/static/'), 'test_env': test,} try: tor_pdf = render_to_pdf('crppdmt/pdf/tor.html', context) letter_pdf = render_to_pdf('crppdmt/pdf/letter_of_request.html', context) msg.attach('ToR.pdf',tor_pdf,'application/pdf') msg.attach('LetterOfRequest.pdf',letter_pdf,'application/pdf') except: print("Error attaching ToR and Letter to Email. Request: " + expert_request.name) print("Error: " + str(sys.exc_info())) msg.send()
def form_valid(self, form): user = UserProfile.objects.get(user=request.user) product = Product.objects.get(id=request.GET.get('product_id')) try: margin = user.margin except: margin = 30.0 price_increased = (product.price * margin) / 100.00 price = product.price + price_increased to_email = [form.cleaned_data['Customer_email']] subject = '%s - %s' % (product.model, product.manufacturer) text_content = render_to_string('saas_app/email/product_info_email.txt') html_content = render_to_string('saas_app/email/product_info_email.html', {'text_content':text_content, 'price':price, 'product':product}) msg = EmailMultiAlternatives(subject, text_content, [user.email], to_email) msg.attach_alternative(html_content, 'text/html') msg.mixed_subtype = 'related' img_content_id = 'product' img_data = open(product.image_url(), 'rb') msg_img = MIMEImage(img_data.read()) img_data.close() msg_img.add_header('Content-ID', '<{}>'.format(product.picture)) msg.attach(msg_img) msg.send()
def _send(recipients, text_content=None, html_content=None, sent_from=None, subject=None, extra_data=None, attachments=None): extra_data = extra_data or {} mail = EmailMultiAlternatives( subject=subject, body=text_content, from_email=sent_from, to=recipients, bcc=extra_data.get('bcc', None), headers=extra_data.get('headers', None), cc=extra_data.get('cc', None), reply_to=extra_data.get('reply_to', None), ) if html_content: mail.attach_alternative(html_content, 'text/html') for attachment in (attachments or []): # All mimebase attachments must have a Content-ID or Content-Disposition header # or they will show up as unnamed attachments" if isinstance(attachment, MIMEBase): if attachment.get('Content-ID', False): # if you are sending attachment with content id, # subtype must be 'related'. mail.mixed_subtype = 'related' mail.attach(attachment) else: mail.attach(*attachment) mail.send()
def email_client(self, subject, text): # Send the client an email html_content = render_to_string( "../templates/baseTemplates/emailToUser.html", { 'salutation': self.salutation, 'last_name': self.last_name, 'text_body': text }) msg = EmailMultiAlternatives( subject, 'Dear ' + self.salutation + ' ' + self.last_name + '/n' + text, '*****@*****.**', [self.email], ) msg.attach_alternative(html_content, "text/html") msg.attach_file('static/Images/asranetLogo.jpg') msg.mixed_subtype = 'related' f = 'asranetLogo.jpg' fp = open(os.path.join(os.path.dirname(__file__), f), 'rb') msg_img = MIMEImage(fp.read()) fp.close() msg_img.add_header('Content-ID', '<{}>'.format(f)) msg.attach(msg_img) msg.send()
def send_email_signal_handler(sender, **kwargs): emailto = kwargs['emailto'] title = kwargs['title'] content = kwargs['content'] images = kwargs['images'] msg = EmailMultiAlternatives(title, content, from_email=settings.DEFAULT_FROM_EMAIL, to=emailto) msg.content_subtype = "html" msg.mixed_subtype = 'related' if images is not None: for key, value in images.items(): full_path = os.path.join(EMAIL_FILES, key) if os.path.isfile(full_path): img_data = open(full_path, 'rb').read() img = MIMEImage(img_data, value) img.add_header('Content-Id', key) img.add_header("Content-Disposition", "inline", filename=key) msg.attach(img) from servermanager.models import EmailSendLog log = EmailSendLog() log.title = title log.content = content log.emailto = ','.join(emailto) try: result = msg.send() log.send_result = result > 0 except Exception as e: logger.error(e) log.send_result = False log.save()
def send_data_suggestion(suggestion_id, data_suggestion): conn = get_connection(settings.EMAIL_BACKEND) emails = [ config.CONTACT_MAIL, ] notes = data_suggestion["notes"] data_suggestion['host'] = settings.BASE_URL msg_plain = render_to_string('mails/data-suggestion.txt', data_suggestion) msg_html = render_to_string('mails/data-suggestion.html', data_suggestion) if settings.DEBUG and config.TESTER_EMAIL: emails = [config.TESTER_EMAIL] mail = EmailMultiAlternatives(_('Resource demand reported'), msg_plain, from_email=config.NO_REPLY_EMAIL, to=emails, connection=conn) mail.mixed_subtype = 'related' mail.attach_alternative(msg_html, 'text/html') mail.send() model = apps.get_model('suggestions', 'Suggestion') model.objects.filter(pk=suggestion_id).update(send_date=now()) return {'suggestion': f'{notes}'}
def enviar_correo(asunto, template, recipients, data, attachment_file=None): image_path = os.path.join(settings.BASE_DIR, 'assets/images/afini_logo.png') image_name = 'afini_logo.png' context = {'image_name': image_name, 'data': data} html_content = render_to_string(template, context) reply_to = ['*****@*****.**'] message = EmailMultiAlternatives(asunto, html_content, os.getenv('MAIL_USER'), to=recipients, reply_to=reply_to) if attachment_file is not None: message.attach_file(os.path.join(settings.BASE_DIR, attachment_file)) message.attach_alternatives = (html_content, "text/html") message.content_subtype = "html" message.mixed_subtype = 'related' with open(image_path, mode='rb') as f: image = MIMEImage(f.read()) message.attach(image) image.add_header('Content-ID', f"<{image_name}>") message.send()
def send_order_fulfilled_email(sender, instance, *args, **kwargs): if instance.status_tracker.has_changed( 'status') and instance.status == Cart.Status.FULFILLED: order = instance.ordershipping cart_details = order.cart.cartdetail_set.all() #Info needed to send user email email = instance.user.email subject = f"ORDER INVOICE" message = f"Your order has been shipped and an invoice will be provided on delivery. Please log into your account to view details." html_message = loader.render_to_string('email/invoice_email.html', { 'order': order, 'user': instance.user, 'cart_details': cart_details }) msg = EmailMultiAlternatives(subject, message, 'settings.EMAIL_HOST_USER', [email]) msg.attach_alternative(html_message, "text/html") msg.mixed_subtype = 'related' f = 'static/images/road-star-logo.png' fp = open(os.path.join(os.path.dirname(__file__), f), 'rb') msg_img = MIMEImage(fp.read()) fp.close() msg_img.add_header('Content-ID', '<{}>'.format(f)) msg.attach(msg_img) print(msg_img.get_filename()) msg.send()
def notify_audit_performed(owner_email, audit_link, owner_name, checklist_id): checklist_objects = ChecklistInstance.objects.filter(checklist_id=checklist_id) scoreTable = ScoreTable.objects.filter(checklist_id=checklist_id)[0] base = checklist_objects[0] auditor_name = base.auditor score_percentage = "{:0.2f}".format((scoreTable.score / scoreTable.total)*100) closest_date = EmailHandler._getClosestDate(checklist_objects) subject = "New Audit Performed" message = f"This email is to notify you that {auditor_name} has performed a {base.checklist_type} audit." context = { 'view_audit_link': audit_link, 'auditor_name': auditor_name, 'owner_name': owner_name, 'checklist_type': base.checklist_type, 'is_noncompliance': date(date.today().year+2, 12, 30) != closest_date, 'score_percentage': score_percentage, 'closest_date': closest_date, 'logo_name': "logo" } msg_html = render_to_string("email_templates/notify_audit_performed.html", context) email = EmailMultiAlternatives( subject=subject, body=message, from_email=settings.EMAIL_HOST_USER, to=[owner_email] ) email.attach_alternative(msg_html, "text/html") email.mixed_subtype = "related" with open(finders.find("assets/img/Singhealth-logo.png"), mode='rb') as f: image = MIMEImage(f.read()) image.add_header('Content-ID', "<logo>") email.attach(image) email.send()
def post(self, request, *args, **kwargs): self.object = self.get_object() body = json.loads(request.body) email_recipient = body['email_recipient'] if email_recipient: try: subject = self.object.headline from_mail = request.user.email job_url = request.build_absolute_uri(self.object.get_absolute_url()) html_message = render_to_string( 'jobs/job_email.html', context={ 'job': self.object, 'user': request.user, 'domain': request.META['HTTP_HOST'] } ) text_content = 'Read "{}" at {}.'.format(self.object.headline, job_url) msg = EmailMultiAlternatives( subject, text_content, from_mail, [email_recipient] ) msg.attach_alternative(html_message, "text/html") msg.mixed_subtype = 'related' msg.send() except SMTPException as e: logging.error('SMTPException: %s' % e) else: return JsonResponse({'status': 'error'}) return JsonResponse({'status': 'ok'})
def post(self, request): if request.user.is_superuser: form = self.form_class(request.POST) if form.is_valid(): email = form.cleaned_data.get("email") username = form.cleaned_data.get("first_name") + '_' + form.cleaned_data.get("last_name") existing_email = User.objects.filter(email=email) existing_username = User.objects.filter(username=username) if not existing_username: if not existing_email: first_name = form.cleaned_data.get("first_name") last_name = form.cleaned_data.get("last_name") username = first_name + '_' + last_name sender = settings.EMAIL_HOST_USER password = User.objects.make_random_password() self.subject = "ViaSofie Account Registratie" html_content = "<center><div style='background-color:#0d3532; border:14px solid black; " \ "style='text-align:center; " \ "color:whitesmoke;padding:40px;'><h1 style='text-align:center;" \ "color:darkseagreen;'>" \ "Welkom bij Via Sofie!" \ "succesvol aangemaakt!</h1> \n" \ "<p>Aan de hand van de hieronder vermelde </p>" \ "<p>gebruikersnaam en paswoord kan u terecht in uw </p>" \ "<p>persoonlijk dossier. Op die manier kan u volgen </p>" \ "<p>welke acties er werden ondernomen met betrekking</p>" \ "<p>tot de verkoop van uw onroerend goed.</p>" \ "<p style='text-align:center'>E-mail: " + email + "</p>\n" \ "<p style='text-align:center'>Paswoord: " + password + '</p>' \ "<p></p>" \ "<h2 style='text-align:center'>VIA SOFIE</h2>" \ "</div></center>" msg = EmailMultiAlternatives(self.subject, '', sender, [email]) msg.attach_alternative(html_content, "text/html") msg.mixed_subtype = 'related' msg.send() user = User.objects.create_user(username=username, email=email, password=password, first_name=first_name, last_name=last_name) context = LoadFooter.get_context(LoadFooter) context['form'] = form context['success'] = 'Account is succesvol aangemaakt! '' \ ''De gebruikersnaam & wachtwoord zijn naar ' + \ email + ' verzonden.' return render(request, self.template_name, context) else: context = LoadFooter.get_context(LoadFooter) context['form'] = form context['error'] = 'Dit Email bestaat al!' return render(request, self.template_name, context) else: context = LoadFooter.get_context(LoadFooter) context['form'] = form context['error'] = 'De voornaam en achternaam komen overeen met een bestaande gebruiker.' return render(request, self.template_name, context) else: context = LoadFooter.get_context(LoadFooter) context['form'] = form context['error'] = 'Formulier fout ingevuld.' return render(request, self.template_name, context) return render(request, self.template_name, context)
def send_email(to, subject, email_template, cc=None, images=None, context=None): connection = get_connection() html_content = render_to_string(email_template, context) text_content = strip_tags(html_content) email = EmailMultiAlternatives(subject, text_content, settings.EMAIL_FROM, to, cc, connection) email.attach_alternative(html_content, "text/html") if images: email.mixed_subtype = 'related' for i in images: #email.headers() image_name = i.split("/")[-1] fp = open(settings.BASE_DIR + i, 'rb') msg_img = MIMEImage(fp.read()) msg_img.add_header('Content-Id', '<' + image_name + '>') email.attach(msg_img) fp.close() email.send()
def send_new_tenant_email(email, login_link, gen_password, owner_name, username): subject = "Account Created with Singhealth RMS" message = f"""Your account has been created with username: {username} and password: {gen_password}. You can log in at {login_link}. Remember to change your password to a preferred one after logging in. """ context = { 'login_link': login_link, 'gen_password': gen_password, 'owner_name': owner_name, 'username': username, 'logo_name': "logo" } msg_html = render_to_string("email_templates/new_tenant_notice.html", context) email = EmailMultiAlternatives( subject=subject, body=message, from_email=settings.EMAIL_HOST_USER, to=[email] ) email.attach_alternative(msg_html, "text/html") email.mixed_subtype = "related" with open(finders.find("assets/img/Singhealth-logo.png"), mode='rb') as f: image = MIMEImage(f.read()) image.add_header('Content-ID', "<logo>") email.attach(image) email.send()
def send_mail(subject, html_content, text_content, recipients, expert_request=None, attach_tor=False, attach_letter=False): # control of execution if email_is_off(): return # control of environment if env_is_local(): pass # test indicator to render PDF as test sample test = test_is_on() if test: # subject with TEST subject = "This is a TEST email! " + subject msg = EmailMultiAlternatives(subject, text_content, EMAIL_HOST_USER, recipients) msg.attach_alternative(html_content, "text/html") msg.mixed_subtype = 'related' # attachments stuff, if any msg.send()
def send_invoice(page_type, user): if page_type.send_email: subject = page_type.email_subject try: attachment = open(page_type.attachment.url[1:], 'r') except: attachment = None email_to = [user.email] #Ruben had hardcoded the two lines below this one. The lines from the send_custom_email function were used for this function after realizing that the hardcoded lines broke sending emails #plaintext = get_template("/opt/myenv/careerfair"+page_type.invoice_template_text.url) #htmly = get_template("/opt/myenv/careerfair"+page_type.invoice_template_html.url) plaintext = get_template('pages/invoice.txt') htmly = get_template('pages/invoice.html') try: sponsorship = SponsorshipPackage.objects.get( title=user.companyprofile.sponsor) except: sponsorship = None d = Context({ 'sponsorship': sponsorship, 'paypal_info': PayPalInfo.objects.all()[0], 'company': user.companyprofile }) text_content = plaintext.render(d) html_content = htmly.render(d) email = EmailMultiAlternatives(subject, text_content, 'Career Fair Staff', email_to) email.attach_alternative(html_content, "text/html") email.mixed_subtype = 'related' email.send()
def send_email(subject, message, html_message=None, sender=sender, recipent=recipient_list, image_path=None, image_name=None): email = EmailMultiAlternatives(subject=subject, body=message, from_email=sender, to=recipient_list) if all([html_message, image_path, image_name]): email.attach_alternative(html_message, "text/html") email.content_subtype = 'html' email.mixed_subtype = 'related' image_name = 'ctrader_logo_traders_first.png' with open(image_path, 'r') as f: image = MIMEImage(f.read()) image.add_header( 'Content-ID', '<{name}>'.format(name='ctrader_logo_traders_first.png')) image.add_header('Content-Disposition', 'inline', filename='ctrader_logo_traders_first.png') email.attach(image) image.add_header('Content-ID', f"<{image_name}>") email.send()
def email_invoice(req, order_id): order = OrderShipping.objects.get(id=order_id) cart_details = order.cart.cartdetail_set.all() # Send email to user email = req.user.email subject = f"Roadstar Tire Wholesale Order # {order.id} was shipped" message = f"Your order has been shipped and an invoice will be provided on delivery. Please log into your account to view details." html_message = loader.render_to_string( 'email/invoice_email.html', { 'order': order, 'user': req.user, 'cart_details': cart_details } ) msg = EmailMultiAlternatives( subject, message, 'settings.EMAIL_HOST_USER', [email] ) msg.attach_alternative(html_message, "text/html") msg.mixed_subtype = 'related' f = 'static/images/road-star-logo.png' fp = open(os.path.join(os.path.dirname(__file__), f), 'rb') msg_img = MIMEImage(fp.read()) fp.close() msg_img.add_header('Content-ID', '<{}>'.format(f)) msg.attach(msg_img) msg.send() return redirect('account')
def send_invitation_email(party, test_only=False, recipients=None): if recipients is None: recipients = party.guest_emails if not recipients: print('===== WARNING: no valid email addresses found for {} ====='.format(party)) return context = get_invitation_context(party) context['email_mode'] = True template_html = render_to_string(INVITATION_TEMPLATE, context=context) template_text = "You're invited to Cory and Rowena's wedding. To view this invitation, visit {} in any browser.".format( reverse('invitation', args=[context['invitation_id']]) ) subject = "You're invited" # https://www.vlent.nl/weblog/2014/01/15/sending-emails-with-embedded-images-in-django/ msg = EmailMultiAlternatives(subject, template_text, 'Cory and Rowena <*****@*****.**>', recipients, cc=['Rowena Luk <*****@*****.**>'], reply_to=['*****@*****.**']) msg.attach_alternative(template_html, "text/html") msg.mixed_subtype = 'related' for filename in (context['main_image'], ): attachment_path = os.path.join(os.path.dirname(__file__), 'static', 'invitation', 'images', filename) with open(attachment_path, "rb") as image_file: msg_img = MIMEImage(image_file.read()) msg_img.add_header('Content-ID', '<{}>'.format(filename)) msg.attach(msg_img) print('sending invitation to {} ({})'.format(party.name, ', '.join(recipients))) if not test_only: msg.send()
def send_invoice(page_type, user): if page_type.send_email: subject= page_type.email_subject try: attachment = open(page_type.attachment.url[1:],'r') except: attachment=None email_to= [user.email] plaintext = get_template('pages/custom_email.txt') htmly = get_template('pages/custom_email.html') try: sponsorship = SponsorshipPackage.objects.get(title=user.companyprofile.sponsor) except: sponsorship = None d = Context({'sponsorship':sponsorship, 'paypal_info': PayPalInfo.objects.all()[0], 'company':user.companyprofile}) text_content = plaintext.render(d) html_content = htmly.render(d) email = EmailMultiAlternatives(subject, text_content, 'Career Fair Staff', email_to) email.attach_alternative(html_content, "text/html") email.mixed_subtype = 'related' f = "/opt/myenv/careerfair/static/media/uploads/static images/header.png" fp = open(f, 'rb') msg_img = MIMEImage(fp.read()) fp.close() msg_img.add_header('Content-ID', '<header.png>'.format(f)) msg_img.add_header("Content-Disposition", "inline", filename="header.png") email.attach(msg_img) email.send()
def change_email(request): subject = 'Express Finance: смена почты' to_email = request.session.get('email') site = get_current_site(request) token = account_activation_token.make_token(request.user) token_db = Token.objects.filter(token=token).first() if not token_db: token_db = Token() token_db.token = token token_db.save() uid = str(urlsafe_base64_encode(force_bytes( request.user.pk))).split("'")[1] data = {'site': site, 'uid': uid, 'token': token} template = get_template('email/change.html') message = template.render(data) msg = EmailMultiAlternatives(subject, message, ADMIN_EMAIL, [to_email]) msg.attach_alternative(message, "text/html") msg.mixed_subtype = 'related' try: msg.send() except: print('Errooooooooooooooooooooooooooooooooooooooooor') return render(request, 'email/sended.html', {})
def post(self, request): form = self.form_class(request.POST) if form.is_valid(): subject = 'Request for business account from {}'.format( request.user) from_mail = request.user.email email_recipient = '*****@*****.**' text_content = 'Request for business account from {}.'.format( request.user) html_message = render_to_string( 'accounts/business_request_email.html', { 'user': request.user, 'business_name': form.cleaned_data['business_name'], 'location': form.cleaned_data['location'], 'address': form.cleaned_data['address'], 'license_id': form.cleaned_data['license_id'], }) msg = EmailMultiAlternatives(subject, text_content, from_mail, [ email_recipient, ]) msg.attach_alternative(html_message, "text/html") msg.mixed_subtype = 'related' msg.send() return super().form_valid(form)
def send_save_the_date_email_old(context, recipients, test_only=False): context['email_mode'] = True context['rsvp_address'] = settings.DEFAULT_WEDDING_REPLY_EMAIL template_html = render_to_string(SAVE_THE_DATE_TEMPLATE, context=context) template_text = "Save the date for Cliff and Melissa's wedding! September 29th, 2019. Masker's Barn, Berkeley Heights, NJ" subject = 'Save the Date!' connection = get_connection() connection.open() # https://www.vlent.nl/weblog/2014/01/15/sending-emails-with-embedded-images-in-django/ msg = EmailMultiAlternatives( subject, template_text, settings.DEFAULT_WEDDING_FROM_EMAIL, recipients, reply_to=[settings.DEFAULT_WEDDING_REPLY_EMAIL], connection=connection) msg.attach_alternative(template_html, "text/html") msg.mixed_subtype = 'related' for filename in (context['header_filename'], context['main_image']): attachment_path = os.path.join(os.path.dirname(__file__), 'static', 'save-the-date', 'images', filename) with open(attachment_path, "rb") as image_file: msg_img = MIMEImage(image_file.read()) msg_img.add_header('Content-ID', '<{}>'.format(filename)) msg.attach(msg_img) print('sending {} to {}'.format(context['name'], ', '.join(recipients))) if not test_only: msg.send(fail_silently=False) connection.close()
def send_mail(self): """ sends a schedueled email to all participants """ subject = self.title sender = self.owner.email to_mail = self.email_list context = {'query_list': [v for k, v in self.return_dict.iteritems()]} html_content = render_to_string( os.path.join('email/email_report.html'), context ) text_content = render_to_string( os.path.join('email/email_report.txt'), context ) msg = EmailMultiAlternatives(subject, text_content, sender, to_mail) msg.attach_alternative(html_content, "text/html") msg.mixed_subtype = 'related' # print subject, text_content, sender, to_mail for k, f in self.return_dict.iteritems(): f = f['img'] if f is not None: fp = open(os.path.join(os.path.dirname(__file__), f), 'rb') msg_img = MIMEImage(fp.read()) fp.close() msg_img.add_header('Content-ID', '<{}>'.format(f)) msg.attach(msg_img) msg.send() return msg
def validate(self, attrs): try: user = User.objects.get(email=attrs['email']) except User.DoesNotExist: raise User.DoesNotExist('User does not exist') else: if user: new_password = faker.password() user.set_password(new_password) user.save() # sending password mail to user msg = EmailMultiAlternatives( 'Reset password of Calgary Locks and Safe', render_to_string( 'email/reset_password.html', { 'password': new_password, 'first_name': user.first_name, 'last_name': user.last_name }), EMAIL_HOST_USER, [user.email]) msg.content_subtype = 'html' # Main content is text/html msg.mixed_subtype = 'related' # This is critical, otherwise images will be displayed as attachments with open(settings.STATIC_DIR + LOGO_PATH, 'rb') as f: file = f.read() image = MIMEImage(file) image.add_header('Content-ID', '<logo.png>') msg.attach(image) msg.send() else: raise ValueError('Usre is not a valid user') return attrs
def dict_to_email(messagedict): if isinstance(messagedict, dict) and "content_subtype" in messagedict: content_subtype = messagedict["content_subtype"] del messagedict["content_subtype"] else: content_subtype = None if isinstance(messagedict, dict) and "mixed_subtype" in messagedict: mixed_subtype = messagedict["mixed_subtype"] del messagedict["mixed_subtype"] else: mixed_subtype = None if hasattr(messagedict, 'from_email'): ret = messagedict elif 'alternatives' in messagedict: ret = EmailMultiAlternatives(**messagedict) else: ret = EmailMessage(**messagedict) if content_subtype: ret.content_subtype = content_subtype messagedict[ "content_subtype"] = content_subtype # bring back content subtype for 'retry' if mixed_subtype: ret.mixed_subtype = mixed_subtype messagedict[ "mixed_subtype"] = mixed_subtype # bring back mixed subtype for 'retry' return ret
def send_email(results_data): today = date.today().strftime("%m/%d/%y") subject = f'{today} ThoughtExchange Report | Summary & Response' # sender = '*****@*****.**' sender_username = results_data['username'] sender_password = results_data['password'] recipient = results_data['recipient'] msg_html = render_to_string('email.html', {'results_data': results_data}) msg_plain = strip_tags(msg_html) connection = get_connection( username=sender_username, password=sender_password, fail_silently=False, ) email = EmailMultiAlternatives( subject=subject, body=msg_plain, from_email=sender_username, to=recipient if isinstance(recipient, list) else [recipient], connection=connection) image_path = 'static/i/logo.png' if all([msg_html, image_path]): email.attach_alternative(msg_html, "text/html") email.mixed_subtype = 'related' with open(image_path, mode='rb') as f: image = MIMEImage(f.read()) f.close() image.add_header('Content-ID', "<logo>") email.attach(image) email.send()
def notify_expiring_membership(self): from ain7.adhesions.models import SubscriptionKey today = timezone.now().date() is_today = False if self.current_subscription() is not None and self.current_subscription_end_date() == today: is_today = True is_future = False if self.current_subscription() is not None and self.current_subscription_end_date() > today: is_future = True is_past = False if self.current_subscription() is None: is_past = True subject = u'Votre adhésion à l\'AIn7 arrive à échéance' if is_today: subject += u' aujourd\'hui!' if is_future: subject += u' le '+self.current_subscription_end_date().strftime("%d %B %Y") if is_past: subject = u'Votre adhésion à l\'AIn7 est arrivée à échéance le '+self.previous_subscription().end_date.strftime("%d %B %Y") html_content = render_to_string( 'emails/notification_subscription_ending.html', { 'person': self.person, 'is_today': is_today, 'is_future': is_future, 'is_past': is_past, 'settings': settings, }) text_content = render_to_string( 'emails/notification_subscription_ending.txt', { 'person': self.person, 'is_today': is_today, 'is_future': is_future, 'is_past': is_past, 'settings': settings, }) msg = EmailMultiAlternatives( subject, text_content, settings.DEFAULT_FROM_EMAIL, [self.person.mail_favorite()], ) msg.mixed_subtype = 'related' for img in ['logo_ain7.png', 'facebook.png', 'linkedin.png', 'twitter.png', 'googleplus.png']: fp = open(os.path.join(os.path.dirname(os.path.dirname(__file__)), 'templates/emails/img', img), 'rb') msg_img = MIMEImage(fp.read()) fp.close() msg_img.add_header('Content-ID', '<{}>'.format(img)) msg.attach(msg_img) msg.attach_alternative(html_content, "text/html") msg.send() sub_key = SubscriptionKey(person=self.person, expire_at=timezone.now()+datetime.timedelta(days=30)) sub_key.save()
def send_explosion_email(to, subject, content_name, variables, email_notifications_requested): if to and email_notifications_requested == True: from_email = '*****@*****.**' html_content = render_to_string('explosion/emails/' + content_name + '.html', variables) text_content = render_to_string('explosion/emails/' + content_name + '.txt', variables) msg = EmailMultiAlternatives(subject, text_content, from_email, [to]) msg.attach_alternative(html_content, "text/html") msg.mixed_subtype = 'related' msg.send() return
def send_html_mail(subject, body_txt, body_html, recipient): message = EmailMultiAlternatives(subject, body_txt, settings.DEFAULT_FROM_EMAIL, [recipient]) message.attach_alternative(body_html, 'text/html') message.mixed_subtype = 'related' logo_file = open(settings.STATIC_ROOT.child('images').child('logo.png')) logo_mime = MIMEImage(logo_file.read()) logo_file.close() logo_mime.add_header('Content-ID', '<*****@*****.**>') logo_mime.add_header('Content-Disposition', 'attachment') message.attach(logo_mime) message.send()
def send_html_mail(subject, recipient, message, template='', recipient_name='', sender_name='', sender=None, CHARSET=CHARSET): """ If you want to use Django template system: use `message` and define `template`. If you want to use images in html message, no problem, it will attach automatically found files in html template. (image paths are relative to PROJECT_PATH) """ html = render(message, template) # Image processing, replace the current image urls with attached images. soup = BeautifulSoup(html) images = [] added_images = [] for index, tag in enumerate(soup.findAll(image_finder)): if tag.name == u'img': name = 'src' elif tag.name == u'table': name = 'background' # If the image was already added, skip it. if tag[name] in added_images: continue added_images.append(tag[name]) images.append((tag[name], 'img%d' % index)) tag[name] = 'cid:img%d' % index html = str(soup) msg = EmailMultiAlternatives( subject=subject, body=html, to=[named(recipient, recipient_name)], from_email=named(sender, sender_name), ) for filename, file_id in images: image_file = open(settings.PROJECT_PATH + filename, 'rb') msg_image = MIMEImage(image_file.read()) image_file.close() msg_image.add_header('Content-ID', '<%s>' % file_id) msg.attach(msg_image) msg.content_subtype = 'html' msg.mixed_subtype = 'related' msg.send()
def avatar_updated_handler(sender, instance, **kwargs): try: original_mentor = Mentor.objects.get(id=instance.id) except ObjectDoesNotExist: return if not instance.avatar: return if original_mentor.avatar != instance.avatar: instance.avatar_approved = False context = { 'first_name': instance.user.first_name, 'last_name': instance.user.last_name, 'image': 'avatar', 'approve_url': instance.get_approve_avatar_url(), 'reject_url': instance.get_reject_avatar_url(), } subject = u"{} {} | Mentor Avatar Changed".format( instance.user.first_name, instance.user.last_name ) html_content = render_to_string("mentor-avatar-changed.html", context) text_content = render_to_string("mentor-avatar-changed.txt", context) msg = EmailMultiAlternatives( subject=subject, body=text_content, from_email=settings.DEFAULT_FROM_EMAIL, to=[settings.CONTACT_EMAIL] ) msg.attach_alternative(html_content, "text/html") msg.mixed_subtype = 'related' img = MIMEImage(instance.avatar.read()) img.add_header('Content-Id', 'avatar') img.add_header("Content-Disposition", "inline", filename="avatar") msg.attach(img) msg.send()
def submitRegistration(request): if request.method == 'POST': username = request.POST['username'].strip() email = request.POST['email'].strip() password = request.POST['password'].strip() if User.objects.filter(username=username): data = {'error':'This username is already taken.'} elif email: if User.objects.filter(email=email): data = {'error':'This email is already used with another account.'} #user = User.objects.create_user(username, email, password) #Create EmailAccountCreation accountCreator = EmailAccountCreation.objects.create( username = username, email = email, ) args = { "accountID":accountCreator.id, } #Send email confirmation subject = "My Travel Shop Account Verification" sender = "My Travel Shop Inc. <*****@*****.**>" html_content = render_to_string('google_login/email_verification.html', args) text_content = render_to_string('google_login/email_verification.txt', args) msg = EmailMultiAlternatives(subject, text_content, sender, [email]) msg.attach_alternative(html_content, "text/html") msg.mixed_subtype = 'related' msg.send() data = {'error':'Please check your email. A verification email has been sent to your email address.'} else: data = {'error':'Did not post correctly'} return HttpResponse(json.dumps(data))
def send_html_email(subject, html_content, sender, to_addresses, images): text_content = html2text.html2text(html_content) msg = EmailMultiAlternatives(subject, text_content, sender, to_addresses) msg.attach_alternative(html_content, "text/html") msg.mixed_subtype = 'related' for f in images: fp = open(staticfiles_storage.path(f), 'rb') msg_img = MIMEImage(fp.read()) fp.close() name = os.path.basename(f) msg_img.add_header('Content-ID', '<{}>'.format(name)) msg_img.add_header('Content-Disposition', 'attachment', filename=name) msg.attach(msg_img) msg.send()
def enviar_correo(destinatario,contenido): template = get_template('inscripcion.html') context = Context(contenido) content = template.render(context) email = EmailMultiAlternatives('Registro', content, settings.EMAIL_HOST_USER, [destinatario]) email.attach_alternative(content, "text/html") email.mixed_subtype = 'related' for f in ['Email-Lab-Virt-Confirmacion_r1_c1.png', 'Email-Lab-Virt-Confirmacion_r3_c1.png','spacer.gif']: fp = open(os.path.join(settings.BASE_DIR, 'plataforma/media/'+f), 'rb') msg_img = MIMEImage(fp.read()) fp.close() msg_img.add_header('Content-ID', '<{}>'.format(f)) email.attach(msg_img) email.send()
def dict_to_email(messagedict): messagedict = copy.deepcopy(messagedict) extra_attrs = {} if settings.CELERY_EMAIL_MESSAGE_EXTRA_ATTRIBUTES: for attr in settings.CELERY_EMAIL_MESSAGE_EXTRA_ATTRIBUTES: if attr in messagedict: extra_attrs[attr] = messagedict.pop(attr) attachments = messagedict.pop('attachments') messagedict['attachments'] = [] for attachment in attachments: filename, contents, mimetype = attachment contents = base64.b64decode(contents.encode('ascii')) # For a mimetype starting with text/, content is expected to be a string. if mimetype and mimetype.startswith('text/'): contents = contents.decode() messagedict['attachments'].append((filename, contents, mimetype)) if isinstance(messagedict, dict) and "content_subtype" in messagedict: content_subtype = messagedict["content_subtype"] del messagedict["content_subtype"] else: content_subtype = None if isinstance(messagedict, dict) and "mixed_subtype" in messagedict: mixed_subtype = messagedict["mixed_subtype"] del messagedict["mixed_subtype"] else: mixed_subtype = None if hasattr(messagedict, 'from_email'): ret = messagedict elif 'alternatives' in messagedict: ret = EmailMultiAlternatives(**messagedict) else: ret = EmailMessage(**messagedict) for attr, val in extra_attrs.items(): setattr(ret, attr, val) if content_subtype: ret.content_subtype = content_subtype messagedict["content_subtype"] = content_subtype # bring back content subtype for 'retry' if mixed_subtype: ret.mixed_subtype = mixed_subtype messagedict["mixed_subtype"] = mixed_subtype # bring back mixed subtype for 'retry' return ret
def forge_corporate_email(subject, html_body, text_body, to, extra_images={}, **kwargs): # related = MIMEMultipart("related") html_content = render_to_string('email/email.html', {'body': html_body, 'subject': subject, 'corp_color': '#642e99', 'BASE_URL': settings.BASE_URL}) text_content = strip_tags(render_to_string('email/email_text.html', {'body': text_body, 'subject': subject, 'corp_color': '#642e99', 'BASE_URL': settings.BASE_URL})) if 'from_email' in kwargs: from_email = kwargs.pop('from_email') else: from_email = settings.DEFAULT_FROM_EMAIL email = EmailMultiAlternatives( subject=subject, body=text_content, from_email=from_email, to=to, **kwargs ) email.attach_alternative(html_content, 'text/html') img = open(os.path.join(os.path.dirname(__file__), '..', '..', 'static', 'images', 'email-logo.png'), 'rb').read() logo_image = MIMEImage(img) logo_image.add_header('Content-ID', '<email-logo.png>') logo_image.add_header('Content-Disposition', 'inline', filename='email-logo.png') logo_image.add_header('Content-Type', 'image/png', name='email-logo.png') email.attach(logo_image) for img_id, img_path in extra_images.items(): try: img = open(img_path, 'r').read() logo_image = MIMEImage(img) logo_image.add_header('Content-ID', '<{}>'.format(img_id)) logo_image.add_header('Content-Disposition', 'inline', filename=img_id) subtype = 'jpeg' if img_path.lower().endswith('png'): subtype = 'png' logo_image.add_header('Content-Type', 'image/{}'.format(subtype), name=img_id) email.attach(logo_image) except: pass email.mixed_subtype = "related" return email
def contact(request): context = { 'nbar': 'contact', 'form': ContactForm(), } if request.POST: form = ContactForm(request.POST, request.FILES) try: if form.is_valid(): email_address = form.cleaned_data['email'] message = form.cleaned_data['message'] email = EmailMessage('', email_address + '\n\n' + message, to=[EMAIL_CONTACT]) email.send() bev_content_text = 'Welkom bij Via Sofie! \n\n Wij hebben uw mail goed ontvangen. \n U mag spoedig een antwoord van ons verwachten.\n\n Vriendelijke groet, \n\n Sofie' msg = EmailMultiAlternatives("Contactverzoek", bev_content_text, EMAIL_CONTACT, [email_address]) msg.attach_alternative(render_to_string('ViaSofie/email/contact_confirmation.html'), "text/html") msg.mixed_subtype = 'related' for f in ['ContactBevestiging.jpg']: print os.path.join(os.path.join(os.path.join(os.path.dirname(__file__), 'static'), 'ViaSofie'), f) fp = open(os.path.join(os.path.join(os.path.join(os.path.dirname(__file__), 'static'), 'ViaSofie'), f), 'rb') msg_img = MIMEImage(fp.read()) fp.close() msg_img.add_header('Content-ID', '<{}>'.format(f)) msg.attach(msg_img) msg.send() context['succes'] = True else: raise Exception() except: context['error'] = True context['form'] = form return render(request, 'ViaSofie/contact.html', context)
def email_client(self, subject, text): # Send the client an email html_content = render_to_string("../templates/baseTemplates/emailToUser.html", {'salutation': self.salutation, 'last_name': self.last_name, 'text_body': text}) msg = EmailMultiAlternatives(subject, 'Dear ' + self.salutation + ' ' + self.last_name + '/n' + text, '*****@*****.**', [self.email], ) msg.attach_alternative(html_content, "text/html") msg.attach_file('adWind/asranetLogo.jpg') msg.mixed_subtype = 'related' f = 'adWind/asranetLogo.jpg' fp = open(os.path.join(os.path.dirname(__file__), f), 'rb') msg_img = MIMEImage(fp.read()) fp.close() msg_img.add_header('Content-ID', '<{}>'.format(f)) msg.attach(msg_img) msg.send(fail_silently=True)
def send_email(self, user, from_email, reply_to_email, to_person, subject, html_content = None, text_content = None, attachments = []): """ @param attachments a list of MIMEBase objects """ total_emails_sent = 0 total_emails_failed = 0 to_email = "{} {} <{}>".format(to_person.first_name, to_person.last_name, to_person.email) headers = {} if reply_to_email: headers['Reply-To'] = reply_to_email email_message = EmailMultiAlternatives(subject, text_content, from_email, [to_email], headers=headers) if html_content: email_message.attach_alternative(html_content, "text/html") email_message.mixed_subtype = 'related' # attachements for attachment in attachments: email_message.attach(attachment) # Record the email email_record = EmailRecord( subject=subject, message = email_message.message(), from_email = from_email, to_email = to_person.email, recipient = to_person, sender = user, ) email_record.save() # Send try: email_message.send(fail_silently=False) email_record.status = 'sent' email_record.save() total_emails_sent += 1 except SMTPException: email_record.statis = 'failed' email_record.save() total_emails_failed += 1 return total_emails_sent
def main(): connection = mail.get_connection() # Manually open the connection connection.open() DeliveryQueue.objects.filter(enviado=True).delete() queue = DeliveryQueue.objects.exclude(enviado=True) for q in queue: link = 'http://admin.quickmail.cl/qm?m=%s&e=%s' % (str(q.delivery.plantilla.pk),str(q.email.pk)) nombre = '%s %s' % (q.email.nombre,q.email.apellido) nombre = '' msg = EmailMultiAlternatives('%s %s' % (nombre,q.subject), q.plainContent, q.from_email, [q.email.email]) header_html = '<html><body><h2>Estimado(a): %s</h2><p>Si no puede ver el contenido de este mensaje haga click en el <a href="%s">link</a></p><br/>'% (nombre,link) disclaimer = u'Este correo electrónico fue enviado a %s. Si no quiere recibir estos emails, haga clic en el <a href="%s">link</a> \ Este e-mail ha sido enviado por la plataforma <a href="http://www.quickmail.cl">QuickMail</a>' % (q.email.email,link) footer_html = '</body></footer>' msg.attach_alternative('%s%s%s%s' % (header_html,q.htmlContent,disclaimer,footer_html), "text/html") msg.mixed_subtype = 'related' for f in q.attachedFiles: try: if q.htmlContent.__contains__(os.path.basename(f)): fp = open(f, 'rb') msg_img = MIMEImage(fp.read()) fp.close() msg_img.add_header('Content-ID', '<{}>'.format(os.path.basename(f))) msg.attach(msg_img) except: pass try: msg.send() q.enviado = True q.save() print 'Sent %s %s %s \n' % (str(q.pk),q.from_email,q.email.email) time.sleep(1) except: pass try: connection.close() except: pass
def send_invoice(page_type, user): if page_type.send_email: subject= page_type.email_subject try: attachment = open(page_type.attachment.url[1:],'r') except: attachment=None email_to = [user.email] plaintext = get_template("/opt/myenv/careerfair"+page_type.invoice_template_text.url) htmly = get_template("/opt/myenv/careerfair"+page_type.invoice_template_html.url) try: sponsorship = SponsorshipPackage.objects.get(title=user.companyprofile.sponsor) except: sponsorship = None d = Context({'sponsorship':sponsorship, 'paypal_info': PayPalInfo.objects.all()[0], 'company':user.companyprofile}) text_content = plaintext.render(d) html_content = htmly.render(d) email = EmailMultiAlternatives(subject, text_content, 'Career Fair Staff', email_to) email.attach_alternative(html_content, "text/html") email.mixed_subtype = 'related' email.send()
def send_mail(course, enroll, qr_code_path): from django.core.mail import EmailMultiAlternatives from email.MIMEImage import MIMEImage import uuid attch_name = str(uuid.uuid1()) + ".png" subject, from_email, to = settings.ENROLL_EMAIL_SUBJECT.format( name=course.courseName), settings.ENROLL_EMAIL_FROM, enroll.email text_content = settings.ENROLL_EMAIL_CONTENT.format(name=course.courseName) html_content = course.event_type.type_template.format( name=course.courseName, seat=enroll.seat, image=attch_name, courseTime=course.courseStartTime.strftime('%d/%m/%Y %I:%M:%S %p'), email=enroll.email.split("@")[0]) msg = EmailMultiAlternatives(subject, text_content, from_email, [to]) msg.attach_alternative(html_content, "text/html") msg.mixed_subtype = 'related' fp = open(qr_code_path, 'rb') msg_img = MIMEImage(fp.read()) fp.close() msg_img.add_header('Content-ID', '<{}>'.format(attch_name)) msg.attach(msg_img) msg.send()
def post(self, request): email = request.POST.get('cd-email') print(email) context = LoadFooter.get_context(LoadFooter) if email not in [None, '']: if not Nieuwsbrief.objects.filter(email=email).exists(): activate_code = str(uuid.uuid4()) nieuwsbrieflid = Nieuwsbrief.objects.create(email=email, activate_code=activate_code) nieuwsbrieflid.save() subject = "inschrijving nieuwsbrief" html_content = '<center><div style="background-color:#0d3532; border:14px solid black; ' \ 'color:whitesmoke;padding:40px;"><h1 style="text-align:center;color:darkseagreen;">' \ 'Welkom bij VIA SOFIE!</h1>' + \ '<p style="text-align:center">Klik de link om je actief te stellen voor de nieuwsbrief' + \ 'van VIA SOFIE</p> <center><a href="' + \ str(request.build_absolute_uri(reverse('index'))) + \ 'nieuwsbrief/activate/' + activate_code + '">Activeer nieuwsbrief</a></center>' + \ '<p></p>' \ '<h2 style="text-align:center" >Sofie</h2>' + \ '<img src="static/master/img/base/logo.png" width="60px" height="60px"/>' \ '</div></center>' msg = EmailMultiAlternatives(subject, 'test', settings.EMAIL_HOST_USER, [email]) msg.attach_alternative(html_content, "text/html") msg.mixed_subtype = 'related' """test = msg.attach_file('http://localhost:8000' + settings.STATIC_URL + 'master/img/base/logo.png') fp = open(test, 'rb') msg_img = MIMEImage(fp.read()) fp.close() msg_img.add_header('Content-ID', '<{}>'.format(f)) msg.attach(msg_img)""" msg.send() context['success'] = 'mail is gestuurd naar ' + str( email) + ' klik op de link om je account te activeren voor nieuwsbrieven.' return JsonResponse({'message-success': 'mail is gestuurd naar ' + str( email) + ' klik op de link om je account te activeren voor nieuwsbrieven.'}) else: return JsonResponse({'message-error': 'Dit email is al reeds geregistreerd!'}) else: context['form'] = form return JsonResponse({'message-error': 'Geen geldig email!'})
def deliver_digest(self, users, notice_history): rendered_history = self.render_history(notice_history) digest_body = render_to_string(["notifications/custom/digest.html", "notifications/digest.html"], {'notice_history': rendered_history}) digest_text = strip_tags(digest_body) digest_subject = "Digest from " + Site.objects.get_current().domain emails = [] for user in users: emails.append(user.email) msg = EmailMultiAlternatives(digest_subject, digest_text, settings.DEFAULT_FROM_EMAIL, bcc=emails) msg.attach_alternative(digest_body, "text/html") msg.mixed_subtype = "related" asset_list = [] for notice in notice_history: asset_list = asset_list + notice.notice_type.get_assets() asset_set = set(asset_list) msg = self.add_assets(asset_set, msg) msg.send()
def home(request): form = ProductInfoEmailForm(request.POST or None) context = {"form": form} template = "saas_app/product-search-result.html" if form.is_valid(): to_email = [form.cleaned_data['Customer_email']] subject = "Product that you had expressed interest in." body = " Here are the details for the item we've discussed. There's a limited quantity available, so let me know when you are ready to place your order." html_content = render_to_string('saas_app/email/product_info_email.html', context) msg = EmailMultiAlternatives(subject, body, '*****@*****.**', to_email) msg.attach_alternative(html_content, "text/html") msg.mixed_subtype = 'related' img_content_id = 'gun' img_data = open(product.image_url(), 'rb') msg_img = MIMEImage(img_data.read()) img_data.close() msg_img.add_header('Content-ID', '<{}>'.format(product.picture)) msg.attach(msg_img) msg.send() return render(request, template, context)
def send_email(self): profiles = UserProfile.objects.filter(notify_by_email=True) recipients = [p.user.email for p in profiles] subject = '[{0}]: {1}'.format(self.site.name, self.entry.title) body = self.render_template('blog/notification_email.html') message = EmailMultiAlternatives(subject, body, settings.DEFAULT_FROM_EMAIL, [settings.DEFAULT_FROM_EMAIL], recipients) message.mixed_subtype = "related" try: body_html = self.render_template('blog/notification_email_html.html') soup = BeautifulSoup(body_html) images = {} for index, tag in enumerate(soup.findAll(self._image_finder)): if tag['src'] not in images.keys(): images[tag['src']] = "image_{0}".format(index) tag['src'] = 'cid:{0}'.format(images[tag['src']]) body_html = str(soup) for filename, file_id in images.items(): image_file = self._file_finder(filename) if image_file: msg_image = MIMEImage(image_file.read()) image_file.close() msg_image.add_header('Content-ID', '<{0}>'.format(file_id)) message.attach(msg_image) message.attach_alternative(body_html, "text/html") except Exception, e: raise e # if we can't load the html template or related images, # don't send the HTML version pass
def mail(subject, context, template, from_email, to_email, connection=None, reply_to=None): html_template = render_to_string(template + '.html', context) txt_template = render_to_string(template + '.txt', context) plinper = pynliner.Pynliner() plinper.relative_url = 'file://localhost/' html_email = plinper.from_string(html_template).run() if reply_to: email = EmailMultiAlternatives(subject, txt_template, from_email, to_email, reply_to=reply_to) else: email = EmailMultiAlternatives(subject, txt_template, from_email, to_email) email.mixed_subtype = 'related' # Find all images in html img_regex = '<img(.*?)src=("|\')(.*?)("|\')(.*?)>' compiled_img_regex = re.compile(img_regex) images = compiled_img_regex.findall(html_email) # Replace src to cid for image in images: img_path = image[2] img_file = open(img_path , 'rb') img = MIMEImage(img_file.read()) img_file.close() img_cid = hashlib.md5(open(img_path, 'rb').read()).hexdigest() img.add_header('Content-ID', '<%s>' % img_cid) img.add_header('Content-Disposition', 'inline') email.attach(img) html_email = re.sub(img_path, 'cid:%s' % img_cid , html_email) email.attach_alternative(html_email, "text/html") if connection: connection.open() email.send()
def send_email(user, item, gender, manage_user): """Methode called to send email to new borrower :param user: the User class instance :param item: the Equipment class instance :param gender: the current equipment gender :param manage_user: the User who is logged in """ if settings.SEND_EMAIL: # and not request.user.is_authenticated: subject = "{prefix} Emprunt {item}".format(prefix=settings.EMAIL_SUBJECT_PREFIX, item=item) from_email = settings.DEFAULT_FROM_EMAIL to = [user.email] text_content = """ Salut {user}, tu as emprunté {article} {item} (déclaré par {manager}). Tu en es responsable pendant une semaine, jusqu'à son retour entre les mains du référent matériel jeudi prochain. """.format(user=user.first_name, article=gender, item=item, manager=manage_user.first_name) html_content = """ <p>Salut {user},</p> <p>Tu as emprunté {article} <strong>{item}</strong> (déclaré par {manager}).<br \> Tu en es responsable pendant une semaine, jusqu'à son retour entre les mains du référent matériel <strong>jeudi prochain</strong>.</p> <p>Bonne grimpe !</p> <p>- - -<br /> https://matos.vertigo-montpellier.fr</p> <img src="cid:logo.png"> """.format(user=user.first_name, article=gender, item=item, manager=manage_user.first_name) msg = EmailMultiAlternatives(subject, text_content, from_email, to) msg.attach_alternative(html_content, "text/html") msg.mixed_subtype = 'related' with open(os.path.join(settings.STATICFILES_DIRS[0], 'img/logo_mail.png'), 'rb') as img: msg_image = MIMEImage(img.read()) msg_image.add_header('Content-ID', '<logo.png>') msg.attach(msg_image) msg.send()