def forget_password(request): if request.method == 'POST': email = request.data['email'] try: user_id = SlpUser.objects.get(email=email) print(user_id.id) except: return Response("Email Not registered, Enter Registerd Email") try: ids = user_id.id subject = 'hello' text_content = 'http://127.0.0.1:8000/user/reset_password/user_id.id/' data = 'Please Click the link to Reset your Password' content = '<br><a href="http://127.0.0.1:8000/user/reset_password/' + str( ids) + '/"><button type="button"> CLICK </button></a>' html_content = data + content # msg = send_mail(subject,message, EMAIL_HOST_USER, [email], fail_silently = False) # send_mail(subject,message, EMAIL_HOST_USER, [email], fail_silently = False) msg = EmailMessage(subject, html_content, EMAIL_HOST_USER, [email]) msg.content_subtype = "html" # Main content is now text/html msg = EmailMultiAlternatives(subject, text_content, EMAIL_HOST_USER, [email]) msg.attach_alternative(html_content, "text/html") msg.send() except Exception as e: print(e) return Response("error") return Response("Email is sent")
def run(self): try: log.info(self.toString()) msg = EmailMessage(self.subject.strip(), self.body.strip(), self._from, self.to.split(','),self.bcc.split(','), None) if self.isAttachment: img_data = open(self.attachment,'rb').read() msg.attach('product.jpg',img_data,'image/jpg') if self.isHtml: text_content = strip_tags(self.body.strip()) msg = EmailMultiAlternatives(self.subject.strip(), text_content, self._from,self.to.split(','), self.bcc.split(',')) msg.bcc = self.bcc.split(',') msg.attach_alternative(self.body.strip(), "text/html") msg.send() if self.email_log_id: try: email_log = LEmail.objects.get(id = self.email_log_id) email_log.status = 'delivered' email_log.save() except: log.warn( 'Skipping saving email log to %s' % self.email_log_id) except Exception, e: if self.email_log_id: try: email_log = LEmail.objects.get(id = self.email_log_id) email_log.status = 'delivery_failed' email_log.save() except: log.warn( 'Skipping saving email log to %s' % self.email_log_id) log.exception('Error sending email %s' % self.toString())
def send(self, address, title, content, html_message=None, attachments=None): msg = EmailMessage(title, content, self.from_address, [address], connection=self.get_connection()) if html_message or attachments: msg = EmailMultiAlternatives(title, content, self.from_address, [address], connection=self.get_connection()) if html_message: msg.attach_alternative(html_message, "text/html") if attachments: for attachment in attachments: msg.attach_file(attachment) msg.send() msg.connection.close() self.add_usage()
def umail(request, template, subject, sender, to, context = {}, bcc = [], attachments=[]): """ It sends mail with template. It supports html and txt template. In the first case it searches a txt template with the same name in the same position. If it will be found it sends both. 'template', 'subject' and 'sender' are strings. 'to' and 'bcc' are lists of addresses. 'context' is a dictionary. 'attachments' is a list of paths. """ if request: c = RequestContext(request, context) else: c = Context(context) if template.endswith('.html'): t = loader.get_template(template) try: t_html = t txt_name = '%s.txt' % (template.rsplit('.', 1)[0]) t = loader.get_template(txt_name) except: print "Missing .txt template for: %s" % (template) email = EmailMessage(subject, t_html.render(c), sender, to, bcc) email.content_subtype = "html" else: email = EmailMultiAlternatives(subject, strip_tags(t.render(c)), sender, to, bcc) email.attach_alternative(t_html.render(c).encode('utf-8'), "text/html") else: t = loader.get_template(template) email = EmailMessage(subject, strip_tags(t.render(c)), sender, to, bcc) for filepath in attachments: mimetype = mimetypes.guess_type(filepath)[0] email.attach_file(filepath, mimetype) email.send()
def email_password_reset(request): email = request.POST.get('email', '') try: user = User.objects.get(email=email) if user and user.is_active: message = render_to_string( "activate_reset_password.html", { "email": email, "domain": get_current_site(request).domain, "uid": urlsafe_base64_encode(force_bytes(user.pk)), "token": account_token.make_token(user) }) mail = EmailMessage("Please use the Reset link ", message, to=[email], reply_to=['*****@*****.**'], headers={'Reply-To': '*****@*****.**'}) mail.attach_alternative(message, "text/html") mail.content_subtype = "html" mail.mixed_type = "related" mail.send() except (BadHeaderError, ValueError, Exception): messages.info(request, "link sent to email") return redirect("signin") else: messages.info(request, "sent you an email") return redirect("signin")
def send_email(*args, **kwargs): """ Send an html message Args: template_name: required context: required, a dict for render template subject: required from_email: optional, email address to: required, array of destination emails plain: optional, default is false Raise: TemplateDoesNotExist """ subject = kwargs.get('subject') from_email = kwargs.get('from_email', settings.DEFAULT_FROM_EMAIL) to = kwargs.get('to') body = kwargs.get('body', '') plain = kwargs.get('plain', False) if plain: message = EmailMessage(subject, body, from_email, to) else: context = Context(kwargs.get('context', {})) template = loader.get_template(kwargs.get('template_name')) html_content = template.render(context) message = EmailMultiAlternatives(subject, body, from_email, to) message.attach_alternative(html_content, 'text/html') message.send(fail_silently=True)
def booking_succeeded(booking: Booking): config = SiteConfig.objects.first() questions_text = [] for question in booking.booking_question_answers.all(): questions_text.append(f"{question.question.question}:\r\n{question.answer}") questions_text = "\r\n".join(questions_text) files_text = [] for file in booking.booking_files.all(): file_url = settings.EXTERNAL_URL_BASE + file.file.url files_text.append(f"- {file_url}") files_text = "\r\n".join(files_text) tz = pytz.timezone(booking.type.timezone) time = booking.time.astimezone(tz=tz).strftime("%I:%M%p %a %d %b %Y") body = f"Name: {booking.customer.first_name} {booking.customer.last_name}\r\n" \ f"Email: {booking.customer.email}\r\n" \ f"Phone: {booking.customer.phone}" \ f"\r\n\r\n---\r\n\r\n" \ f"{booking.type.name}\r\n" \ f"Time: {time}, {booking.type.timezone}\r\n" \ f"{questions_text}\r\n---\r\n\r\n" \ f"Files:\r\n" \ f"{files_text}" email_msg = EmailMessage( subject=f"{booking.customer.first_name} {booking.customer.last_name} has booked {booking.type.name}", body=body, to=[config.notification_email], reply_to=[f"{booking.customer.first_name} {booking.customer.last_name} <{booking.customer.email}>"] ) email_msg.send() context = { "booking_type": booking.type, "time": time, "first_name": booking.customer.first_name, "last_name": booking.customer.last_name, "email": booking.customer.email, "phone": booking.customer.phone, "questions": [{ "question": q.question, "answer": q.answer } for q in booking.booking_question_answers.all()] } email_msg = EmailMultiAlternatives( subject=f"Confirmation of your booking with Louise", body=render_to_string("bookings/booking_confirmation_txt.html", context), to=[booking.customer.email], headers={ "List-Unsubscribe": f"<mailto:{config.email}?subject=unsubscribe>", }, reply_to=[f"Louise Misell <{config.email}>"] ) email_msg.attach_alternative(render_to_string("bookings/booking_confirmation_amp.html", context), "text/x-amp-html") email_msg.attach_alternative(render_to_string("bookings/booking_confirmation.html", context), "text/html") email_msg.send() insert_booking_to_calendar(booking)
def get_email_message(self, template_name, context, from_email=None, to=None, cc=None, bcc=None, headers=None, template_prefix=None, template_suffix=None, template_dir=None, file_extension=None, attachments=[]): parts = self._render_email(template_name, context, template_prefix or template_dir, template_suffix or file_extension) plain_part = 'plain' in parts html_part = 'html' in parts if 'subject' in parts: subject = parts['subject'] else: subject_dict = getattr(settings, 'TEMPLATED_EMAIL_DJANGO_SUBJECTS', {}) subject_template = subject_dict.get(template_name, _('%s email subject' % template_name)) subject = subject_template % context if plain_part and not html_part: e = EmailMessage( subject, parts['plain'], from_email, to, cc=cc, bcc=bcc, headers=headers, attachments=attachments, ) if html_part and not plain_part: e = EmailMessage( subject, parts['html'], from_email, to, cc=cc, bcc=bcc, headers=headers, attachments=attachments, ) e.content_subtype = 'html' if plain_part and html_part: e = EmailMultiAlternatives( subject, parts['plain'], from_email, to, cc=cc, bcc=bcc, headers=headers, attachments=attachments, ) e.attach_alternative(parts['html'], 'text/html') return e
def _create_single_message( msg_body_sbj_to: List[str], track_str: str, from_email: str, cc_email_list: List[str], bcc_email_list: List[str], attachments: Optional[List[models.View]] = None, filter_formula: Optional[Dict] = None, ) -> Union[EmailMessage, EmailMultiAlternatives]: """Create either an EmailMessage or EmailMultiAlternatives object. :param msg_body_sbj_to: List with body, subject, to :param track_str: String to add to track :param from_email: From email :param cc_email_list: CC list :param bcc_email_list: BCC list :param attachments: List of views to attach to the message (optional) :param filter_formula: Filter attached ot the action (optional) :return: Either EmailMessage or EmailMultiAlternatives """ if settings.EMAIL_HTML_ONLY: # Message only has the HTML text msg = EmailMessage( msg_body_sbj_to[1], msg_body_sbj_to[0] + track_str, from_email, [msg_body_sbj_to[2]], bcc=bcc_email_list, cc=cc_email_list, ) msg.content_subtype = 'html' else: # Get the plain text content and bundle it together with the HTML # in a message to be added to the list. msg = EmailMultiAlternatives( subject=html2text.html2text(msg_body_sbj_to[0]), body=msg_body_sbj_to[1], from_email=from_email, to=[msg_body_sbj_to[2]], bcc=bcc_email_list, cc=cc_email_list, ) msg.attach_alternative(msg_body_sbj_to[0] + track_str, 'text/html') if attachments: for attachment in attachments: data_frame = pandas.get_subframe( attachment.workflow.get_data_frame_table_name(), filter_formula, [col.name for col in attachment.columns.all()]) mime_obj = MIMEText(data_frame.to_csv(), 'csv') mime_obj.add_header('Content-Disposition', 'attachment', filename=attachment.name + '.csv') msg.attach(mime_obj) return msg
def send_raw(subject, text, sender, to, headers, connection_label=None, html=None): connection = get_connection(connection_label) if html is None: msg = EmailMessage(subject, text, sender, to, headers=headers, connection=connection) else: msg = EmailMultiAlternatives(subject, text, sender, to, headers=headers, connection=connection) msg.attach_alternative(html, "text/html") msg.send(fail_silently=False)
def send(self, template_name, from_email, recipient_list, context, cc=[], bcc=[], fail_silently=False, headers={}, files=[]): parts = self._render_email(template_name, context) plain_part = parts.has_key('plain') html_part = parts.has_key('html') subject = parts.get('subject', getattr( settings,'TEMPLATED_EMAIL_DJANGO_SUBJECTS',{} ).get( template_name, _('%s email subject' % template_name) ) % context ) if plain_part and not html_part: e=EmailMessage( subject, parts['plain'], from_email, recipient_list, cc = cc, bcc = bcc, headers = headers, ) self.attach_files(e,files) e.send(fail_silently) if html_part and not plain_part: e=EmailMessage( subject, parts['html'], from_email, recipient_list, cc = cc, bcc = bcc, headers = headers, ) e.content_subtype = 'html' self.attach_files(e,files) e.send(fail_silently) if plain_part and html_part: e=EmailMultiAlternatives( subject, parts['plain'], from_email, recipient_list, cc = cc, bcc = bcc, headers = headers, ) e.attach_alternative(parts['html'],'text/html') self.attach_files(e,files) e.send(fail_silently) return e.extra_headers.get('Message-Id',None)
def get_email_message(self, template_name, context, from_email=None, to=None, cc=None, bcc=None, headers=None, template_prefix=None, template_suffix=None, template_dir=None, file_extension=None): parts = self._render_email(template_name, context, template_prefix or template_dir, template_suffix or file_extension) plain_part = 'plain' in parts html_part = 'html' in parts if 'subject' in parts: subject = parts['subject'] else: subject_dict = getattr(settings, 'TEMPLATED_EMAIL_DJANGO_SUBJECTS', {}) subject_template = subject_dict.get(template_name, _('%s email subject' % template_name)) subject = subject_template % context if plain_part and not html_part: e = EmailMessage( subject, parts['plain'], from_email, to, cc=cc, bcc=bcc, headers=headers, ) if html_part and not plain_part: e = EmailMessage( subject, parts['html'], from_email, to, cc=cc, bcc=bcc, headers=headers, ) e.content_subtype = 'html' if plain_part and html_part: e = EmailMultiAlternatives( subject, parts['plain'], from_email, to, cc=cc, bcc=bcc, headers=headers, ) e.attach_alternative(parts['html'], 'text/html') return e
def render_mail(self, template_prefix, email, context): """ Renders an e-mail to `email`. `template_prefix` identifies the e-mail that is to be sent, e.g. "account/email/email_confirmation" """ print("tyler0") subject = render_to_string('{0}_subject.txt'.format(template_prefix), context) # remove superfluous line breaks print("tyler0.5") subject = " ".join(subject.splitlines()).strip() print("tyler0.75") subject = self.format_email_subject(subject) print("tyler1") bodies = {} for ext in ['html', 'txt']: try: template_name = '{0}_message.{1}'.format(template_prefix, ext) bodies[ext] = render_to_string(template_name, context).strip() except TemplateDoesNotExist: print("all is lost branko") print(ext) if ext == 'txt' and not bodies: print("truely all is lost now") # We need at least one body raise if 'txt' in bodies: print("?") print("subject = ", subject) print("body = ", bodies['txt']) print("from email =", settings.DEFAULT_FROM_EMAIL) print("to email = ", email) msg = EmailMessage(subject=subject, body=bodies['txt'], from_email=settings.DEFAULT_FROM_EMAIL, to=[email]) print("XD") if 'html' in bodies: print("how did we get here") msg.attach_alternative(bodies['html'], 'text/html') else: print("uhh i guess we're here") msg = EmailMessage(subject, bodies['html'], settings.DEFAULT_FROM_EMAIL, email) msg.content_subtype = 'html' # Main content is now text/html return msg
def send_email(subject, message, from_email, recipient_list, content_type="text/plain"): """ send mail with mime-type, core django send_mail doesn't have this functionality """ if content_type == "text/plain": plain_body = message email = EmailMessage(subject=subject, body=message, from_email=from_email, to=recipient_list).send() else: email = EmailMultiAlternatives(subject=subject, from_email=from_email, to=recipient_list) plain_body = MAILER_DEFAULT_PLAIN_TEXT_ALTERNATIVE email.attach_alternative(content=plain_body, mimetype='text/plain') email.attach_alternative(content=message, mimetype=content_type) email.send()
def send(template_name, sender=None, to=None, cc=None, bcc=None, subject='mail', attachments=(), html_template_name=None, context=None, headers=None, reply_to=None): """ Render and send an email. `template_name` is a plaintext template. If `html_template_name` is passed then a multipart email will be sent using `template_name` for the text part and `html_template_name` for the HTML part. The context will include any `context` specified. If no `sender` is specified then the `DEFAULT_FROM_EMAIL` or `SERVER_EMAIL` setting will be used. Extra email headers can be passed in to `headers` as a dictionary. """ to, cc, bcc, reply_to = map(listify, [to, cc, bcc, reply_to]) if sender is None: sender = getattr(settings, 'DEFAULT_FROM_EMAIL', settings.SERVER_EMAIL) attachment_list = [[a.name, a.read(), a.content_type] for a in attachments] email_kwargs = { 'from_email': sender, 'to': to, 'cc': cc, 'bcc': bcc, 'subject': six.text_type(subject), 'attachments': attachment_list, 'reply_to': reply_to, 'headers': headers or {}, } text_content = render_to_string(template_name, context) email_kwargs['body'] = text_content if html_template_name is None: msg = EmailMessage(**email_kwargs) else: msg = EmailMultiAlternatives(**email_kwargs) html_content = render_to_string(html_template_name, context) msg.attach_alternative(html_content, 'text/html') msg.send()
def umail(request, template, subject, sender, to, context={}, bcc=[], attachments=[]): """ It sends mail with template. It supports html and txt template. In the first case it searches a txt template with the same name in the same position. If it will be found it sends both. 'template', 'subject' and 'sender' are strings. 'to' and 'bcc' are lists of addresses. 'context' is a dictionary. 'attachments' is a list of paths. """ if request: c = RequestContext(request, context) else: c = Context(context) if template.endswith('.html'): t = loader.get_template(template) try: t_html = t txt_name = '%s.txt' % (template.rsplit('.', 1)[0]) t = loader.get_template(txt_name) except: print "Missing .txt template for: %s" % (template) email = EmailMessage(subject, t_html.render(c), sender, to, bcc) email.content_subtype = "html" else: email = EmailMultiAlternatives(subject, strip_tags(t.render(c)), sender, to, bcc) email.attach_alternative( t_html.render(c).encode('utf-8'), "text/html") else: t = loader.get_template(template) email = EmailMessage(subject, strip_tags(t.render(c)), sender, to, bcc) for filepath in attachments: mimetype = mimetypes.guess_type(filepath)[0] email.attach_file(filepath, mimetype) email.send()
def send(template_name, sender=None, to=None, cc=None, bcc=None, subject='mail', attachments=(), html_template_name=None, context=None, headers=None, reply_to=None): """ Render and send an email. `template_name` is a plaintext template. If `html_template_name` is passed then a multipart email will be sent using `template_name` for the text part and `html_template_name` for the HTML part. The context will include any `context` specified. If no `sender` is specified then the `DEFAULT_FROM_EMAIL` or `SERVER_EMAIL` setting will be used. Extra email headers can be passed in to `headers` as a dictionary. """ to, cc, bcc, reply_to = map(listify, [to, cc, bcc, reply_to]) if sender is None: sender = getattr(settings, 'DEFAULT_FROM_EMAIL', settings.SERVER_EMAIL) attachment_list = [[a.name, a.read(), a.content_type] for a in attachments] email_kwargs = { 'from_email': sender, 'to': to, 'cc': cc, 'bcc': bcc, 'subject': six.text_type(subject), 'attachments': attachment_list, 'reply_to': reply_to, 'headers': headers or {}, } text_content = render_to_string(template_name, context) email_kwargs['body'] = text_content if html_template_name is None: msg = EmailMessage(**email_kwargs) else: msg = EmailMultiAlternatives(**email_kwargs) html_content = render_to_string(html_template_name, context) msg.attach_alternative(html_content, 'text/html') msg.send()
def send(self, address, title, content, html_message=None, html_only=False): if html_only: msg = EmailMessage(title, content, self.from_address, [address], connection=self.get_connection()) msg.content_subtype = "html" else: msg = EmailMultiAlternatives( title, content, self.from_address, [address], connection=self.get_connection() ) msg.attach_alternative( html_message, "text/html" ) msg.send() msg.connection.close() self.add_usage()
def send(self, address, title, content, html_message=None, attachments=None): msg = EmailMessage(title, content, self.from_address, [address], connection=self.get_connection()) if html_message or attachments: msg = EmailMultiAlternatives(title, content, self.from_address, [address], connection=self.get_connection() ) if html_message: msg.attach_alternative(html_message, "text/html") if attachments: for attachment in attachments: msg.attach_file(attachment) msg.send() msg.connection.close() self.add_usage()
def _create_single_message( msg_body_sbj_to: List[str], track_str: str, from_email: str, cc_email_list: List[str], bcc_email_list: List[str], ) -> Union[EmailMessage, EmailMultiAlternatives]: """Create either an EmailMessage or EmailMultiAlternatives object. :param msg_body_sbj_to: List with body, subject, to :param track_str: String to add to track :param from_email: From email :param cc_email_list: CC list :param bcc_email_list: BCC list :return: Either EmailMessage or EmailMultiAlternatives """ if settings.EMAIL_HTML_ONLY: # Message only has the HTML text msg = EmailMessage( msg_body_sbj_to[1], msg_body_sbj_to[0] + track_str, from_email, [msg_body_sbj_to[2]], bcc=bcc_email_list, cc=cc_email_list, ) msg.content_subtype = 'html' else: # Get the plain text content and bundle it together with the HTML # in a message to be added to the list. msg = EmailMultiAlternatives( msg_body_sbj_to[1], html2text.html2text(msg_body_sbj_to[0]), from_email, [msg_body_sbj_to[2]], bcc=bcc_email_list, cc=cc_email_list, ) msg.attach_alternative(msg_body_sbj_to[0] + track_str, 'text/html') return msg
def export_documents(export): from contacts.imex import get_exportable_documents as contacts_documents from invoicing.imex import get_exportable_documents as invoicing_documents with respect_language(export.language): archive_name = _('Vosae export.zip') zipped = ContentFile('', archive_name) f = zipfile.ZipFile(zipped, mode='w', compression=zipfile.ZIP_DEFLATED) for documents, path_func, doc_func in contacts_documents(export): for document in documents: f.writestr(path_func(document), doc_func(document)) for documents, path_func, doc_func in invoicing_documents(export): for document in documents: f.writestr(path_func(document), doc_func(document)) f.close() zipped.content_type = "application/zip" export.zipfile = VosaeFile( tenant=export.tenant, uploaded_file=zipped, issuer=export.issuer ) export.zipfile.save() export.update(set__zipfile=export.zipfile) context = { 'tenant': export.tenant, 'file': export.zipfile, 'site': {'name': settings.SITE_NAME, 'url': settings.SITE_URL} } # Email to issuer plaintext_context = Context(autoescape=False) # HTML escaping not appropriate in plaintext subject = subject = _("Your Vosae export is available") text_body = render_to_string('data_liberation/emails/export_finished.txt', context, plaintext_context) html_body = render_to_string("data_liberation/emails/export_finished.html", context) message = EmailMessage(subject=subject, from_email=settings.DEFAULT_FROM_EMAIL, to=[export.issuer.email], body=text_body) message.attach_alternative(html_body, "text/html") message.send()
def forget_password(request): print("in method forget") if request.method == 'POST': email = request.POST['resetEmail'] try: admin_email = SlpAdmin.objects.get(email=email) except: context = { 'message': "Email not Registerd!", 'url': '/slp_admin/login/', 'icon': 'error', } return render(request, "admin_login.html", context) try: ids = admin_email.id subject = 'hello' text_content = 'http://127.0.0.1:8000/slp_admin/reset_password/admin_email.id/' data = 'Please Click the link to Reset your Password' content = '<br><a href="http://127.0.0.1:8000/slp_admin/reset_password/' + str( ids) + '/"><button type="button"> CLICK </button></a>' html_content = data + content # msg = send_mail(subject,message, EMAIL_HOST_USER, [email], fail_silently = False) # send_mail(subject,message, EMAIL_HOST_USER, [email], fail_silently = False) msg = EmailMessage(subject, html_content, EMAIL_HOST_USER, [email]) msg.content_subtype = "html" # Main content is now text/html msg = EmailMultiAlternatives(subject, text_content, EMAIL_HOST_USER, [email]) msg.attach_alternative(html_content, "text/html") msg.send() print("email sent") except Exception as e: print(e) return Response("error") context = { 'message': "Email is Sent", 'url': '/slp_admin/login/', 'icon': 'success', } return render(request, "admin_login.html", context)
def send(self, template_name, from_email, recipient_list, context, cc=[], bcc=[], fail_silently=False, headers={}, template_dir=None, file_extension=None, auth_user=None, auth_password=None, connection=None, **kwargs): connection = connection or get_connection(username=auth_user, password=auth_password, fail_silently=fail_silently) parts = self._render_email(template_name, context, template_dir, file_extension) plain_part = parts.has_key('plain') html_part = parts.has_key('html') subject = parts.get('subject', getattr( settings,'TEMPLATED_EMAIL_DJANGO_SUBJECTS',{} ).get( template_name, _('%s email subject' % template_name) ) % context ) if plain_part and not html_part: e=EmailMessage( subject, parts['plain'], from_email, recipient_list, cc = cc, bcc = bcc, headers = headers, connection = connection, ) if html_part and not plain_part: e=EmailMessage( subject, parts['html'], from_email, recipient_list, cc = cc, bcc = bcc, headers = headers, connection = connection, ) e.content_subtype = 'html' if plain_part and html_part: e=EmailMultiAlternatives( subject, parts['plain'], from_email, recipient_list, cc = cc, bcc = bcc, headers = headers, connection = connection, ) e.attach_alternative(parts['html'],'text/html') try: e.send(fail_silently) except NameError: raise EmailRenderException("Couldn't render plain or html parts") return e.extra_headers.get('Message-Id',None)
def send_email(request, extra_context, subject_template, body_template, from_email, recipients, priority="medium", reply_to=None, headers={}): """ Sends an email based on templates for subject and body. :param request: The current request instance. :param extra_context: A dictionary of items that should be added to the templates' contexts. :param subject_template: A string representing the path to the template of of the email's subject. :param body_template: A string representing the path to the template of the email's body. :param from_email: String that represents the sender of the email. :param recipients: A list of tuples of recipients. The tuples are similar to the ADMINS setting. :param priority: Sets the priority of the email (only used by django-mailer to prioritise email sendings). :param reply_to: Optional email address to reply to. :param headers: Additional dictionary to add header attributes. """ if not reply_to: reply_to = from_email if django.get_version() >= '1.8': # The reply_to argument has been added in 1.8 reply_to = [reply_to] else: headers.update({'Reply-To': reply_to}) if request: context = RequestContext(request, extra_context) else: context = extra_context if request and request.get_host(): domain = request.get_host() protocol = 'https://' if request.is_secure() else 'http://' else: domain = getattr(settings, 'DOMAIN', Site.objects.get_current().domain) protocol = getattr(settings, 'PROTOCOL', 'http://') context.update({ 'domain': domain, 'protocol': protocol, }) subject = render_to_string(subject_template, context) subject = ''.join(subject.splitlines()) message_html = render_to_string(body_template, context) message_plaintext = html_to_plain_text(message_html) if settings.EMAIL_BACKEND == 'mailer.backend.DbBackend': mailer.send_html_mail( subject, message_plaintext, message_html, from_email, recipients, priority=priority, headers=headers) else: subject = force_text(subject) message = force_text(message_plaintext) if django.get_version() >= '1.8': # The reply_to argument has been added in 1.8 email = EmailMessage( subject=subject, body=message, from_email=from_email, to=recipients, headers=headers, reply_to=reply_to) email = EmailMultiAlternatives( email.subject, email.body, email.from_email, email.to, headers=email.extra_headers, reply_to=reply_to) else: email = EmailMessage( subject=subject, body=message, from_email=from_email, to=recipients, headers=headers) email = EmailMultiAlternatives( email.subject, email.body, email.from_email, email.to, headers=email.extra_headers) email.attach_alternative(message_html, "text/html") email.send()
def send(self, template_name, from_email, recipient_list, context, cc=[], bcc=[], fail_silently=False, headers={}, template_dir=None, file_extension=None, auth_user=None, auth_password=None, connection=None, **kwargs): connection = connection or get_connection(username=auth_user, password=auth_password, fail_silently=fail_silently) parts = self._render_email(template_name, context, template_dir, file_extension) plain_part = parts.has_key('plain') html_part = parts.has_key('html') subject = parts.get( 'subject', getattr(settings, 'TEMPLATED_EMAIL_DJANGO_SUBJECTS', {}).get( template_name, _('%s email subject' % template_name)) % context) if plain_part and not html_part: e = EmailMessage( subject, parts['plain'], from_email, recipient_list, cc=cc, bcc=bcc, headers=headers, connection=connection, ) if html_part and not plain_part: e = EmailMessage( subject, parts['html'], from_email, recipient_list, cc=cc, bcc=bcc, headers=headers, connection=connection, ) e.content_subtype = 'html' if plain_part and html_part: e = EmailMultiAlternatives( subject, parts['plain'], from_email, recipient_list, cc=cc, bcc=bcc, headers=headers, connection=connection, ) e.attach_alternative(parts['html'], 'text/html') try: e.send(fail_silently) except NameError: raise EmailRenderException("Couldn't render plain or html parts") return e.extra_headers.get('Message-Id', None)
def post(self, request, *args, **kwargs): serializer = ReplySerializer(data=request.DATA) def record_send_message(email_msg, related_lead, sending_mailbox): """ Records and sends a message with metadata for Mandrill. :param email_msg: :param related_lead: :param sending_mailbox: :return: """ out_msg = sending_mailbox.record_outgoing_message( email.message_from_string( email_msg.message().as_string() ) ) out_msg.lead = related_lead out_msg.save() email_msg = set_metadata(email_msg, out_msg) email_msg.send() return out_msg if serializer.is_valid(): from fetchmyguest.utils.html2plaintext import html2plaintext import HTMLParser h = HTMLParser.HTMLParser() html_content = h.unescape(serializer.data['message']) text_content = html2plaintext(html_content, encoding='utf-8') if int(kwargs['msg_pk']) != 0: message = get_object_or_404(Message, pk=int(kwargs['msg_pk'])) cc = [] if serializer.data['cc']: for address in serializer.data['cc'].split(','): cc.append( rfc822.parseaddr( address )[1] ) # Forwarded message if serializer.data['fwd']: to = [] for address in serializer.data['fwd'].split(','): to.append( rfc822.parseaddr( address )[1] ) subject = 'Fwd: ' + message.subject msg = EmailMessage(subject=subject, body=message.get_text_body(), to=to, cc=cc) if message.mailbox.from_email: msg.from_email = message.mailbox.from_email else: msg.from_email = settings.DEFAULT_FROM_EMAIL record_send_message(msg, message.lead, message.mailbox) # Reply message else: subject, to = 'Re: ' + ' '.join(message.subject.split()), message.lead.customer.email msg = EmailMultiAlternatives(subject=subject, body=text_content, to=[to], cc=cc) msg.attach_alternative(html_content, "text/html") new_msg = message.prepare_reply(msg) record_send_message(new_msg, message.lead, message.mailbox) else: lead = get_object_or_404(Lead, pk=int(kwargs['lead_pk'])) if serializer.data['subject']: subject = serializer.data['subject'] else: try: lp = lead.leadproperty_set.filter( Q(status=LeadProperty.REQUESTED) | Q(status=LeadProperty.NOTAVAILABLE) )[0] subject = 'Property Request for {0}'.format(lp.property.title) except: subject = 'Property Request' msg = EmailMultiAlternatives( subject=subject, body=text_content, to=[lead.customer.email], bcc=[lead.agency.email] ) msg.attach_alternative(html_content, "text/html") record_send_message(msg, lead, lead.agency.mailbox) return Response(serializer.data, status=201) else: return Response(serializer.errors, status=400)
class MessagePrep: from_ = None def prevent_failure(func): def inner_function(self, arg): arg = arg.strip() if arg: func(self, arg) return inner_function def __init__(self, row): self.msg = EmailMessage() self.prep_to(row[0]) self.prep_file(row[1]) self.prep_subject(row[2]) self.prep_message(row[3]) def prep_from(self): self.msg.from_email(self.from_) def prep_to(self, to): to = list(lambda x:x.strip(), to.split()) self.msg.to(to) @prevent_failure def prep_file(self, file_paths): for fil in map(lambda x: x.strip(), file_paths.split(",")): if os.path.exists(fil): with open(os.path.join(fil), "rb") as f: file_data = f.read(fil) file_name = pathlib.Path(fil).name self.msg.attach(file_name, file_data, get_mime(fil)) def prep_subject(self, subject): subject = subject.strip() if subject is None: raise ValueError(f"Invalid Subject < {subject} >") self.msg.subject(subject) @prevent_failure def prep_message(self, file_path): with codecs.open(file_path, "r") as f: self.msg.attach_alternative(''' <!DOCTYPE html> <html> <body> %s </body> </html>'''.format(f), subtype='html') @staticmethod def get_mime(path): mime = mimetypes.guess_type(path)[0] if mime: return mime elif path.endswith(".rar"): return "application/x-rar-compressed" else: raise TypeError("Filetype not supported invalid")
def send_email(request, extra_context, subject_template, body_template, from_email, recipients, priority="medium"): """ Sends an email based on templates for subject and body. :param request: The current request instance. :param extra_context: A dictionary of items that should be added to the templates' contexts. :param subject_template: A string representing the path to the template of of the email's subject. :param body_template: A string representing the path to the template of the email's body. :param from_email: String that represents the sender of the email. :param recipients: A list of tuples of recipients. The tuples are similar to the ADMINS setting. """ if request: context = RequestContext(request, extra_context) else: context = extra_context if request and request.get_host(): context.update({ 'domain': '{}://{}'.format('https' if request.is_secure() else 'http', request.get_host()) }) else: context.update({'domain': Site.objects.get_current().domain}) subject = render_to_string(subject_template, context) subject = ''.join(subject.splitlines()) message_html = render_to_string(body_template, context) message_plaintext = html_to_plain_text(message_html) if settings.EMAIL_BACKEND == 'mailer.backend.DbBackend': mailer.send_html_mail(subject, message_plaintext, message_html, from_email, recipients, priority=priority) else: subject = force_text(subject) message = force_text(message_plaintext) email = EmailMessage( subject=subject, body=message, from_email=from_email, to=recipients, bcc=None, attachments=None, headers=None, ) email = EmailMultiAlternatives(email.subject, email.body, email.from_email, email.to, headers=None) email.attach_alternative(message_html, "text/html") email.send()
def send_all(): """ Send all eligible messages in the queue. """ lock = FileLock("send_mail") logging.debug("acquiring lock...") try: lock.acquire(LOCK_WAIT_TIMEOUT) except AlreadyLocked: logging.debug("lock already in place. quitting.") return except LockTimeout: logging.debug("waiting for the lock timed out. quitting.") return logging.debug("acquired.") start_time = time.time() dont_send = 0 deferred = 0 sent = 0 connection = None try: for message in prioritize(): if DontSendEntry.objects.has_address(message.to_address): logging.info("skipping email to %s as on don't send list " % message.to_address) MessageLog.objects.log(message, 2) # @@@ avoid using literal result code message.delete() dont_send += 1 else: try: logging.info("sending message '%s' to %s" % (message.subject.encode("utf-8"), message.to_address.encode("utf-8"))) # Using EmailMessage instead of send_mail since that is basically all send_mail does. if message.message_body_html is None or len(message.message_body_html) == 0: logging.debug("message is text only") msg = EmailMessage(message.subject, message.message_body, message.from_address, [message.to_address]) else: logging.debug("message is text+html alternative") msg = EmailMultiAlternatives(message.subject, message.message_body, message.from_address, [message.to_address]) msg.attach_alternative(message.message_body_html, "text/html") if not DRY_RUN: if connection is None: # save the connection for possible reuse connection = msg.get_connection() logging.debug("got new conncetion") if not SKIP_SEND: msg.send() MessageLog.objects.log(message, 1) # @@@ avoid using literal result code message.delete() sent += 1 except (socket_error, smtplib.SMTPSenderRefused, smtplib.SMTPRecipientsRefused, smtplib.SMTPAuthenticationError), err: message.defer() connection = None # don't try to cache on error logging.info("message deferred due to failure: %s" % err) MessageLog.objects.log(message, 3, log_message=str(err)) # @@@ avoid using literal result code deferred += 1 if MAX_MESSAGES and MAX_MESSAGES == sent + deferred: logging.info("stopped sending after reaching max of %d", MAX_MESSAGES) break finally: logging.debug("releasing lock...") lock.release() logging.debug("released.") logging.info("") logging.info("%s sent; %s deferred; %s don't send" % (sent, deferred, dont_send)) logging.info("done in %.2f seconds" % (time.time() - start_time))
def send_email(request, extra_context, subject_template, body_template, from_email, recipients, priority="medium", reply_to=None, headers={}): """ Sends an email based on templates for subject and body. :param request: The current request instance. :param extra_context: A dictionary of items that should be added to the templates' contexts. :param subject_template: A string representing the path to the template of of the email's subject. :param body_template: A string representing the path to the template of the email's body. :param from_email: String that represents the sender of the email. :param recipients: A list of tuples of recipients. The tuples are similar to the ADMINS setting. :param priority: Sets the priority of the email (only used by django-mailer to prioritise email sendings). :param reply_to: Optional email address to reply to. :param headers: Additional dictionary to add header attributes. """ if not reply_to: reply_to = from_email if django.get_version() >= '1.8': # The reply_to argument has been added in 1.8 reply_to = [reply_to] else: headers.update({'Reply-To': reply_to}) if request: context = RequestContext(request, extra_context) else: context = extra_context if request and request.get_host(): domain = request.get_host() protocol = 'https://' if request.is_secure() else 'http://' else: domain = getattr(settings, 'DOMAIN', Site.objects.get_current().domain) protocol = getattr(settings, 'PROTOCOL', 'http://') context.update({ 'domain': domain, 'protocol': protocol, }) subject = render_to_string(subject_template, context) subject = ''.join(subject.splitlines()) message_html = render_to_string(body_template, context) message_plaintext = html_to_plain_text(message_html) if settings.EMAIL_BACKEND == 'mailer.backend.DbBackend': mailer.send_html_mail(subject, message_plaintext, message_html, from_email, recipients, priority=priority, headers=headers) else: subject = force_text(subject) message = force_text(message_plaintext) if django.get_version() >= '1.8': # The reply_to argument has been added in 1.8 email = EmailMessage(subject=subject, body=message, from_email=from_email, to=recipients, headers=headers, reply_to=reply_to) email = EmailMultiAlternatives(email.subject, email.body, email.from_email, email.to, headers=email.extra_headers, reply_to=reply_to) else: email = EmailMessage(subject=subject, body=message, from_email=from_email, to=recipients, headers=headers) email = EmailMultiAlternatives(email.subject, email.body, email.from_email, email.to, headers=email.extra_headers) email.attach_alternative(message_html, "text/html") email.send()
def gen_report(report_name, date=None, report_type=None, destination=None, date_gen=None): reports = CommonGroup.objects.filter(group_def_name='SimpleReport', title=report_name) if len(reports)!=1: return None report = reports[0] ret_files = [] if date_gen == None: date_gen = pendulum.now() else: date_gen = pendulum.datetime(date_gen) if date==None: date = date_gen else: date = pendulum.datetime(date) date_gen_str = date_gen.isoformat()[:10] datetime_gen_str = date_gen.isoformat()[:16].replace('T',' ') date_gen_year = date_gen_str[:4] date_gen_month = date_gen_str[5:7] date_gen_id = date_gen_str[:10].replace('-','').replace('.','') param="" if not report_type: report_type = report.json_rep_type.split('.')[-1].strip() if not destination: destination = report.json_dest.split('.')[0].strip() columns = report.json_columns.split(';') width_sum = 0 columns2 = [] width = [] for pos in columns: c = pos.split(":") columns2.append(c[0]) if len(c)>1: try: w = int(c[1]) except: w=0 else: w = 0 width.append(w) width_sum+=w if width_sum<100: c = 0 for pos in width: if pos==0: c+=1 if c>0: dx = int((100-width_sum)/c) width2 = [] for pos in width: if pos==0: width2.append(dx) else: width2.append(pos) width = width2 columns = [] for i in range(len(columns2)): columns.append((columns2[i], width[i])) if 'select' in report.json_mail.lower(): sel = _replace(report.json_mail, date, "") if 'mysql' in sel: cursor = connection.cursor() cursor.execute(sel) parameters=cursor.fetchall() elif 'http' in sel and '://' in sel: r = requests.get(sel) p = r.text parser = SimpleTabParserBase() parser.feed(p) parameters = parser.tables[0][1:] else: with settings.DB as db: db.execute(sel) parameters=db.fetchall() else: parameters = ( ('', report.json_mail), ) count = 0 for param, mail in parameters: mail_to = [p for p in mail.split(';') if p] sel = _replace(report.json_select, date, param) desc = _replace(report.json_desc, date, param) if 'mysql' in sel: cursor = connection.cursor() cursor.execute(sel) object_list=cursor.fetchall() elif 'http' in sel and '://' in sel: r = requests.get(sel) p = r.text parser = SimpleTabParserBase() parser.feed(p) object_list = parser.tables[0][1:] else: with settings.DB as db: db.execute(sel) object_list=db.fetchall() doc_type = 'html' template_names = ['raporty/formsimplereport_' + report_name, 'raporty/formsimplereport',] if report_type == 'pdf' and destination!='2': doc_type = 'pdf' elif report_type == 'odf' and destination!='2': doc_type = 'odf' elif report_type == 'xlsx' and destination!='2': doc_type = 'xlsx' elif report_type == 'txt': doc_type = 'txt' if len(object_list)>0 and len(object_list[0])> len(columns): colors = True sli="0:"+str(len(columns)) else: sli=":" colors = False rep_dict = { "object_list": object_list, 'doc_type': doc_type, 'report_type': report_type, 'date': date, 'columns': columns, 'time_str': datetime_gen_str, 'report': report, 'year': date_gen_year, 'month': date_gen_month, 'colors': colors, 'sli': sli, 'param': param, 'template_names': template_names, 'description': desc } attrs, content = render_doc(rep_dict) desc2 = desc.split('<')[0] if len(mail_to)>0: #mail_to=['*****@*****.**',] if destination=='1': #Mail (attachement) mail = EmailMessage(desc2, MAIL_CONTENT, to=mail_to) mail.attach(f"{report_name}_{date_gen_id}.{doc_type}", content, attrs['Content-Type']) mail.send() elif destination=='2': #Mail (content) mail = EmailMultiAlternatives(desc2, MAIL_CONTENT, to=mail_to) if type(content) == bytes: content = content.decode('utf-8') mail.attach_alternative(content, "text/html") mail.send() elif destination=='3': #User storage pass elif destination=='4': #Group storage pass count += 1 if destination.startswith('5'): #Download if mail_to: x = ';'.join(mail_to) else: x = date_gen_id ret_files.append((f"{report_name}_{x}.{doc_type}", content, attrs)) if ret_files: if len(ret_files) == 1: return ret_files[0] else: file_like_object = io.BytesIO() zipfileobj = zipfile.ZipFile(file_like_object, mode='w') for f in ret_files: zipfileobj.writestr(f[0], f[1]) zipfileobj.close() file_like_object.seek(0) data = file_like_object.read() return ('data.zip', data, { 'Content-Type': 'application/zip', 'Content-Disposition': 'attachment; filename=data.zip;' } ) else: return count