def helper_request(request, id=None): print request.user opportunity = get_object_or_404(Create_opportunity, id = id) if not RequestApplication.objects.filter(requests=opportunity).exists(): form = ApplyForm(data = request.POST or None) if form.is_valid(): instance = form.save(commit=False) instance.user = request.user instance.requests = opportunity print "Obj not exist" instance.save() message_body = "This is an notification for a job involving:\n" + opportunity.description +\ "\nThe job requires the following skills: " + ", ".join([skill['skill'] for skill in opportunity.skills.values('skill')]) subject, from_email, to = opportunity.title, '*****@*****.**', [request.user.email] calendar = ical( opportunity.starting_date, opportunity.stopping_date, opportunity.title, "https://sccial-ckiilu.c9users.io/" + str(opportunity.get_absolute_url()) ) print (calendar) html_content = Template(""" <p>This is an notification for a job involving:</p> <div style="margin-left:55px;">{{ opportunity.description }}</div> <p>The job requires the following skills:</p> <ul style="list-style-type:none;"> {% for skill in opportunity.skills.all %} <li>{{ skill }}</li> {% endfor %} </ul> """).render(RequestContext(request, {'opportunity': opportunity})) msg = EmailMultiAlternatives(subject, message_body, from_email, to) msg.attach_alternative(html_content, "text/html") try: msg.attach(calendar) except AssertionError: print("Whaaat! AssertionError!") msg.send() else: form = ApplyForm() print "Obj not exist, form invalid" else: form = ApplyForm(data = request.POST or None, instance=opportunity) current_request = RequestApplication.objects.get(requests=opportunity).application if form.is_valid(): instance = form.save(commit=False) instance.save() print "Obj exists" else: form = ApplyForm() print "Obj exists, form invalid" RequestApplication.objects.get(requests=opportunity).delete() print opportunity.title context = { 'opportunity':opportunity, 'form': form, } return render(request, 'profiles/browseOpportunity.html', context)
def send_opml_export_email(self): if not self.user.email: return MSentEmail.objects.get_or_create(receiver_user_id=self.user.pk, email_type='opml_export') exporter = OPMLExporter(self.user) opml = exporter.process() params = { 'feed_count': UserSubscription.objects.filter(user=self.user).count(), } user = self.user text = render_to_string('mail/email_opml_export.txt', params) html = render_to_string('mail/email_opml_export.xhtml', params) subject = "Backup OPML file of your NewsBlur sites" filename= 'NewsBlur Subscriptions - %s.xml' % datetime.datetime.now().strftime('%Y-%m-%d') msg = EmailMultiAlternatives(subject, text, from_email='NewsBlur <%s>' % settings.HELLO_EMAIL, to=['%s <%s>' % (user, user.email)]) msg.attach_alternative(html, "text/html") msg.attach(filename, opml, 'text/xml') msg.send(fail_silently=True) logging.user(self.user, "~BB~FM~SBSending OPML backup email to: %s" % self.user.email)
def send_email_extended(title, to_list=[], cc_list=[], bcc_list=[], email_words_dict={}, request='', attachment=''): try: template_obj = Emailtemplates.objects.get(title=title) if template_obj.is_active: if not to_list: to_list = str(template_obj.to_list).split(',') if not cc_list: cc_list = str(template_obj.cc_list).split(',') if not bcc_list: bcc_list = str(template_obj.bcc_list).split(',') body = str(template_obj.description) from_email = extractTLDfromHost(str(template_obj.from_email), '[DOMAIN]', 'email_sender', request) subject = template_obj.subject subject = evariableReplace(subject, email_words_dict) email_text = evariableReplace(body, email_words_dict) # from_email = '*****@*****.**' msg = EmailMultiAlternatives(subject, email_text, from_email, to=to_list,cc=cc_list, bcc=bcc_list) if attachment: msg.attach(attachment['title'], attachment['file'] , attachment['type']) msg.content_subtype = "html" msg.send() if email_words_dict: template_obj.placeholders = '\n'.join([k for k in email_words_dict.keys()]) template_obj.save() except Exception,ex: print traceback.print_exc(5) print str(ex)
def email_project(request, slug): project = get_object_or_404(Project, slug=slug) funding_program = FundingProgram.objects.get(id=project.funding_program_id) lpms = AssignedEmployee.objects.filter(project_id=project.id, role='Project manager').values('employee_id') project_managers = Employee.objects.filter(id__in=lpms).order_by('name', 'first_surname', 'second_surname') lprs = AssignedEmployee.objects.filter(project_id=project.id, role='Principal researcher').values('employee_id') principal_researchers = Employee.objects.filter(id__in=lprs).order_by('name', 'first_surname', 'second_surname') project_leader = Organization.objects.get(id=project.project_leader_id) consortium_members = [] for consortium_member in ConsortiumMember.objects.all().filter(project_id=project.id): org = Organization.objects.get(id=consortium_member.organization.id) consortium_members.append(org.name) html_content = render_to_string('projects/project_email_template.html', { 'project': project, 'funding_program': funding_program, 'project_managers': project_managers, 'principal_researchers': principal_researchers, 'project_leader': project_leader, 'consortium_members': consortium_members, }) text_content = strip_tags(html_content) msg = EmailMultiAlternatives( '[NEW PROJECT]: ' + project.title, # subject text_content, # message settings.PROJECTS_SENDER_EMAIL, # from settings.PROJECTS_RECEPTOR_EMAILS, # to ) try: image_file = open(project.logo.path, 'rb') msg_image = MIMEImage(image_file.read()) image_file.close() msg_image.add_header('Content-ID', '<image>', filename=project.logo.path) msg.attach(msg_image) except: pass try: image_file = open(funding_program.logo.path, 'rb') msg_image = MIMEImage(image_file.read()) image_file.close() msg_image.add_header('Content-ID', '<image>', filename = funding_program.logo.path) msg.attach(msg_image) except: pass msg.attach_alternative(html_content, "text/html") msg.send() return HttpResponseRedirect(reverse('project_index'))
def send_notification_email(self): if getattr(settings, 'SEND_EMAIL_NOTIFICATIONS', False): from_email = self.get_from_email() headers = self.get_email_headers() recipients = self.get_recipients_list() cc_recipients = self.get_cc_recipients_list() subject = self.get_email_subject().strip() plaintext_body = self.get_email_plaintext_body() msg = EmailMultiAlternatives(subject, plaintext_body, from_email, recipients, headers=headers, cc=cc_recipients) html_body = self.get_email_html_body() if html_body: msg.attach_alternative(html_body, 'text/html') attachment_files = self.get_attachment_files() for att in attachment_files: msg.attach(att.name, att.read()) try: msg.send() except Exception as exc: # Store error msg smtp_code = getattr(exc, 'smtp_code', '') smtp_error = getattr(exc, 'smtp_error', '') error_msg = getattr(exc, 'message', '') self.delivery_response = "Exception: %s\nSMTP code: %s\nSMTP error: %s\nMessage: %s" % (repr(exc), smtp_code, smtp_error, error_msg) self.save() # Not failing silently is default behaviour if not getattr(settings, 'NOTI_FAIL_SILENTLY', False): raise else: self.email_sent = True self.save()
def send_html_mail(subject, message, message_html, from_email, recipient_list, priority="medium", fail_silently=False, auth_user=None, auth_password=None, attach_files=[]): """ Function to queue HTML e-mails """ from django.utils.encoding import force_unicode from django.core.mail import EmailMultiAlternatives from mailer.models import make_message 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 = EmailMultiAlternatives(email.subject, email.body, email.from_email, email.to) email.attach_alternative(message_html, "text/html") for f in attach_files: if isinstance(f, (str, unicode)): 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(self): ''' Returns True/False ''' try: s = loader.get_template(self.subject) t = loader.get_template(self.template) except Exception as e: print e headers = {} if self.reply_to: headers.update({'Reply-To': self.reply_to}) self.context['settings'] = settings subject = s.render(Context(self.context)) content = t.render(Context(self.context)) msg = EmailMultiAlternatives(subject, content, self.from_email, self.to, self.bcc, headers=headers) msg.attach_alternative(content, getattr(settings, 'EMAIL_MIMETYPE', 'text/plain')) if self.attachments[0]: for file_doc in self.attachments: file_name = file_doc.name msg.attach(file_name.split('/')[-1], file_doc.read(), 'application/pdf') try: msg.send(fail_silently=False) except Exception, e: print 'Exception: ', e return False
def email_message(self, connection=None): subject = smart_text(self.subject) if self.template is not None: render_language = self.context.get('render_language', settings.LANGUAGE_CODE) context = Context(self.context) with translation_override(render_language): subject = Template(self.template.subject).render(context) message = Template(self.template.content).render(context) html_message = Template(self.template.html_content).render(context) else: subject = self.subject message = self.message html_message = self.html_message if html_message: if not message: message = BeautifulSoup(html_message).text mailmsg = EmailMultiAlternatives( subject=subject, body=message, from_email=self.from_email, to=self.to, bcc=self.bcc, cc=self.cc, connection=connection, headers=self.headers) mailmsg.attach_alternative(html_message, 'text/html') else: mailmsg = EmailMessage( subject=subject, body=message, from_email=self.from_email, to=self.to, bcc=self.bcc, cc=self.cc, connection=connection, headers=self.headers) for attachment in self.attachments.all(): mailmsg.attach(attachment.name, attachment.file.read()) return mailmsg
def send_pdf(request, report_id): to_return = { "status": "success", "message": "", "logMessages": [], } user = get_current_user() recipients = request.POST.get('to') comments = request.POST.get('comments', '') # Only set privacy as private if user is auth and privacy POST param is private if request.fmsuser.is_pro() and "private" == request.POST.get('privacy'): pro_version = True else: pro_version = False report = get_object_or_404(Report, id=report_id) #generate the pdf pdffile = generate_pdf("reports/pdf.html", { 'report': report, 'files': report.files() if pro_version else report.active_files(), 'comments': report.comments() if pro_version else report.active_comments(), 'activity_list': report.activities.all(), 'privacy': 'private' if pro_version else 'public', 'BACKOFFICE': pro_version, 'base_url': getattr(settings, 'RENDER_PDF_BASE_URL', None), }, context_instance=RequestContext(request)) subject, html, text = transform_notification_template("mail-pdf", report, user, comment=comments) recepients = re.compile("[\\s,;]+").split(recipients) for recepient in recepients: recepient = recepient.strip() if not recepient: continue try: validate_email(recepient) except ValidationError: to_return["status"] = "error" to_return["logMessages"].append(_("'{email}' is not a valid email address.").format(email=recepient)) continue msg = EmailMultiAlternatives(subject, text, settings.DEFAULT_FROM_EMAIL, (recepient,)) if html: msg.attach_alternative(html, "text/html") #reset the seek to 0 to be able to read multiple times the same file pdffile.seek(0) name = "export-incident-%s-date-%s.pdf" % (report.id, datetime.date.today().isoformat()) msg.attach(name, pdffile.read(), 'application/pdf') msg.send() to_return["logMessages"].append(_("Successfully sent to '{email}'.").format(email=recepient)) if to_return["status"] == "success": to_return["message"] = _("PDF sent by email.") else: to_return["message"] = _("There were errors.") return JsonHttpResponse(to_return)
def email_message(self, connection=None): """ Returns a django ``EmailMessage`` or ``EmailMultiAlternatives`` object from a ``Message`` instance, depending on whether html_message is empty. """ subject = smart_text(self.subject) # msg = EmailMultiAlternatives(subject, self.message, self.from_email, # [self.to], connection=connection, # headers=self.headers) msg = EmailMultiAlternatives(subject, self.message, self.from_email, [self.to], connection=connection, headers=self.headers) if self.html_message: msg.attach_alternative(self.html_message, "text/html") for attachment in self.attachments.all(): msg.attach(attachment.name, attachment.file.read()) # msg = EmailMultiAlternatives(subject, self.message, self.from_email, # [self.to], connection=connection, # headers=self.headers) msg = SendGridEmailMultiAlternatives(subject, self.message, self.from_email, [self.to], connection=connection, headers=self.headers) if self.html_message: msg.attach_alternative(self.html_message, "text/html") if len(self.category) > 0: msg.sendgrid_headers.setCategory(self.category) msg.sendgrid_headers.setUniqueArgs() return msg
def test_mime(self): msg = EmailMultiAlternatives( subject="Hello, World!", body=" ", from_email="Sam Smith <*****@*****.**>", to=["John Doe <*****@*****.**>", "*****@*****.**"], ) content = '<body><img src="cid:linux_penguin" /></body>' msg.attach_alternative(content, "text/html") with open("test/linux-penguin.png", "rb") as f: img = MIMEImage(f.read()) img.add_header("Content-ID", "<linux_penguin>") msg.attach(img) result = self.backend._build_sg_mail(msg) self.assertEqual(len(result["content"]), 2) self.assertDictEqual(result["content"][0], {"type": "text/plain", "value": " "}) self.assertDictEqual(result["content"][1], {"type": "text/html", "value": content}) self.assertEqual(len(result["attachments"]), 1) self.assertEqual(result["attachments"][0]["content_id"], "linux_penguin") with open("test/linux-penguin.png", "rb") as f: if sys.version_info >= (3.0, 0.0, ): self.assertEqual(bytearray(result["attachments"][0]["content"], "utf-8"), base64.b64encode(f.read())) else: self.assertEqual(result["attachments"][0]["content"], base64.b64encode(f.read())) self.assertEqual(result["attachments"][0]["type"], "image/png")
def send_mail(mail): """Send a Mail instance. Note that this does not alter the mail instance. It is the responsibility of the caller to set `status` to Mail.STATUS_SENT and `sent_on` to the current datetime. Return the `EmailMultiAlternatives` instance of the sent mail. """ subject = mail.subject html_body = mail.html_body text_body = mail.text_body or html_to_text(html_body) headers = mail.get_headers() from_email = headers.pop('From', settings.DEFAULT_FROM_EMAIL) to_emails = filter(None, map( str.strip, headers.pop('To', '').split(','))) cc_emails = filter(None, map( str.strip, headers.pop('Cc', '').split(','))) bcc_emails = filter(None, map( str.strip, headers.pop('Bcc', '').split(','))) msg = EmailMultiAlternatives(subject, text_body, from_email, to_emails, cc=cc_emails, bcc=bcc_emails, headers=headers) msg.attach_alternative(html_body, 'text/html') for attachment in mail.get_attachments(): msg.attach(attachment.filename, attachment.get_file_content(), attachment.mime_type) msg.send() return msg
def form_valid(self, form): user = UserProfile.objects.get(user=request.user) product = Product.objects.get(id=request.GET.get('product_id')) try: margin = user.margin except: margin = 30.0 price_increased = (product.price * margin) / 100.00 price = product.price + price_increased to_email = [form.cleaned_data['Customer_email']] subject = '%s - %s' % (product.model, product.manufacturer) text_content = render_to_string('saas_app/email/product_info_email.txt') html_content = render_to_string('saas_app/email/product_info_email.html', {'text_content':text_content, 'price':price, 'product':product}) msg = EmailMultiAlternatives(subject, text_content, [user.email], to_email) msg.attach_alternative(html_content, 'text/html') msg.mixed_subtype = 'related' img_content_id = 'product' img_data = open(product.image_url(), 'rb') msg_img = MIMEImage(img_data.read()) img_data.close() msg_img.add_header('Content-ID', '<{}>'.format(product.picture)) msg.attach(msg_img) msg.send()
def sendEmail(subject,content,from_address,from_name='',to=[],cc=[],bcc=[],attachment_name='attachment',attachment=None,html_content=None): # Ensure that email address information is in list form and that there are no empty values recipients = [x for x in to + cc if x] bcc = [x for x in bcc if x] from_email = from_name + ' <' + from_address + '>' if from_address else None reply_to = [from_address,] if from_address else None logger.info('Sending email from %s to %s' % (from_address,recipients)) if getattr(settings,'DEBUG',None): logger.info('Email content:\n\n%s' % content) logger.info('Email HTML content:\n\n%s' % html_content) with get_connection() as connection: connection.open() message = EmailMultiAlternatives( subject=subject, body=content, from_email=from_email, to=recipients, bcc=bcc, reply_to=reply_to, connection=connection, ) if html_content: message.attach_alternative(html_content, "text/html") if attachment: message.attach(attachment_name, attachment) message.send(fail_silently=False) connection.close()
def email_admin(self, subject, text, sorted_self): styleSheet = getSampleStyleSheet() # Send the admin a PDF of client details response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="clientDetails.pdf"' string_buffer = StringIO() new_pdf = [] header = Paragraph("DISS Attendee Details", styleSheet['Heading1']) new_pdf.append(header) for element in sorted_self: new_pdf.append(Paragraph(element[0], styleSheet['Heading3'])) new_pdf.append(Paragraph(element[1], styleSheet['BodyText'])) new_pdf.append(Spacer(1, 2)) doc = SimpleDocTemplate(string_buffer) doc.build(new_pdf) pdf = string_buffer.getvalue() string_buffer.close() msg = EmailMultiAlternatives(subject, text, "*****@*****.**", ["*****@*****.**"]) msg.attach(self.first_name + self.last_name + "DISS.pdf", pdf, "application/pdf") msg.send()
def email_message(self, connection=None): """ Returns a django ``EmailMessage`` or ``EmailMultiAlternatives`` object, depending on whether html_message is empty. """ subject = smart_text(self.subject) if self.template is not None: _context = Context(self.context) subject = Template(self.template.subject).render(_context) message = Template(self.template.content).render(_context) html_message = Template(self.template.html_content).render(_context) else: subject = self.subject message = self.message html_message = self.html_message if html_message: msg = EmailMultiAlternatives( subject=subject, body=message, from_email=self.from_email, to=self.to, bcc=self.bcc, cc=self.cc, connection=connection, headers=self.headers) msg.attach_alternative(html_message, "text/html") else: msg = EmailMessage( subject=subject, body=message, from_email=self.from_email, to=self.to, bcc=self.bcc, cc=self.cc, connection=connection, headers=self.headers) for attachment in self.attachments.all(): msg.attach(attachment.name, attachment.file.read()) return msg
def email_submission(self, form_data, request, referrer): mail_to = re.compile('\s*[,;]+\s*').split(self.form_definition.email_to) mail_from = self.form_definition.email_from or None mail_subject = self.form_definition.email_subject or \ 'Form Submission - %s' % self.form_definition.name context = { 'form': self.form_definition, 'referrer': referrer, 'title': mail_subject, 'form_data': form_data, 'request': request, 'recipients': mail_to, } message = render_to_string('djangocms_forms/email_template/email.txt', context) message_html = render_to_string('djangocms_forms/email_template/email.html', context) email = EmailMultiAlternatives(mail_subject, message, mail_from, mail_to) email.attach_alternative(message_html, 'text/html') if self.form_definition.email_uploaded_files: for field, filedata in self.files.items(): filedata.open('r') content = filedata.read() filedata.close() email.attach(filedata.name, content, filedata.content_type) email.send(fail_silently=False)
def send_opml_export_email(self, reason=None, force=False): if not self.user.email: return emails_sent = MSentEmail.objects.filter(receiver_user_id=self.user.pk, email_type='opml_export') day_ago = datetime.datetime.now() - datetime.timedelta(days=1) for email in emails_sent: if email.date_sent > day_ago and not force: logging.user(self.user, "~SN~FMNot sending opml export email, already sent today.") return MSentEmail.record(receiver_user_id=self.user.pk, email_type='opml_export') exporter = OPMLExporter(self.user) opml = exporter.process() params = { 'feed_count': UserSubscription.objects.filter(user=self.user).count(), 'reason': reason, } user = self.user text = render_to_string('mail/email_opml_export.txt', params) html = render_to_string('mail/email_opml_export.xhtml', params) subject = "Backup OPML file of your NewsBlur sites" filename= 'NewsBlur Subscriptions - %s.xml' % datetime.datetime.now().strftime('%Y-%m-%d') msg = EmailMultiAlternatives(subject, text, from_email='NewsBlur <%s>' % settings.HELLO_EMAIL, to=['%s <%s>' % (user, user.email)]) msg.attach_alternative(html, "text/html") msg.attach(filename, opml, 'text/xml') msg.send(fail_silently=True) logging.user(self.user, "~BB~FM~SBSending OPML backup email to: %s" % self.user.email)
def email_admin(self, subject, text, sorted_self): site_name = SiteSetting.objects.all().first().site_name styleSheet = getSampleStyleSheet() # Send the admin a PDF of client details response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="clientDetails.pdf"' string_buffer = StringIO() new_pdf = [] header = Paragraph(site_name + " Attendee Details", styleSheet['Heading1']) new_pdf.append(header) for element in sorted_self: new_pdf.append(Paragraph(element[0], styleSheet['Heading3'])) new_pdf.append(Paragraph(element[1], styleSheet['BodyText'])) new_pdf.append(Spacer(1, 2)) doc = SimpleDocTemplate(string_buffer) doc.build(new_pdf) pdf = string_buffer.getvalue() string_buffer.close() msg = EmailMultiAlternatives(subject, text, EMAIL_HOST_USER, [EMAIL_HOST_USER]) msg.attach(self.first_name + self.last_name + site_name + ".pdf", pdf, "application/pdf") msg.send(fail_silently=True)
def send(self, to_addresses, context={}, attachments=None, headers=None): html_body = self.render(context) text_body = self.render_txt(context) or striptags(html_body) subject = self._render_from_string(self.subject, context) if isinstance(to_addresses, (str,unicode)): to_addresses = (to_addresses,) whitelisted_email_addresses = getattr(settings, 'EMAILTEMPLATES_DEBUG_WHITELIST', []) if getattr(settings, 'EMAILTEMPLATES_DEBUG', False): # clean non-whitelisted emails from the to_address cleaned_to_addresses = [] for address in to_addresses: try: email_domain = address.split('@')[1] except IndexError: email_domain = None if email_domain in whitelisted_email_addresses or address in whitelisted_email_addresses: cleaned_to_addresses.append(address) to_addresses = cleaned_to_addresses msg = EmailMultiAlternatives(subject, text_body, self.visible_from_address(), to_addresses, headers=headers) msg.attach_alternative(html_body, "text/html") if attachments is not None: for attach in attachments: msg.attach(*attach) return msg.send()
def send_mail_template(subject, template, addr_from, addr_to, context=None, attachments=None, fail_silently=False, addr_bcc=None, headers=None): """ Send email rendering text and html versions for the specified template name using the context dictionary passed in. """ if context is None: context = {} if attachments is None: attachments = [] # Add template accessible settings from Mezzanine to the context # (normally added by a context processor for HTTP requests) context.update(context_settings()) # Allow for a single address to be passed in. if not hasattr(addr_to, "__iter__"): addr_to = [addr_to] if addr_bcc is not None and not hasattr(addr_bcc, "__iter__"): addr_bcc = [addr_bcc] # Loads a template passing in vars as context. render = lambda type: loader.get_template("%s.%s" % (template, type)).render(Context(context)) # Create and send email. msg = EmailMultiAlternatives(subject, render("txt"), addr_from, addr_to, addr_bcc, headers=headers) try: template = loader.get_template('%s.html' % template).render(Context(context)) msg.attach_alternative(template, 'text/html') except: pass for attachment in attachments: msg.attach(*attachment) msg.send(fail_silently=fail_silently)
def send_mail_template(subject, template, addr_from, addr_to, context=None, attachments=None, fail_silently=None, addr_bcc=None, headers=None): """ Send email rendering text and html versions for the specified template name using the context dictionary passed in. """ if context is None: context = {} if attachments is None: attachments = [] if fail_silently is None: fail_silently = settings.EMAIL_FAIL_SILENTLY # Add template accessible settings from Mezzanine to the context # (normally added by a context processor for HTTP requests) context.update() # Allow for a single address to be passed in. # Python 3 strings have an __iter__ method, so the following hack # doesn't work: if not hasattr(addr_to, "__iter__"): if isinstance(addr_to, str) or isinstance(addr_to, bytes): addr_to = [addr_to] if addr_bcc is not None and (isinstance(addr_bcc, str) or isinstance(addr_bcc, bytes)): addr_bcc = [addr_bcc] # Loads a template passing in vars as context. render = lambda type: loader.get_template("%s.%s" % (template, type)).render(Context(context)) # Create and send email. msg = EmailMultiAlternatives(subject, render("txt"), addr_from, addr_to, addr_bcc, headers=headers) msg.attach_alternative(render("html"), "text/html") for attachment in attachments: msg.attach(*attachment) msg.send(fail_silently=fail_silently)
def send_opportunity_email(subject, template, opportunities): for opportunity in opportunities: try: opportunity.instrument = Instrument.objects.get(symbol=opportunity.symbol) except ObjectDoesNotExist: pass opportunity.type = Opportunity.TYPES[opportunity.opportunity_type-1][1] logger.info('Sending notification e-mail to %s', RECIPIENT_EMAIL) t_plain = get_template('%s.txt' % template) t_html = get_template('%s.html' % template) c = Context({ 'semurg_host': SEMURG_HOST, 'portfolio_id': ANALYTICS_PORTFOLIO_ID, 'opportunities': opportunities }) msg = EmailMultiAlternatives(subject, t_plain.render(c), SENDER_EMAIL, [RECIPIENT_EMAIL]) msg.attach_alternative(t_html.render(c), 'text/html') for opportunity in opportunities: try: opportunity_date = opportunity.date.strftime('%Y-%m-%d') symbol = opportunity.symbol chart_filename = join(CHARTS_PATH, symbol, '%s.png' % opportunity_date) chart_data = open(chart_filename, 'r').read() msg.attach('%s-%s.png' % (symbol, opportunity_date), chart_data, 'image/png') except Exception: logger.exception('Failed to attach chart for %s' % opportunity.symbol) msg.send()
def send_mail(subject, html_content, from_email, recipient_list, attachments=[], priority="medium", fail_silently=False, auth_user=None, auth_password=None): from django.utils.encoding import force_unicode from django.core.mail import EmailMultiAlternatives from mailer.models import make_message from django.utils.html import strip_tags priority = PRIORITY_MAPPING[priority] message = strip_tags(html_content) 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 = EmailMultiAlternatives(email.subject, email.body, email.from_email, email.to) email.attach_alternative(html_content, "text/html") for att in attachments: email.attach(att) msg.email = email msg.save() return 1
def send_email(self, request, *args, **kwargs): # TODO: Проверить, а также сделать from_email form = SendMailForm(request.POST or None, instance=self.invoice) if form.is_valid(): invoice = form.save() to = form.cleaned_data['org_email'] template = webodt.ODFTemplate(self.document_name) doc_context = {'invoice': invoice} document = template.render(Context(doc_context)) pdf = converter().convert(document, format='pdf') is_remind = kwargs.get('remind') conf = is_remind and self.remind_send_conf or self.one_send_conf subject = render_to_string( conf['template_name']['subject'], doc_context, ).strip() text_content = render_to_string( conf['template_name']['text'], doc_context, ).srtip() msg = EmailMultiAlternatives(subject, text_content, from_email, [to]) filename = self.attach_name_template.format(invoice.id) msg.attach(filename, pdf.read(), 'application/pdf') msg.send() messages.success(request, conf['success_message']) context = {'mail_form': form, 'invoice': invoice} return self.render_to_response(context)
def send_mail_with_attachments(subject, message, from_email, recipient_list, fail_silently=False, auth_user=None, auth_password=None, connection=None, html_message=None, attachments=None): """ Extension of django.core.main.send_mail to allow the inclusion of attachments Easy wrapper for sending a single message to a recipient list. All members of the recipient list will see the other recipients in the 'To' field. If auth_user is None, the EMAIL_HOST_USER setting is used. If auth_password is None, the EMAIL_HOST_PASSWORD setting is used. Note: The API for this method is frozen. New code wanting to extend the functionality should use the EmailMessage class directly. attachments must be a list of dicts of the form {'filename': <file name>, 'content': <attachment data>, 'mimetype': mime type} """ connection = connection or get_connection(username=auth_user, password=auth_password, fail_silently=fail_silently) mail = EmailMultiAlternatives(subject, message, from_email, recipient_list, connection=connection) if html_message: mail.attach_alternative(html_message, 'text/html') if attachments: for attachment in attachments: mail.attach(**attachment) return mail.send()
def send_invoice(page_type, user): if page_type.send_email: subject= page_type.email_subject try: attachment = open(page_type.attachment.url[1:],'r') except: attachment=None email_to= [user.email] plaintext = get_template('pages/custom_email.txt') htmly = get_template('pages/custom_email.html') try: sponsorship = SponsorshipPackage.objects.get(title=user.companyprofile.sponsor) except: sponsorship = None d = Context({'sponsorship':sponsorship, 'paypal_info': PayPalInfo.objects.all()[0], 'company':user.companyprofile}) text_content = plaintext.render(d) html_content = htmly.render(d) email = EmailMultiAlternatives(subject, text_content, 'Career Fair Staff', email_to) email.attach_alternative(html_content, "text/html") email.mixed_subtype = 'related' f = "/opt/myenv/careerfair/static/media/uploads/static images/header.png" fp = open(f, 'rb') msg_img = MIMEImage(fp.read()) fp.close() msg_img.add_header('Content-ID', '<header.png>'.format(f)) msg_img.add_header("Content-Disposition", "inline", filename="header.png") email.attach(msg_img) email.send()
def _send(self): if not self.sent: self.last_attempt = timezone.now() subject, from_email = self.subject, self.from_address text_content = self.content msg = EmailMultiAlternatives(subject, text_content, from_email) if self.reply_to: msg.reply_to = [email.strip() for email in self.reply_to.split(',') if email.strip()] if self.html_content: html_content = self.html_content msg.attach_alternative(html_content, "text/html") msg.to = [email.strip() for email in self.to_address.split(',') if email.strip()] msg.cc = [email.strip() for email in self.cc_address.split(',') if email.strip()] msg.bcc = [email.strip() for email in self.bcc_address.split(',') if email.strip()] # Add any additional attachments for attachment in self.attachment_set.all(): path = attachment.file_attachment.path if os.path.isfile(path): with open(path, 'rb') as f: content = f.read() msg.attach(attachment.original_filename, content, None) try: msg.send() self.sent = True except Exception as e: self.do_not_send = True logger.error('Mail Queue Exception: {0}'.format(e)) self.save()
def send_mail(subject, html_content, text_content, recipients, expert_request=None, attach_tor=False, attach_letter=False): # control of execution if email_is_off(): return # control of environment if env_is_local(): # local env email only to secondments mail list recipients = SECONDMENTS_MAIL_LIST # test indicator to render PDF as test sample test = test_is_on() if test: # subject with TEST subject = "This is a TEST email! " + subject msg = EmailMultiAlternatives(subject, text_content, EMAIL_HOST_USER, recipients, bcc=SECONDMENTS_MAIL_LIST) msg.attach_alternative(html_content, "text/html") msg.mixed_subtype = 'related' # attachments stuff if attach_letter or attach_tor: context = {'expert_request': expert_request, 'pagesize': 'A4', 'BASE_DIR': os.path.join(BASE_DIR, 'crppdmt/static/'), 'test_env': test,} try: tor_pdf = render_to_pdf('crppdmt/pdf/tor.html', context) letter_pdf = render_to_pdf('crppdmt/pdf/letter_of_request.html', context) msg.attach('ToR.pdf',tor_pdf,'application/pdf') msg.attach('LetterOfRequest.pdf',letter_pdf,'application/pdf') except: print("Error attaching ToR and Letter to Email. Request: " + expert_request.name) print("Error: " + str(sys.exc_info())) msg.send()
def send_mail_template(subject, template, addr_from, addr_to, context=None, attachments=None, fail_silently=False, addr_bcc=None): """ Send email rendering text and html versions for the specified template name using the context dictionary passed in. """ if context is None: context = {} if attachments is None: attachments = [] # Allow for a single address to be passed in. if not hasattr(addr_to, "__iter__"): addr_to = [addr_to] if addr_bcc is not None and not hasattr(addr_bcc, "__iter__"): addr_bcc = [addr_bcc] # Loads a template passing in vars as context. render = lambda type: loader.get_template("%s.%s" % (template, type)).render(Context(context)) # Create and send email. msg = EmailMultiAlternatives(subject, render("txt"), addr_from, addr_to, addr_bcc) msg.attach_alternative(render("html"), "text/html") for attachment in attachments: msg.attach(*attachment) msg.send(fail_silently=fail_silently)
def sync_send(self, message, message_txt): if not self.fake: email = EmailMultiAlternatives( subject=self.subject, body=message_txt, from_email=self.from_email, to=self.to, ) email.attach_alternative(message, "text/html") for attach in self.attaches: attach_file_name, attach_content, attach_content_type = attach email.attach(attach_file_name, attach_content, attach_content_type) email.send()
def dispatch(self, save=True, is_test=False): """Dispatch the communication Currently only method 'email' is implemented, all other methods will be only saved. For these messages, the email is sent via the service configured in application settings. TODO: Implement 'mail': the form with the requested text should be typeseted and the admin presented with a 'print' button. Address for filling on the envelope should be displayed to the admin. """ administrative_unit = getattr(self, "administrative_unit", None) if self.type.send_sms: # TODO: implement SMS method pass if self.type.send_email: user_email = self.user.get_email_str(self.administrative_unit) if user_email: # if we don't want to save email => its fake communication and we sent some user to administrative unit if is_test: to = administrative_unit.from_email_str body = _( "Testing email\n" "Similar email will be sent to every user (email originaly to: %(email)s !!\n" "^^^Ignore those lines ^^^\n\n") % { "email": user_email } body = str(body) + self.summary_txt() else: to = user_email body = self.summary_txt() email = EmailMultiAlternatives( subject=self.subject, body=body, from_email=administrative_unit.from_email_str, to=[to], ) if self.communication_type != "individual": email.attach_alternative(self.summary, "text/html") if self.attachment: att = self.attachment email.attach(os.path.basename(att.name), att.read()) email.send(fail_silently=False) self.dispatched = True if save: self.save() else: self.dispatched = True if save: self.save()
def send_mail(subject, html_content, text_content, recipients, expert_request=None, attach_tor=False, attach_letter=False): # control of execution if email_is_off(): return # control of environment if env_is_local(): # local env email only to secondments mail list recipients = SECONDMENTS_MAIL_LIST # test indicator to render PDF as test sample test = test_is_on() if test: # subject with TEST subject = "This is a TEST email! " + subject msg = EmailMultiAlternatives(subject, text_content, EMAIL_HOST_USER, recipients, bcc=SECONDMENTS_MAIL_LIST) msg.attach_alternative(html_content, "text/html") msg.mixed_subtype = 'related' # attachments stuff if attach_letter or attach_tor: context = { 'expert_request': expert_request, 'pagesize': 'A4', 'BASE_DIR': os.path.join(BASE_DIR, 'crppdmt/static/'), 'test_env': test, } try: tor_pdf = render_to_pdf('crppdmt/pdf/tor.html', context) letter_pdf = render_to_pdf( 'crppdmt/pdf/letter_of_request.html', context) msg.attach('ToR.pdf', tor_pdf, 'application/pdf') msg.attach('LetterOfRequest.pdf', letter_pdf, 'application/pdf') except: print("Error attaching ToR and Letter to Email. Request: " + expert_request.name) print("Error: " + str(sys.exc_info())) msg.send()
def send_contact_member_form(subject, message, member, contact_member, copy_to_member, attachments): msg = EmailMultiAlternatives('Nachricht per ' + Config.adminportal_name() + ': ' + subject, message, member.email, [contact_member.email], headers={'Reply-To': member.email}) for attachment in attachments: msg.attach(attachment.name, attachment.read()) send_mail_multi(msg) if copy_to_member: send_mail( 'Nachricht per ' + Config.adminportal_name() + ': ' + subject, message, member.email, [member.email])
def lidgeld_mail(pk): plaintext = get_template('mail/lidgeld.txt') htmly = get_template('mail/lidgeld.html') betaling = Betaling.objects.get(pk=pk) lid = betaling.lid datum_versturen = datetime.date.today().strftime('%d-%m-%Y') datum_verval = (datetime.date.today() + timedelta(days=40)).strftime('%d-%m-%Y') to = [] if lid.moeder: to.append(lid.moeder.email) if lid.vader: to.append(lid.vader.email) if lid.email: to.append(lid.email) d = { 'betaling': betaling, 'lid': lid, 'datum_versturen': datum_versturen, 'datum_verval': datum_verval, 'emailadressen': to, } image_path = "management/static/management/images/signature.png" image_name = "signature" subject, from_email = "Inschrijvingsgeld {} LDP Donza, seizoen '20-'21".format( lid), '*****@*****.**' text_content = plaintext.render(d) html_content = htmly.render(d) msg = EmailMultiAlternatives(subject, text_content, from_email, to, reply_to=['*****@*****.**']) msg.attach_alternative(html_content, "text/html") msg.mixed_subtype = 'related' with open(image_path, mode='rb') as f: image = MIMEImage(f.read()) msg.attach(image) image.add_header('Content-ID', '<%s>' % image_name) msg.send() betaling.status = 'mail_sent' betaling.mails_verstuurd = str(datetime.date.today()) betaling.save()
def run(self, *args, **kwargs): self.init(*args, **kwargs) # Get the csv data from GeneralMetrics csv_data = self.get_csv(self.get_data()) email_message = EmailMultiAlternatives( subject='Archivo csv', from_email='*****@*****.**', to=[self.email], ) email_message.attach(self.filename, csv_data, 'text/csv') email_message.attach_alternative('Archivo csv', "text/html") return email_message.send()
def send_alert(self, service, users, duty_officers): """ Send an email to the specified users with the service status and (possibly) Grafana panel images/links. """ emails = [u.email for u in users if u.email] + \ [u.email for u in duty_officers if u.email] if not emails: return # don't send emails for acked services if service.overall_status == service.ACKED_STATUS: return c = Context({ 'service': service, 'host': settings.WWW_HTTP_HOST, 'scheme': settings.WWW_SCHEME }) images = {} if service.overall_status != service.PASSING_STATUS: subject = '%s status for service: %s' % (service.overall_status, service.name) failing_metrics_checks = service.all_failing_checks() # Get the panel urls and name: image mapping for the failing metrics checks for check in failing_metrics_checks: image = check.get_status_image() if image is not None: images[check.name] = image else: subject = 'Service back to normal: %s' % (service.name, ) text_message = Template(email_txt_template).render(c) html_message = Template(email_html_template).render(c) sender = 'Cabot <%s>' % env.get('CABOT_FROM_EMAIL') msg = EmailMultiAlternatives(subject, text_message, sender, emails) msg.attach_alternative(html_message, 'text/html') msg.mixed_subtype = 'related' # Insert images here for name, image in images.iteritems(): msg.attach('{}.png'.format(name), image, 'image/png') msg.send()
def render_to_pdf(template_src, context_dict={}): template = get_template(template_src) html = template.render(context_dict) result = BytesIO() pdf = pisa.pisaDocument( BytesIO(html.replace(u'\ufeff', '').encode("latin-1")), result) subject, from_email, to = 'hello', '*****@*****.**', '*****@*****.**' text_content = 'This is an important message.' # html_content = html_message = render_to_string('portfolio/Pdf.html', {'context': 'values'}) msg = EmailMultiAlternatives(subject, text_content, from_email, [to]) msg.attach("customer_portfolio", result.getvalue(), "application/pdf") msg.send() if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') return None
def send_order_success_email(self): invoice = self.generate_invoice() if invoice is not None: context = {'order_id': self.order_id.upper()} subject = 'Your Order [{id}] with Kart has been confirmed.'.format( id=self.order_id.upper()) from_email = settings.DEFAULT_FROM_EMAIL recipient = [self.billing_profile.email] txt_ = get_template('order/order_success.txt').render(context) html_ = get_template('order/order_success.html').render(context) mail = EmailMultiAlternatives(subject, txt_, from_email, recipient) mail.attach_alternative(html_, "text/html") mail.attach('invoice.pdf', invoice.getvalue(), 'application/pdf') mail.send()
def send_ticket_email(ticket_data, ticket_svg): event_name = ticket_data['event'].name first_name = ticket_data['first_name'] last_name = ticket_data['last_name'] email_to = ticket_data['email'] ticket_code = ticket_data['ticket'].code email = EmailMultiAlternatives() email.subject = get_ticket_subject(event_name) body_txt, body_html = get_ticket_body(first_name, last_name, event_name) email.body = body_txt email.attach_alternative(body_html, "text/html") email.to = [email_to] email.attach('Ticket-{}.pdf'.format(ticket_code), cairosvg.svg2pdf(bytestring=ticket_svg), 'application/pdf') email.send(fail_silently=False)
def send_html_mail(subject, body_txt, body_html, recipient): message = EmailMultiAlternatives(subject, body_txt, settings.DEFAULT_FROM_EMAIL, [recipient]) message.attach_alternative(body_html, 'text/html') message.mixed_subtype = 'related' logo_file = open( settings.STATIC_ROOT.child('images').child('logo.png'), 'rb') logo_mime = MIMEImage(logo_file.read()) logo_file.close() logo_mime.add_header('Content-ID', '<*****@*****.**>') logo_mime.add_header('Content-Disposition', 'attachment') message.attach(logo_mime) message.send()
def send_notification(notification, recipients, **kwargs): # HTML to text conversion html2text = HTML2Text(bodywidth=78) html2text.unicode_snob = True html2text.ignore_images = True html2text.pad_tables = True # Logos images = [] for name in ("email-logo.png", "email-logo-footer.png"): filename = os.path.join(settings.STATIC_ROOT, name) with open(filename, "rb") as handle: image = MIMEImage(handle.read()) image.add_header("Content-ID", "<{}@cid.weblate.org>".format(name)) image.add_header("Content-Disposition", "inline", filename=name) images.append(image) # Context and subject context = { "LANGUAGE_CODE": get_language(), "LANGUAGE_BIDI": get_language_bidi(), } context.update(kwargs) subject = render_to_string( "mail/{0}_subject.txt".format(notification), context ).strip() context["subject"] = subject # Render body body = render_to_string("mail/{0}.html".format(notification), context).strip() # Prepare e-mail email = EmailMultiAlternatives( subject, html2text.handle(body), "*****@*****.**", recipients, ) email.mixed_subtype = "related" for image in images: email.attach(image) email.attach_alternative(body, "text/html") # Include invoice PDF if exists if "invoice" in kwargs: with open(kwargs["invoice"].pdf_path, "rb") as handle: email.attach( os.path.basename(kwargs["invoice"].pdf_path), handle.read(), "application/pdf", ) email.send()