def send_email(request): if request.method != 'POST': form = EmailForm() return render(request, 'submit_event.html', {'email_form': form}) form = EmailForm(request.POST, request.FILES) if form.is_valid(): subject = form.cleaned_data['subject'] message = form.cleaned_data['message'] email = form.cleaned_data['email'] attach = request.FILES['attach'] try: mail = EmailMessage(subject, message, settings.EMAIL_HOST_USER, [email]) mail.attach(attach.name, attach.read(), attach.content_type) response = mail.send() return render(request, 'submit_event.html', {'message': 'Sent email to %s' % (email)}) except Exception as e: return render(request, 'submit_event.html', {'message': e.message}) else: try: return render(request, 'submit_event.html', {'message': form.message}) except AttributeError: return render(request, 'submit_event.html', {'message': "Please fill out all fields on the form.", "email_form":form})
def send_html_mail(subject, message, recipient_list, from_email, html_message, fail_silently=False, reply_to=None, bcc=None): msg_alternative = MIMEMultipart('alternative') msg_html = MIMEText(html_message, _subtype='html', _charset='utf-8') msg_text = MIMEText(message, _charset='utf-8') msg_alternative.attach(msg_text) msg_alternative.attach(msg_html) msg = EmailMessage(subject, '', from_email, recipient_list, reply_to=reply_to, bcc=bcc) msg.mixed_subtype = 'related' msg.attach(msg_alternative) if settings.SSO_EMAIL_LOGO: with open(settings.SSO_EMAIL_LOGO, 'rb') as f: email_image = MIMEImage(f.read()) email_image.add_header('Content-ID', '<{}>'.format("logo")) email_image.add_header("Content-Disposition", "inline", filename="logo") msg.attach(email_image) return msg.send(fail_silently=fail_silently)
def pull_translation_files_from_transifex(domain, data, email=None): version = data.get('version') transifex = Transifex( domain, data.get('app_id'), data.get('target_lang') or data.get('source_lang'), data.get('transifex_project_slug'), version, lock_translations=data.get('lock_translations'), ) translation_file = None try: translation_file, filename = transifex.generate_excel_file() with open(translation_file.name) as file_obj: email = EmailMessage( subject='[{}] - Transifex pulled translations'.format( settings.SERVER_ENVIRONMENT), body="PFA Translations pulled from transifex.", to=[email], from_email=settings.DEFAULT_FROM_EMAIL) email.attach(filename=filename, content=file_obj.read()) email.send() finally: if translation_file and os.path.exists(translation_file.name): os.remove(translation_file.name)
def payment_notification(sender, **kwargs): ipn_obj = sender if ipn_obj.payment_status == ST_PP_COMPLETED: # payment was successful order = get_object_or_404(Order, id=ipn_obj.invoice) # mark the order as paid order.paid = True order.save() # create invoice e-mail subject = 'My Shop - Invoice no. {}'.format(order.id) message = 'Please, find attached the invoice for your recent purchase.' email = EmailMessage(subject, message, '*****@*****.**', [order.email]) # generate PDF html = render_to_string('orders/order/pdf.html', {'order': order}) out = BytesIO() css_path = os.path.join(settings.STATICFILES_DIRS[0], 'css/pdf.css') weasyprint.HTML(string=html).write_pdf(out, stylesheets=[weasyprint.CSS(css_path)]) # attach PDF file email.attach('order_{}.pdf'.format(order.id), out.getvalue(), 'application/pdf') # send e-mail email.send()
def __prepareMessagesQueue(self): manEmail = Site.objects.get_current().managementemail messagesList = [] if manEmail is None: logger.debug('mail config does not exist') return messagesList for u in User.objects.all(): userProfile = u.userprofile if (userProfile is not None) and (u.email is not None): #check if file to send exist path = MEDIA_ROOT + '/newsletters/' + str(u.id) + '.pdf' if not os.path.exists(path): continue title = manEmail.title message = manEmail.message emailMessage = EmailMessage(title, message, 'Redakcja Biuletynu Polonistycznego ' + '<' + BPORTAL_CONTACT_EMAIL_ADDRES_FROM + '>', [u.email]) filename = 'newsletter_biuletyn.pdf' with open(path, 'rb') as f: content = f.read() emailMessage.attach(filename, content) messagesList.append(emailMessage) userNewsConfig = None userNewsConfig = NewsletterConfig.objects.get(user=userProfile) # newsletter is not configured if userNewsConfig is None: continue userNewsConfig.last_sent = date.today() userNewsConfig.save() return messagesList
def home(request): if request.method == 'POST': form = ContactForm(request.POST, request.FILES) if form.is_valid(): contact = form.save() message = render_to_string("email.html", {'contact': contact}) msg = EmailMessage('Info verzoek van anverhuizen.be', message, contact.email, ['*****@*****.**']) msg.content_subtype = "html" if 'attachment' in request.FILES: request.FILES['attachment'].seek(0) msg.attach(request.FILES['attachment'].name, request.FILES['attachment'].read(), request.FILES['attachment'].content_type) msg.send(fail_silently=False) messages.success(request, _("Ik heb jouw bericht ontvangen en zal zo snel mogelijk contact opnemen.")) return HttpResponseRedirect(reverse('home')) else: form = ContactForm() return render_to_response('home.html', {'form': form}, RequestContext(request))
def user_report(): today = date.today() start_date = today + relativedelta(months=-1) qs = Country.objects.exclude(schema_name__in=['public', 'uat', 'frg']) fieldnames = ['country', 'total_users', 'unicef_users', 'users_last_month', 'unicef_users_last_month'] csvfile = StringIO() writer = csv.DictWriter(csvfile, fieldnames=fieldnames) writer.writeheader() for country in qs: writer.writerow({ 'country': country, 'total_users': get_user_model().objects.filter(profile__country=country).count(), 'unicef_users': get_user_model().objects.filter( profile__country=country, email__endswith='@unicef.org' ).count(), 'users_last_month': get_user_model().objects.filter( profile__country=country, last_login__gte=start_date ).count(), 'unicef_users_last_month': get_user_model().objects.filter( profile__country=country, email__endswith='@unicef.org', last_login__gte=start_date ).count(), }) mail = EmailMessage('Report Latest Users', 'Report generated', '*****@*****.**', settings.REPORT_EMAILS) mail.attach('users.csv', csvfile.getvalue().encode('utf-8'), 'text/csv') mail.send()
def send_mail(subject, message, from_email, recipient_list, priority="medium", fail_silently=False, auth_user=None, auth_password=None, attach_files=[]): from django.utils.encoding import force_unicode from mailer.models import make_message from django.core.mail.message import EmailMessage priority = PRIORITY_MAPPING[priority] # need to do this in case subject used lazy version of ugettext subject = force_unicode(subject) message = force_unicode(message) msg = make_message(subject=subject, body=message, from_email=from_email, to=recipient_list, priority=priority) email = msg.email email = EmailMessage(email.subject, email.body, email.from_email, email.to) for f in attach_files: if isinstance(f, str): email.attach_file(f) elif isinstance(f, (tuple, list)): n, fi, mime = f + (None,) * (3 - len(f)) email.attach(n, fi, mime) msg.email = email msg.save() return 1
def send_email_feedback(self, feedback_pk, sender, recipents): try: feedback = Feedback.objects.get(pk=feedback_pk) except Feedback.DoesNotExist as exc: logger.error('Failed processing_crash_dump', exc_info=True, extra=dict(crash_pk=feedback_pk)) raise self.retry(exc=exc, countdown=2**send_email_feedback.request.retries) recipients = [x.strip() for x in recipents.split(',')] body = email_body_tmpl % ( feedback.description, feedback.page_url, feedback.email, feedback.ip, feedback.feedback_data, ) email = EmailMessage("Feedback # %s" % feedback_pk, body, sender, recipients) attachments = [ feedback.screenshot, feedback.blackbox, feedback.system_logs, feedback.attached_file ] for attach in attachments: if attach: email.attach(os.path.basename(attach.name), attach.read()) email.send()
def process_talk(self, event, talk): application = talk.application user = application.applicant.user body = loader.render_to_string( "talks/emails/survey_results.eml", { "talk": talk, "user": user, "event": event, "application": application, }) email = EmailMessage( subject="Survey results", body=body, from_email="*****@*****.**", to=["{} <{}>".format(user.full_name, user.email)], ) chart = generate_survey_score_chart(talk, format="png") email.attach("survey_scores.png", chart, "image/png") filename = f"{slugify(user.full_name)}.eml" print(f"Generating: {filename}") with open(filename, "w") as f: f.write(email.message().as_string())
def transform_sms_to_email_message(sms_message): backend = getattr(settings, "SMSISH_MAILTRAP_SMS_BACKEND_EMAIL_BACKEND", DEFAULT_SMS_OVER_EMAIL_BACKEND) conn = get_connection(backend=backend) email = EmailMessage( subject="SMS over Email", body=sms_message.body, from_email=emailify_phone_number(sms_message.from_email), to=[emailify_phone_number(r) for r in sms_message.to], bcc=[emailify_phone_number(r) for r in sms_message.bcc] if sms_message.bcc else None, connection=conn, attachments=None, headers=None, cc=[emailify_phone_number(r) for r in sms_message.cc] if sms_message.cc else None, reply_to=[ emailify_phone_number(sms_message.reply_to) for r in sms_message.reply_to ] if sms_message.reply_to else None, ) email.attach("metadata.txt", "Content-Length: {}".format(len(sms_message.body)), "text/plain") return email
def send_email_feedback(self, feedback_pk, sender, recipents): try: feedback = Feedback.objects.get(pk=feedback_pk) except Feedback.DoesNotExist as exc: logger.error('Failed processing_crash_dump', exc_info=True, extra=dict(crash_pk=feedback_pk)) raise self.retry(exc=exc, countdown=2 ** send_email_feedback.request.retries) recipients = [x.strip() for x in recipents.split(',')] body = email_body_tmpl % ( feedback.description, feedback.page_url, feedback.email, feedback.ip, feedback.feedback_data, ) email = EmailMessage("Feedback # %s" % feedback_pk, body, sender, recipients) attachments = [ feedback.screenshot, feedback.blackbox, feedback.system_logs, feedback.attached_file ] for attach in attachments: if attach: email.attach(os.path.basename(attach.name), attach.read()) email.send()
def sender(request): if request.method == 'POST': doc_id = request.POST.get('doc_id') comment = request.POST.get('comment') name_email = request.POST.get('name_email') document = Document.objects.get(id=doc_id) personals = document.personal.all() send_to = [] for per in personals: send_to.append(per.email) # Build message email = EmailMessage(subject=name_email, body=comment, from_email='*****@*****.**',to=send_to, headers = {'Reply-To': '*****@*****.**'}) # Open file attachment = open(u''+document.docfile.name, 'rb') # Attach file email.attach("attach_file.pdf", attachment.read(),'application/pdf') # Send message with built-in send() method email.send() msg_ok = "Send message success" print('Send message success') return render_to_response('group1/send.html', {'document': document, 'msg_ok': msg_ok} , context_instance=RequestContext(request))
def email_household_details(domain, transitions, user_email): try: filestream = Households(domain).dump(transitions) except Exception as e: email = EmailMessage( subject='[{}] - Location Reassignment Household Dump Failed'. format(settings.SERVER_ENVIRONMENT), body="The request could not be completed. Something went wrong. " "Error raised : {}. " "Please report an issue if needed.".format(e), to=[user_email], from_email=settings.DEFAULT_FROM_EMAIL) email.send() raise e else: email = EmailMessage( subject='[{}] - Location Reassignment Household Dump Completed'. format(settings.SERVER_ENVIRONMENT), body="The request has been successfully completed.", to=[user_email], from_email=settings.DEFAULT_FROM_EMAIL) if filestream: email.attach(filename="Households.xlsx", content=filestream.read()) else: email.body += "There were no house hold details found." email.send()
def email(request, template_name="email.html"): ctx = dict() if request.method == "POST": email_address = request.POST.get("email", "your mom") trips = Trip.objects.filter(user=request.user) csv_data = "\n".join(["%s, %s, %s %s, %s" % (trip.date, trip.odometer_start, trip.odometer_end, trip.distance(), trip.reason) for trip in trips]) email = EmailMessage('MileTracker Data', 'Your data is attached', '*****@*****.**', ['*****@*****.**', email_address]) email.attach('miletracker_report.csv', csv_data, 'text/csv') email.send() messages.info(request, "We've sent an email report to: %s" % email_address) return HttpResponseRedirect(reverse("log")) return render_to_response( template_name, RequestContext(request, ctx))
def backup_project_from_transifex(domain, data, email): version = data.get('version') transifex = Transifex(domain, data.get('app_id'), data.get('source_lang'), data.get('transifex_project_slug'), version, use_version_postfix='yes' in data['use_version_postfix']) project_details = transifex.client.project_details().json() target_lang_codes = project_details.get('teams') with NamedTemporaryFile(mode='w+b', suffix='.zip') as tmp: with ZipFile(tmp, 'w') as zipfile: for target_lang in target_lang_codes: transifex = Transifex(domain, data.get('app_id'), target_lang, data.get('transifex_project_slug'), version, use_version_postfix='yes' in data['use_version_postfix']) translation_file, filename = transifex.generate_excel_file() with open(translation_file.name, 'rb') as file_obj: zipfile.writestr(filename, file_obj.read()) os.remove(translation_file.name) tmp.seek(0) email = EmailMessage( subject='[{}] - Transifex backup translations'.format(settings.SERVER_ENVIRONMENT), body="PFA Translations backup from transifex.", to=[email], from_email=settings.DEFAULT_FROM_EMAIL ) filename = "%s-TransifexBackup.zip" % project_details.get('name') email.attach(filename=filename, content=tmp.read()) email.send()
def email_project_from_hq(domain, data, email): """Emails the requester with an excel file translations to be sent to Transifex. Used to verify translations before sending to Transifex """ lang = data.get('source_lang') project_slug = data.get('transifex_project_slug') quacks_like_a_transifex = AppTranslationsGenerator(domain, data.get('app_id'), data.get('version'), key_lang=lang, source_lang=lang, lang_prefix='default_') parser = TranslationsParser(quacks_like_a_transifex) try: translation_file, __ = parser.generate_excel_file() with open(translation_file.name, 'rb') as file_obj: email = EmailMessage( subject='[{}] - HQ translation download'.format( settings.SERVER_ENVIRONMENT), body="Translations from HQ", to=[email], from_email=settings.DEFAULT_FROM_EMAIL) filename = "{project}-{lang}-translations.xls".format( project=project_slug, lang=lang) email.attach(filename=filename, content=file_obj.read()) email.send() finally: try: os.remove(translation_file.name) except (NameError, OSError): pass
def backup_project_from_transifex(domain, data, email): version = data.get('version') transifex = Transifex(domain, data.get('app_id'), data.get('source_lang'), data.get('transifex_project_slug'), version, use_version_postfix='yes' in data['use_version_postfix']) project_details = transifex.client.project_details().json() target_lang_codes = project_details.get('teams') with NamedTemporaryFile(mode='w+b', suffix='.zip') as tmp: with ZipFile(tmp, 'w') as zipfile: for target_lang in target_lang_codes: transifex = Transifex(domain, data.get('app_id'), target_lang, data.get('transifex_project_slug'), version, use_version_postfix='yes' in data['use_version_postfix']) translation_file, filename = transifex.generate_excel_file() with open(translation_file.name, 'rb') as file_obj: zipfile.writestr(filename, file_obj.read()) os.remove(translation_file.name) tmp.seek(0) email = EmailMessage( subject='[{}] - Transifex backup translations'.format( settings.SERVER_ENVIRONMENT), body="PFA Translations backup from transifex.", to=[email], from_email=settings.DEFAULT_FROM_EMAIL) filename = "%s-TransifexBackup.zip" % project_details.get('name') email.attach(filename=filename, content=tmp.read()) email.send()
def send_csv(self, emails=[]): filename, csv_file = self.create_csv() message = EmailMessage(subject='{} LEVEL ASSORTMENT REPORT'.format(self.level.upper()), from_email=EMAIL_HOST_USER, to=emails) message.attach(filename, csv_file.getvalue(), 'text/csv') print message.send()
def email_other_cases_details(domain, transitions, uploaded_filename, user_email): try: transition_objs = [ Transition(**transition) for transition in transitions ] filestream = OtherCases(domain).dump(transition_objs) except Exception as e: email = EmailMessage( subject= f"[{settings.SERVER_ENVIRONMENT}] - Location Reassignment Other Cases Dump Failed", body=linebreaksbr( f"The request could not be completed for file {uploaded_filename}. Something went wrong.\n" f"Error raised : {e}.\n" "Please report an issue if needed."), to=[user_email], from_email=settings.DEFAULT_FROM_EMAIL) email.content_subtype = "html" email.send() raise e else: email = EmailMessage( subject= f"[{settings.SERVER_ENVIRONMENT}] - Location Reassignment Other Cases Dump Completed", body= f"The request has been successfully completed for file {uploaded_filename}. ", to=[user_email], from_email=settings.DEFAULT_FROM_EMAIL) if filestream: email.attach(filename="Other Cases.zip", content=filestream.read()) else: email.body += "There were no cases found. " email.body += f"Please note that the cases are fetched only for " \ f"{', '.join(OtherCases.valid_operations)}." email.send()
def verification_send_page(request): user = UserExt.objects.get(pk=request.user.pk) form_verification_send = VerificationSendForm() if user.userinfo.virifield == UserInfo.UNDF: if request.method == 'POST': form_verification_send = VerificationSendForm(request.POST) if form_verification_send.is_valid(): # Создание, наполнение, отплавка сообщения email = EmailMessage() email.subject = "Verification request. User: " + user.username email.body = form_verification_send.data['message'] email.from_email = user.email email.to = ['*****@*****.**'] image1 = request.FILES['image1'] image2 = request.FILES['image2'] email.attach(image1.name, image1.read(), image1.content_type) email.attach(image2.name, image2.read(), image2.content_type) email.send() user.userinfo.virifield = UserInfo.WAIT user.userinfo.save() return HttpResponseRedirect('/user/verification/send') return render(request, 'UserProfile/verification/verification_send_page.html', {'form_verification_send': form_verification_send}) \ if user.userinfo.virifield == UserInfo.UNDF \ else render(request, 'UserProfile/verification/verification_status_page.html', {'UserStatus': UserInfo})
def send_failure_mail(to_list, subject, message, req, user=None, sender=None, headers=None): ''' Function to send mail :param to_list: :param subject: :param message: :param sender: :param headers: :param design: ''' try: if not sender: sender = "Meisterdish<*****@*****.**>" if not headers: headers = { 'Reply-To': "Meisterdish<*****@*****.**>", 'From': "Meisterdish<*****@*****.**>", } source_ip = (get_client_ip(req) if get_client_ip(req) is not None else 'Not Available' ) usr = (user.full_name if user is not None else 'Not Applicable') dic = { 'error_reason': message, 'sub': subject, 'error_time': timezone.now(), 'error_ip': source_ip, 'user': usr, } log.info("data is " + str(dic)) log.info("User is : " + str(user)) message_html = render_to_string('failure_alert_email.html', dic) msg = EmailMessage( subject, message_html, sender, [to_list, ], headers=headers) log.info('Message Details :' + str(msg)) msg.content_subtype = "html" msg.mixed_subtype = 'related' log.info('Sending message') imgs = { "meisterdish_logo": os.path.join( settings.STATIC_ROOT, "default", "logo_email.png"), } for cid, img in imgs.items(): fp = open(img, 'rb') msg_image = MIMEImage(fp.read()) fp.close() msg_image.add_header('Content-ID', '<' + cid + '>') msg.attach(msg_image) return msg.send() except Exception as error: log.error("Failure Message failed due to: " + error.message)
def notify_success(subject, body, email, filestream=None, filename=None): email_message = EmailMessage(subject=subject, body=linebreaksbr(body), to=[email], from_email=settings.DEFAULT_FROM_EMAIL) if filestream and filename: email_message.attach(filename=filename, content=filestream.read()) email_message.content_subtype = "html" email_message.send()
def send_an_email(subject, body, from_email, to_emails, attachment=None): email = EmailMessage() email.subject = subject email.body = body email.from_email = from_email email.to = to_emails if attachment: # email.attach_file(attachment) email.attach('payslip.pdf', attachment, 'application/pdf') email.send()
def send_an_email(subject, body, from_email, to_emails, attachment=None): email = EmailMessage() email.subject = subject email.body = body email.from_email = from_email email.to = to_emails if attachment: # email.attach_file(attachment) email.attach('payslip.pdf', attachment, 'application/pdf') email.send()
def send_email_with_file_attachment(sender, receiver, subject, body, filename, content, brand='bajaj'): try: yesterday = datetime.now().date() - timedelta(days=1) message = EmailMessage(subject, body, sender, receiver) message.attach(filename + yesterday.strftime("%b %d %Y") +'.csv', content.getvalue(), 'text/csv') message.send() audit_manager.email_log(brand, subject, " ", sender, receiver); return True except Exception as ex: logger.error('Exception while sending mail {0}'.format(ex)) return False
def send_referel_mail(to_list, subject, message, sender=None, headers=None, design=True): ''' Function to send referral email :param to_list: :param subject: :param message: :param sender: :param headers: :param design: ''' if not sender: sender = "Meisterdish<*****@*****.**>" if not headers: headers = { 'Reply-To': "Meisterdish<*****@*****.**>", 'From': "Meisterdish<*****@*****.**>", } msg = EmailMessage(subject, message, sender, to_list, headers=headers) msg.content_subtype = "html" msg.mixed_subtype = 'related' share_images = { "meisterdish_logo": os.path.join( settings.STATIC_ROOT, "default", "logo_email.png"), "deliver": os.path.join( settings.STATIC_ROOT, "default", "deliver.png"), "recepies": os.path.join( settings.STATIC_ROOT, "default", "recepies.png"), "cook": os.path.join( settings.STATIC_ROOT, "default", "cook.png"), "fb": os.path.join( settings.STATIC_ROOT, "default", "fb_icon.png"), "instagram": os.path.join( settings.STATIC_ROOT, "default", "inst_icon.png"), "twitter": os.path.join( settings.STATIC_ROOT, "default", "tw_icon.png"), } if design: for cid, img in share_images.items(): fp = open(img, 'rb') msg_image = MIMEImage(fp.read()) fp.close() msg_image.add_header('Content-ID', '<' + cid + '>') msg.attach(msg_image) else: imgs = {"meisterdish_logo": os.path.join( settings.STATIC_ROOT, "default", "logo_email.png")} for cid, img in imgs.items(): fp = open(img, 'rb') msg_image = MIMEImage(fp.read()) fp.close() msg_image.add_header('Content-ID', '<' + cid + '>') msg.attach(msg_image) return msg.send()
def mail_pdf(self, resp, msg, receivers): tmp_file_html = resp.render_to_temporary_file( template_name=self.template_name, delete=False) tmp_file = resp.convert_to_pdf(tmp_file_html.name) footer_template = 'content/email/transfer_idea_email_footer_text.txt' extended_msg = "\n".join((msg, render_to_string(footer_template))) msg_ready = EmailMessage(subject=_("Idea liitteenä - nuortenideat.fi"), from_email=settings.DEFAULT_FROM_EMAIL, body=extended_msg, to=receivers) msg_ready.attach(filename=self.filename, content=tmp_file) return msg_ready.send()
def send_emails(self, subject): self._clear_log() for job in self.current_jobs: user, message, att = job.user, job.message(), job.attachment() email = EmailMessage(subject, message, GAE_MAIL_ACCOUNT, [user.email]) if att: email.attach(att['name'], att['data'], att['mimetype']) email.send() self._log(_("Message sent to: %s") % user.email) return self._log_buffer
def test_attachment_guess_mimetype_fallback(): email_message = EmailMessage(**base_options) email_message.attach('file', 'test content') actual = SparkPostMessage(email_message) expected = dict(attachments=[{ 'name': 'file', 'data': 'dGVzdCBjb250ZW50', 'type': 'application/octet-stream' }]) expected.update(base_expected) assert actual == expected
def test_attachment_guess_mimetype(): email_message = EmailMessage(**base_options) email_message.attach('file.txt', 'test content') actual = SparkPostMessage(email_message) expected = dict(attachments=[{ 'name': 'file.txt', 'data': 'dGVzdCBjb250ZW50', 'type': 'text/plain' }]) expected.update(base_expected) assert actual == expected
def mail_order_confirmation( to_list, subject, message, order, sender="Meisterdish<*****@*****.**>", headers={ 'Reply-To': "Meisterdish<*****@*****.**>", 'From': "Meisterdish<*****@*****.**>", }): ''' Function to send order confirmation email :param to_list: :param subject: :param message: :param order: :param sender: :param headers: ''' try: msg = EmailMessage(subject, message, sender, to_list, headers=headers) msg.content_subtype = "html" msg.mixed_subtype = 'related' user = order.cart.user first_name = user.first_name.title( ) if user.role.id == settings.ROLE_USER else "Guest" if "Guest" not in first_name: share_images = { "share_fb": os.path.join( settings.STATIC_ROOT, "default", "share_fb.png"), "meisterdish_logo": os.path.join( settings.STATIC_ROOT, "default", "logo_email.png"), } else: share_images = { "meisterdish_logo": os.path.join( settings.STATIC_ROOT, "default", "logo_email.png"), } for ci in order.cart.cartitem_set.all(): share_images["img_" + str(ci.meal.id)] = ( ci.meal.main_image.image.path if ci.meal.main_image else os.path.join( settings.STATIC_ROOT, "default", "meal-default.jpg")) for cid, img in share_images.items(): fp = open(img, 'rb') msg_image = MIMEImage(fp.read()) fp.close() msg_image.add_header('Content-ID', '<' + cid + '>') msg.attach(msg_image) return msg.send() except KeyError as error: log.error(error.message) return False
def mail_pdf(self, resp, msg, receivers): tmp_file_html = resp.render_to_temporary_file(template_name=self.template_name, delete=False) tmp_file = resp.convert_to_pdf(tmp_file_html.name) footer_template = 'content/email/transfer_idea_email_footer_text.txt' extended_msg = "\n".join((msg, render_to_string(footer_template))) msg_ready = EmailMessage( subject=_("Idea liitteenä - nuortenideat.fi"), from_email=settings.DEFAULT_FROM_EMAIL, body=extended_msg, to=receivers ) msg_ready.attach(filename=self.filename, content=tmp_file) return msg_ready.send()
def sendInvoice(invoice, **kwargs): ctx = kwargs ctx.update({'invoice': invoice, 'name': Site.objects.get_current()}) mailContent = render_to_string('invoices/invoice_mail.html', ctx) message = EmailMessage(_('invoice'), mailContent, invoice.contractor.user.email, [invoice.subscriber.user.email], []) stream = StringIO.StringIO() generator.generate(invoice, stream) message.attach('%s.pdf' % _('invoice'), stream.getvalue(), 'application/pdf') message.send(fail_silently=True)
def newmail(request): form = emailForm() if request.method == 'POST': form = emailForm(request.POST, request.FILES) if form.is_valid(): sub = form.cleaned_data['subject'] msg = form.cleaned_data['message'] to = form.cleaned_data['to'] image = form.cleaned_data['photo'] email = EmailMessage(subject=sub, body=msg, from_email='', to=[to]) email.attach(image.name, image.read(), image.content_type) email.send() return HttpResponse("Email Send Successfully") return render(request, "my_app/userdetail.html", {'form': form})
def test_attachment_guess_mimetype_fallback(): email_message = EmailMessage(**base_options) email_message.attach('file', 'test content') actual = SparkPostMessage(email_message) expected = dict( attachments=[ { 'name': 'file', 'data': 'dGVzdCBjb250ZW50', 'type': 'application/octet-stream' } ] ) expected.update(base_expected) assert actual == expected
def test_attachment_unicode(): email_message = EmailMessage(**base_options) email_message.attach('file.txt', u'test content', 'text/plain') actual = SparkPostMessage(email_message) expected = dict( attachments=[ { 'name': 'file.txt', 'data': 'dGVzdCBjb250ZW50', 'type': 'text/plain' } ] ) expected.update(base_expected) assert actual == expected
def MailSending(request): if request.method == 'POST': form = MailSendingForm(request.POST, request.FILES) if form.is_valid(): subject = form.cleaned_data['subject'] message = form.cleaned_data['message'] from_mail = form.cleaned_data['from_mail'] to_mail = form.cleaned_data['to_mail'] attachment = form.cleaned_data['attachment'] email = EmailMessage(subject, message, from_mail, [to_mail]) email.attach(attachment.name, attachment.read(), attachment.content_type) email.send() return HttpResponse('Email send successfully :).....!!!!!!') else: form = MailSendingForm() return render(request, 'djangoapp/mailsend.html', {'form': form})
def event_sent_giftcards_for_today(content): '''This event will trigger when giftcards for today are sent''' today = datetime.now().strftime('%Y-%m-%d') if settings.DEBUG: email = [settings.DEBUG_EMAIL_RECEIVER] else: email = [x[1] for x in settings.GIVIU_FOUNDERS] print 'sending to ' + str(email) msg = EmailMessage() msg.subject = 'Giftcards Sent ' + today msg.body = 'Please find attached Giftcards Sent Today' msg.from_email = settings.EMAIL_DEFAULT_FROM msg.to = email msg.attach(filename='data.json', mimetype='application/json', content=dumps(content)) msg.send()
def email(request): # send_mail('subject','Hello world','*****@*****.**',['tomail'],fail_silently=False) if request.method=='POST': form = MailSendingForm(request.POST,request.FILES) if form.is_valid(): subject = form.cleaned_data['subject'] message = form.cleaned_data['message'] frommail = form.cleaned_data['frommail'] tomail = form.cleaned_data['tomail'] attachment = form.cleaned_data['attachment'] email = EmailMessage(subject,message,frommail,[tomail]) email.attach(attachment.name,attachment.read(),attachment.content_type) email.send() else: form = MailSendingForm() return render(request,'mailwithattachment.html',{'form':form})
def email(self): """ Send email to award recipient User email """ # Setup logger for debugging logger = logging.getLogger(__name__) # Create email fields this_subject = "You've received an award" email_body = 'Congratulations {0}! {1} has awarded you with {2}. ' +\ 'Your award certificate is attached.' email_body = email_body.format(self.to_name, self.from_name, self.award_type) # Generate PDF path = self.__generate_pdf() filename = os.path.split(path)[1] # Open file and read contents into variable try: pdf = open(path, mode='rb') pdf_content = pdf.read() pdf.close() except OSError as exception: logger.error('OS error: %s ', exception) # Create email with pdf attached email = EmailMessage(subject=this_subject, body=email_body, from_email='*****@*****.**', to=[self.to_email], headers={'Reply-To': '*****@*****.**'}) try: email.attach(filename, pdf_content, 'application/pdf') email.send() except: logger.error('Failed to send email') # Clean-up temp file try: os.remove(path) except OSError: pass
def mail(self, request): message = self.render_message(request) headers = {} if self.cleaned_data.has_key('email'): headers = {'Reply-to': self.cleaned_data.get('email')} msg = EmailMessage(self.subject, message, self.sender, self.recipients, headers=headers) if request.FILES: uploaded_file = request.FILES['file'] msg.attach(uploaded_file.name, uploaded_file.read(), uploaded_file.content_type) msg.send() self.after_mail(message=message, headers=headers)
def transform_sms_to_email_message(sms_message): backend = getattr(settings, "SMSISH_MAILTRAP_SMS_BACKEND_EMAIL_BACKEND", DEFAULT_SMS_OVER_EMAIL_BACKEND) conn = get_connection(backend=backend) email = EmailMessage( subject="SMS over Email", body=sms_message.body, from_email=emailify_phone_number(sms_message.from_email), to=[emailify_phone_number(r) for r in sms_message.to], bcc=[emailify_phone_number(r) for r in sms_message.bcc] if sms_message.bcc else None, connection=conn, attachments=None, headers=None, cc=[emailify_phone_number(r) for r in sms_message.cc] if sms_message.cc else None, reply_to=[emailify_phone_number(sms_message.reply_to) for r in sms_message.reply_to] if sms_message.reply_to else None, ) email.attach("metadata.txt", "Content-Length: {}".format(len(sms_message.body)), "text/plain") return email
class TemplateAttachmentEmail(object): """ Email with a templated attachment. """ def __init__(self, from_address, attachment_name, attachment_template, attachment_data, attachment_mime): self.email = None self.attachment_content = None self.from_address = from_address self.attachment_name = attachment_name self.attachment_template = attachment_template self.attachment_data = attachment_data self.attachment_mime = attachment_mime def send(self, to_address, subject, body, route=None): connection = None if route: route_host = settings.SMTP_ROUTES[route]["HOST"] route_port = settings.SMTP_ROUTES[route]["PORT"] route_user = settings.SMTP_ROUTES[route].get("USERNAME", '') route_password = settings.SMTP_ROUTES[route].get("PASSWORD", '') route_use_tls = settings.SMTP_ROUTES[route].get("USE_TLS", True) connection = get_connection(host=route_host, port=route_port, username=route_user, password=route_password, use_tls=route_use_tls) self.attachment_content = render_to_string(self.attachment_template, self.attachment_data) if connection: self.email = EmailMessage(subject, body, self.from_address, to_address, connection=connection) else: self.email = EmailMessage(subject, body, self.from_address, to_address) self.email.attach(self.attachment_name, self.attachment_content, self.attachment_mime) self.email.send(fail_silently=False)
def send_notification_email(): upload_apks = Apk.objects.count() if upload_apks % 5 == 0: apks = Apk.objects.all() \ .prefetch_related('user') \ .order_by('-created_at') csv_file = get_csv_file(apks) zip_file = get_zip_file(apks[:10]) try: user = User.objects.filter(is_superuser=True).first() message = "Upload apks : {}".format(upload_apks) email = EmailMessage('Upload apks', message, EMAIL_HOST_USER, [user.email]) email.attach('report.csv', csv_file.getvalue(), 'text/csv') email.attach('apks.zip', zip_file.getvalue(), 'application/octet-stream') email.send(fail_silently=False) except User.DoesNotExist: pass
def pull_translation_files_from_transifex(domain, data, user_email=None): def notify_error(error): email = EmailMessage( subject='[{}] - Transifex pulled translations'.format( settings.SERVER_ENVIRONMENT), body= "The request could not be completed. Something went wrong with the download. " "Error raised : {}. " "If you see this repeatedly and need support, please report an issue. " .format(error), to=[user_email], from_email=settings.DEFAULT_FROM_EMAIL) email.send() version = data.get('version') transifex = Transifex(domain, data.get('app_id'), data.get('target_lang') or data.get('source_lang'), data.get('transifex_project_slug'), version, lock_translations=data.get('lock_translations'), use_version_postfix='yes' in data['use_version_postfix']) translation_file = None try: translation_file, filename = transifex.generate_excel_file() with open(translation_file.name, 'rb') as file_obj: email = EmailMessage( subject='[{}] - Transifex pulled translations'.format( settings.SERVER_ENVIRONMENT), body="PFA Translations pulled from transifex.", to=[user_email], from_email=settings.DEFAULT_FROM_EMAIL) email.attach(filename=filename, content=file_obj.read()) email.send() except Exception as e: notify_error(e) six.reraise(*sys.exc_info()) finally: if translation_file and os.path.exists(translation_file.name): os.remove(translation_file.name)
class TemplateAttachmentEmail(object): """ Email with a templated attachment. """ def __init__(self, from_address, attachment_name, attachment_template, attachment_data, attachment_mime): self.email = None self.attachment_content = None self.from_address = from_address self.attachment_name = attachment_name self.attachment_template = attachment_template self.attachment_data = attachment_data self.attachment_mime = attachment_mime def send(self, to_address, subject, body, route=None): connection = None if route: route_host = settings.SMTP_ROUTES[route]["HOST"] route_port = settings.SMTP_ROUTES[route]["PORT"] route_user = settings.SMTP_ROUTES[route].get("USERNAME", '') route_password = settings.SMTP_ROUTES[route].get("PASSWORD", '') route_use_tls = settings.SMTP_ROUTES[route].get("USE_TLS", True) connection = get_connection(host=route_host, port=route_port, username=route_user, password=route_password, use_tls=route_use_tls) self.attachment_content = render_to_string(self.attachment_template, self.attachment_data) if connection: self.email = EmailMessage(subject, body, self.from_address, to_address, connection=connection) else: self.email = EmailMessage(subject, body, self.from_address, to_address) self.email.attach(self.attachment_name, self.attachment_content, self.attachment_mime) self.email.send(fail_silently=False)
def get(self, *args, **kwargs): from django.conf import settings user = User.objects.get(id=35) print user.qrcode.url subject = "Your sabha unique identity" message = "Keep attached QR code with you" sender = '*****@*****.**' recipients = ['*****@*****.**'] mail = EmailMessage(subject, message, sender, recipients) path = settings.BASE_DIR + user.qrcode.url print path fp = open(path, 'rb') msg_img = MIMEImage(fp.read()) msg_img.add_header('Content-ID', '<{}>'.format(user.qrcode.url)) fp.close() print msg_img mail.attach(msg_img) # send_mail(subject, message, sender, recipients) mail.send() return Response({'msg': 'success...'}, status=status.HTTP_200_OK)
def _send_email_with_results(recepients, results_csv): """ Triggers email with csv attachment. """ email_subject = _('Progress migration result') email_text = _('Migration is finished. Please review this email attachment.') from_address = configuration_helpers.get_value('email_from_address', settings.DEFAULT_FROM_EMAIL) recepients = recepients or [settings.SERVER_EMAIL] attachment_name = 'MigrationResults.csv' email = EmailMessage() email.subject = email_subject email.body = email_text email.from_email = from_address email.to = recepients email.attach(attachment_name, results_csv, 'text/csv') email.send() log.info('Email with users progress migration results sent to %s', recepients)
def emailFeed(send_to,message=None,attachment=None,extension=None): if send_to == "" or send_to == None: print "No email address on record for this user, so I can't send them their feed" return if (message=="" or message==None) and attachment==None: print "nothing to send" return email = EmailMessage() email.subject = "InfoCatch Feed" email.from_email = "*****@*****.**" email.to = [ send_to, ] if extension == None: mType = "text/plain" email.body = message elif extension=="pdf": email.body = "Please find your feed attatched." mType = "application/pdf" email.attach(filename = "newspaper", mimetype = mType, content = attachment) email.send()
def send_email(request, event_id): event = get_object_or_404(Events, pk=event_id) output = make_calendar_object(event_id) attachment_name = "%s.ics" % slugify(event.name + "-" + str(event.start_datetime.year)) context = {"event": event, "title": "Uh-oh!", "message": "Something went wrong when sending out the invitation"} ctx_dict = { "event_name": event.name, "event_description": event.description, "event_start": event.start_datetime, "event_id": event.pk, "site": Site.objects.get_current(), } subject = "Events@EPAM Event invitation to " + event.name message = render_to_string("events/event_invite_message.txt", ctx_dict) try: mail = EmailMessage(subject, message, settings.EMAIL_HOST_USER, settings.TEST_EMAIL_LIST) mail.attach(attachment_name, output, "text/calendar") mail.send() event.flag_submitted() context["title"] = "Success!" context["message"] = "Invitation was successfully sent!" return render(request, "events/send_done.html", context) except: e = sys.exc_info()[0] print e context["title"] = "Error!" context["message"] = "There was an error sending your invitation." return render(request, "events/send_done.html", context) return render(request, "events/send_done.html", context)
def MailSending(request): form = MailSendingForm if request.method == 'POST': form = MailSendingForm(request.POST, request.FILES) if form.is_valid: subject = request.POST.get('subject') message = request.POST.get('message') from_mail = request.POST.get('from_mail') to_mail = request.POST.get('to_mail') attachment = request.POST.get('attachment') email = EmailMessage(subject, message, from_mail, [to_mail]) email.attach(attachment.name, attachment.read(), attachment.content_type) email.send() return HttpResponse('Mail Sent Successfully!') else: form = MailSendingForm() return render(request, 'newapp/mailsend.html', {'form': form})
def pull_translation_files_from_transifex(domain, data, email=None): version = data.get('version') transifex = Transifex(domain, data.get('app_id'), data.get('target_lang') or data.get('source_lang'), data.get('transifex_project_slug'), version, lock_translations=data.get('lock_translations'), use_version_postfix='yes' in data['use_version_postfix']) translation_file = None try: translation_file, filename = transifex.generate_excel_file() with open(translation_file.name, 'rb') as file_obj: email = EmailMessage( subject='[{}] - Transifex pulled translations'.format(settings.SERVER_ENVIRONMENT), body="PFA Translations pulled from transifex.", to=[email], from_email=settings.DEFAULT_FROM_EMAIL ) email.attach(filename=filename, content=file_obj.read()) email.send() finally: if translation_file and os.path.exists(translation_file.name): os.remove(translation_file.name)
def approve(request, report_id): """ approves the pending reports :param report_id: The id of pending report :return: redirect to list of pending reports """ report = get_report_by_id(report_id) report.confirm_status = 1 report.save() admin = Administrator.objects.get(user=request.user) volunteer_shift_list = report.volunteer_shifts.all() report_list = generate_report(volunteer_shift_list) volunteer = report.volunteer post_pdf = render_to_pdf( 'administrator/pdf.html', { 'report': report, 'admin': admin, 'report_list': report_list, }, ) message = render_to_string( 'administrator/confirm_report.html', { 'volunteer': volunteer, 'admin': admin, } ) msg = EmailMessage( "Report Approved", message, "*****@*****.**", [report.volunteer.email] ) msg.attach('file.pdf', post_pdf, 'application/pdf') msg.send() return HttpResponseRedirect('/administrator/report')
def enviarmail(subject,mails,attachments,template_name,name_db): manageParameters = ManageParameters(name_db) email = "*****@*****.**" # email = manageParameters.get_param_value('from_email') mensaje = EmailMessage(subject=subject, from_email=email, to=mails) for attachment in attachments: filename = attachment fp = open(filename,'rb') adjunto = MIMEBase('multipart', 'encrypted') #lo insertamos en una variable adjunto.set_payload(fp.read()) fp.close() #lo encriptamos en base64 para enviarlo encoders.encode_base64(adjunto) #agregamos una cabecera y le damos un nombre al archivo que adjuntamos puede ser el mismo u otro adjunto.add_header('Content-Disposition', 'attachment', filename=os.path.basename(filename)) #adjuntamos al mensaje mensaje.attach(adjunto) mensaje.template_name=template_name mensaje.send()
def send_assortment_reports(emails=(), **filter): refresh_mat_views() msg = 'Competitor Assortment Dashboard - http://scraper.exclusively.net/analytics/assortment/' message = EmailMessage(subject='ASSORTMENT REPORTS', body=msg, from_email=EMAIL_HOST_USER, to=emails) sub_cat_assortment = DiscountAssortment(**filter) sub_cat_filename, sub_cat_csv = sub_cat_assortment.create_csv() brand_assortment = DiscountAssortment(level='brand', **filter) brand_filename, brand_csv = brand_assortment.create_csv() competitor_assortment = DiscountAssortment(level='competitor', **filter) competitor_filename, competitor_csv = competitor_assortment.create_csv() message.attach(sub_cat_filename, sub_cat_csv.getvalue(), 'text/csv') message.attach(brand_filename, brand_csv.getvalue(), 'text/csv') message.attach(competitor_filename, competitor_csv.getvalue(), 'text/csv') print message.send()
def paypal_ipn(request): # send back the response to paypal data = dict(request.POST.items()) args = {'cmd': '_notify-validate'} args.update(data) params = urllib.urlencode(args) paypal_response = urllib2.urlopen(settings.PAYPAL_URL + '/cgi-bin/webscr', params).read() # process the payment receiver_id = data['receiver_id'] transaction_id = data['txn_id'] payment_status = data['payment_status'] payment_amount = data['mc_gross'] payment_currency = data['mc_currency'] fee = data['mc_fee'] item_name = data['item_name'] user_id = data['custom'] user = get_object_or_404(User, pk=user_id) profile = user.get_profile() last_subscription = profile.get_last_subscription() subscription, created = Subscription.objects.get_or_create(transaction_id=transaction_id, defaults={'owner': user, 'state': SUBSCRIPTION_STATE_NOT_PAID, 'expiration_date': profile.get_next_expiration_date(), 'transaction_id': transaction_id, 'error_message': ugettext('Not verified')}) if paypal_response == 'VERIFIED': if receiver_id <> settings.PAYPAL_RECEIVER_ID: subscription.error_message = ugettext('Receiver is not as defined in settings. Spoofing ?') elif payment_status <> 'Completed': subscription.error_message = ugettext('Payment not completed') elif payment_amount <> settings.PAYPAL_APP_SUBSCRIPTION_AMOUNT: subscription.error_message = ugettext('Amount altered. Bad guy ?') elif payment_currency <> settings.PAYPAL_APP_SUBSCRIPTION_CURRENCY: subscription.error_message = ugettext('Amount altered. Bad guy ?') else: subscription.error_message = ugettext('Paid') subscription.state = SUBSCRIPTION_STATE_PAID # create an invoice for this payment # first, get the provider user provider = User.objects.get(email=settings.SERVICE_PROVIDER_EMAIL) # look for a customer corresponding to user address, created = Address.objects.get_or_create(contact__email=user.email, owner=provider, defaults={'street': profile.address.street, 'zipcode': profile.address.zipcode, 'city': profile.address.city, 'country': profile.address.country, 'owner': provider}) customer, created = Contact.objects.get_or_create(email=user.email, defaults={'contact_type': CONTACT_TYPE_COMPANY, 'name': '%s %s' % (user.first_name, user.last_name), 'company_id': profile.company_id, 'legal_form': 'Auto-entrepreneur', 'email': user.email, 'address': address, 'owner': provider}) # create a related project if needed # set it to finished to clear daily business project, created = Project.objects.get_or_create(state=PROJECT_STATE_FINISHED, customer=customer, name='Subscription %s - %s %s' % (Site.objects.get_current().name, user.first_name, user.last_name), defaults={'state': PROJECT_STATE_FINISHED, 'customer': customer, 'name': 'Subscription %s - %s %s' % (Site.objects.get_current().name, user.first_name, user.last_name), 'owner': provider}) # create proposal for this subscription begin_date = datetime.date.today() if begin_date < last_subscription.expiration_date: begin_date = last_subscription.expiration_date proposal = Proposal.objects.create(project=project, reference='subscription-%i%i%i' % (subscription.expiration_date.year, subscription.expiration_date.month, subscription.expiration_date.day), state=PROPOSAL_STATE_BALANCED, begin_date=begin_date, end_date=subscription.expiration_date, contract_content='', update_date=datetime.date.today(), expiration_date=None, owner=provider) proposal_row = ProposalRow.objects.create(proposal=proposal, label=item_name, category=ROW_CATEGORY_SERVICE, quantity=1, unit_price='%s' % settings.PAYPAL_APP_SUBSCRIPTION_AMOUNT, owner=provider) # finally create invoice invoice = Invoice.objects.create(customer=customer, invoice_id=Invoice.objects.get_next_invoice_id(provider), state=INVOICE_STATE_PAID, amount=payment_amount, edition_date=datetime.date.today(), payment_date=datetime.date.today(), paid_date=datetime.date.today(), payment_type=PAYMENT_TYPE_BANK_CARD, execution_begin_date=begin_date, execution_end_date=subscription.expiration_date, penalty_date=None, penalty_rate=None, discount_conditions=None, owner=provider) invoice_row = InvoiceRow.objects.create(proposal=proposal, invoice=invoice, label=item_name, category=ROW_CATEGORY_SERVICE, quantity=1, unit_price=payment_amount, balance_payments=True, owner=provider) # create expense for paypal fee expense = Expense.objects.create(date=datetime.date.today(), reference=transaction_id, supplier='Paypal', amount=fee, payment_type=PAYMENT_TYPE_BANK_CARD, description='Commission paypal', owner=provider) # generate invoice in pdf response = HttpResponse(mimetype='application/pdf') invoice.to_pdf(provider, response) subject_template = loader.get_template('core/subscription_paid_email_subject.html') subject_context = {'site_name': Site.objects.get_current().name} subject = subject_template.render(Context(subject_context)) body_template = loader.get_template('core/subscription_paid_email.html') body_context = {'site_name': Site.objects.get_current().name, 'expiration_date': subscription.expiration_date} body = body_template.render(Context(body_context)) email = EmailMessage(subject=subject, body=body, to=[user.email]) email.attach('facture_%i.pdf' % (invoice.invoice_id), response.content, 'application/pdf') email.send(fail_silently=(not settings.DEBUG)) subscription.save() return render_to_response('core/paypal_ipn.html', {'active': 'account', 'title': _('Subscribe')}, context_instance=RequestContext(request))
def post(self, req, *args, **kwargs): report = dict([(key, req.POST.get(key, '')) for key in ( 'subject', 'username', 'domain', 'url', 'message', 'app_id', 'cc', 'email', '500traceback', 'sentry_id', )]) try: couch_user = req.couch_user full_name = couch_user.full_name if couch_user.is_commcare_user(): email = report['email'] else: email = couch_user.get_email() except Exception: full_name = None email = report['email'] report['full_name'] = full_name report['email'] = email or report['username'] if report['domain']: domain = report['domain'] elif len(couch_user.domains) == 1: # This isn't a domain page, but the user has only one domain, so let's use that domain = couch_user.domains[0] else: domain = "<no domain>" message = ( "username: {username}\n" "full name: {full_name}\n" "domain: {domain}\n" "url: {url}\n" ).format(**report) domain_object = Domain.get_by_name(domain) if report['domain'] else None debug_context = { 'datetime': datetime.utcnow(), 'self_started': '<unknown>', 'scale_backend': '<unknown>', 'has_handoff_info': '<unknown>', 'project_description': '<unknown>', 'sentry_error': '{}{}'.format(getattr(settings, 'SENTRY_QUERY_URL'), report['sentry_id']) } if domain_object: current_project_description = domain_object.project_description if domain_object else None new_project_description = req.POST.get('project_description') if (domain_object and req.couch_user.is_domain_admin(domain=domain) and new_project_description and current_project_description != new_project_description): domain_object.project_description = new_project_description domain_object.save() message += (( "software plan: {software_plan}\n" ).format( software_plan=Subscription.get_subscribed_plan_by_domain(domain), )) debug_context.update({ 'self_started': domain_object.internal.self_started, 'scale_backend': should_use_sql_backend(domain), 'has_handoff_info': bool(domain_object.internal.partner_contact), 'project_description': domain_object.project_description, }) subject = '{subject} ({domain})'.format(subject=report['subject'], domain=domain) cc = [el for el in report['cc'].strip().split(",") if el] if full_name and not any([c in full_name for c in '<>"']): reply_to = '"{full_name}" <{email}>'.format(**report) else: reply_to = report['email'] # if the person looks like a commcare user, fogbugz can't reply # to their email, so just use the default if settings.HQ_ACCOUNT_ROOT in reply_to: reply_to = settings.SERVER_EMAIL message += "Message:\n\n{message}\n".format(message=report['message']) if req.POST.get('five-hundred-report'): extra_message = ("This message was reported from a 500 error page! " "Please fix this ASAP (as if you wouldn't anyway)...") extra_debug_info = ( "datetime: {datetime}\n" "Is self start: {self_started}\n" "Is scale backend: {scale_backend}\n" "Has Support Hand-off Info: {has_handoff_info}\n" "Project description: {project_description}\n" "Sentry Error: {sentry_error}\n" ).format(**debug_context) traceback_info = cache.cache.get(report['500traceback']) or 'No traceback info available' cache.cache.delete(report['500traceback']) message = "\n\n".join([message, extra_debug_info, extra_message, traceback_info]) email = EmailMessage( subject=subject, body=message, to=self.recipients, headers={'Reply-To': reply_to}, cc=cc ) uploaded_file = req.FILES.get('report_issue') if uploaded_file: filename = uploaded_file.name content = uploaded_file.read() email.attach(filename=filename, content=content) # only fake the from email if it's an @dimagi.com account is_icds_env = settings.SERVER_ENVIRONMENT in settings.ICDS_ENVS if re.search(r'@dimagi\.com$', report['username']) and not is_icds_env: email.from_email = report['username'] else: email.from_email = settings.CCHQ_BUG_REPORT_EMAIL email.send(fail_silently=False) if req.POST.get('five-hundred-report'): messages.success( req, "Your CommCare HQ Issue Report has been sent. We are working quickly to resolve this problem." ) return HttpResponseRedirect(reverse('homepage')) return HttpResponse()
def bug_report(req): report = dict([(key, req.POST.get(key, '')) for key in ( 'subject', 'username', 'domain', 'url', 'message', 'app_id', 'cc' )]) report['user_agent'] = req.META['HTTP_USER_AGENT'] report['datetime'] = datetime.utcnow() if report['app_id']: app = import_app(report['app_id'], BUG_REPORTS_DOMAIN) report['copy_url'] = "%s%s" % (get_url_base(), reverse('view_app', args=[BUG_REPORTS_DOMAIN, app.id])) else: report['copy_url'] = None try: couch_user = CouchUser.get_by_username(report['username']) full_name = couch_user.full_name email = couch_user.get_email() except Exception: full_name = None email = None report['full_name'] = full_name report['email'] = email or report['username'] matching_subscriptions = Subscription.objects.filter( is_active=True, subscriber__domain=report['domain'], ) if len(matching_subscriptions) >= 1: report['software_plan'] = matching_subscriptions[0].plan_version else: report['software_plan'] = u'domain has no active subscription' subject = u'{subject} ({domain})'.format(**report) message = ( u"username: {username}\n" u"full name: {full_name}\n" u"domain: {domain}\n" u"software plan: {software_plan}\n" u"url: {url}\n" u"copy url: {copy_url}\n" u"datetime: {datetime}\n" u"User Agent: {user_agent}\n" u"Message:\n\n" u"{message}\n" ).format(**report) cc = report['cc'].strip().split(",") cc = filter(None, cc) if full_name and not any([c in full_name for c in '<>"']): reply_to = u'"{full_name}" <{email}>'.format(**report) else: reply_to = report['email'] # if the person looks like a commcare user, fogbugz can't reply # to their email, so just use the default if settings.HQ_ACCOUNT_ROOT in reply_to: reply_to = settings.SERVER_EMAIL if req.POST.get('five-hundred-report'): message = "%s \n\n This messge was reported from a 500 error page! Please fix this ASAP (as if you wouldn't anyway)..." % message email = EmailMessage( subject=subject, body=message, to=settings.BUG_REPORT_RECIPIENTS, headers={'Reply-To': reply_to}, cc=cc ) uploaded_file = req.FILES.get('report_issue') if uploaded_file: filename = uploaded_file.name content = uploaded_file.read() email.attach(filename=filename, content=content) # only fake the from email if it's an @dimagi.com account if re.search('@dimagi\.com$', report['username']): email.from_email = report['username'] else: email.from_email = settings.CCHQ_BUG_REPORT_EMAIL email.send(fail_silently=False) if req.POST.get('five-hundred-report'): messages.success(req, "Your CommCare HQ Issue Report has been sent. We are working quickly to resolve this problem.") return HttpResponseRedirect(reverse('homepage')) return HttpResponse()
def send(self, fail_silently=False, **kwargs): recipient_list = [] recipient_bcc_list = [] headers = kwargs.get('headers', {}) attachments = kwargs.get('attachments', []) if isinstance(self.recipient, str): recipient_list = self.recipient.split(',') recipient_list = [recipient.strip() for recipient in recipient_list if recipient.strip() != ''] else: recipient_list = list(self.recipient) if isinstance(self.recipient_cc, str): recipient_cc_list = self.recipient_cc.split(',') recipient_cc_list = [recipient_cc.strip() for recipient_cc in recipient_cc_list if recipient_cc.strip() != ''] recipient_list += recipient_cc_list else: recipient_list += list(self.recipient_cc) if isinstance(self.recipient_bcc, str): recipient_bcc_list = self.recipient_bcc.split(',') recipient_bcc_list = [recipient_bcc.strip() for recipient_bcc in recipient_bcc_list if recipient_bcc.strip() != ''] else: recipient_bcc_list = list(self.recipient_bcc) if self.reply_to: headers['Reply-To'] = self.reply_to if not self.sender: self.sender = get_setting('site', 'global', 'siteemailnoreplyaddress') or settings.DEFAULT_FROM_EMAIL if self.sender_display: # Add quotes around display name to prevent errors on sending # When display name contains comma or other control characters, headers['From'] = '"%s" <%s>' % (self.sender_display, self.sender) if self.priority and self.priority == 1: headers['X-Priority'] = '1' headers['X-MSMail-Priority'] = 'High' # remove blocked from recipient_list and recipient_bcc_list temp_recipient_list = copy.copy(recipient_list) for e in temp_recipient_list: if self.is_blocked(e) or not is_valid_domain(e): recipient_list.remove(e) temp_recipient_bcc_list = copy.copy(recipient_bcc_list) for e in temp_recipient_bcc_list: if self.is_blocked(e) or not is_valid_domain(e): recipient_bcc_list.remove(e) if recipient_list or recipient_bcc_list: msg = EmailMessage(self.subject, add_tendenci_footer(self.body), self.sender, recipient_list, recipient_bcc_list, headers=headers, connection=kwargs.get('connection', None)) if self.content_type == 'html' or self.content_type == self.CONTENT_TYPE_HTML: msg.content_subtype = 'html' if attachments: for name, value in attachments: msg.attach(name, value) msg.send(fail_silently=fail_silently)