def _mail_admins_with_attachment(subject, message, fail_silently=True, connection=None, html_message=None, attachments=None): """ Mimics mail_admins, but allows attaching files to the message""" if not settings.ADMINS: return mail = EmailMultiAlternatives( "%s%s" % (settings.EMAIL_SUBJECT_PREFIX, subject), message, settings.SERVER_EMAIL, [a[1] for a in settings.ADMINS], connection=connection) if html_message: mail.attach_alternative(html_message, "text/html") if attachments: for attachment_name, attachment_content, attachment_mime in attachments: mail.attach(attachment_name, attachment_content, attachment_mime) mail.send(fail_silently=fail_silently)
def handle(self, *args, **options): lines = sys.stdin.readlines() if settings.INCOMING_EMAIL_LOGGING == 'ALL': if not settings.ADMINS: return text_content = "New incomming email" subject = "New incomming email" mail = EmailMultiAlternatives('%s%s' % (settings.EMAIL_SUBJECT_PREFIX, subject), text_content, # content settings.DEFAULT_FROM_EMAIL, # From [a[1] for a in settings.ADMINS] # To ) mail.attach('mail.txt', ''.join(lines), 'text/plain') mail.send() handler = EmailHandler(answer_class=AnswerForManageCommand) try: answer = handler.handle(lines) answer.send_back() except CouldNotFindIdentifier: pass except: tb = traceback.format_exc() text_content = "Error the traceback was:\n" + tb #mail_admins('Error handling incoming email', html_message, html_message=html_message) subject = "Error handling incoming email" mail = EmailMultiAlternatives('%s%s' % (settings.EMAIL_SUBJECT_PREFIX, subject), text_content, # content settings.DEFAULT_FROM_EMAIL, # From [a[1] for a in settings.ADMINS], # To ) mail.attach('mail.txt', ''.join(lines), 'text/plain') mail.send()
def send(self, object_or_list): """ Given an object_or_list creates a EmailMultiAlternatives and send it to the respective destination. If Attachments exist, also adds them to the messsage. """ html_as_string = self.render() text_part = strip_tags(html_as_string) to = self.get_mail_to(object_or_list) if to: msg = EmailMultiAlternatives(self.get_subject(), text_part, self.get_mail_from(), to=to, cc=self.get_mail_cc(), bcc=self.get_mail_bcc(), reply_to=self.get_mail_reply_to()) # Attach the html version of email msg.attach_alternative(html_as_string, "text/html") # If there is attachments attach them to the email for attachment in self.get_attachments(): msg.attach(*attachment.get_triple()) return get_connection().send_messages([msg]) return 0
def send_email(self, subject, text_content, recipients, html_content=None, attachments=None, reply_to=None): logger.info("sending email '%s'..." % subject) if reply_to is None: reply_to = settings.NO_REPLY_EMAIL _recipients = filter(None, recipients) msg = EmailMultiAlternatives(subject, text_content, settings.NO_REPLY_EMAIL, _recipients, reply_to=[reply_to]) if html_content: logger.info("attaching HTML alternative") msg.attach_alternative(html_content, "text/html") if attachments: for a in attachments: logger.info("attaching file: " + a.filename) msg.attach(a.filename, a.file, a.mime) if _recipients: msg.send() logger.info("sent successfully")
def send_HTML_email(subject, recipient, html_content, text_content=None, cc=None, email_from=settings.DEFAULT_FROM_EMAIL, file_attachments=None, bcc=None): if not text_content: text_content = getattr(settings, 'NO_HTML_EMAIL_MESSAGE', NO_HTML_EMAIL_MESSAGE) from_header = {'From': email_from} # From-header connection = get_connection() msg = EmailMultiAlternatives(subject, text_content, email_from, [recipient], headers=from_header, connection=connection, cc=cc, bcc=bcc) for file in (file_attachments or []): if file: msg.attach(file["title"], file["file_obj"].getvalue(), file["mimetype"]) msg.attach_alternative(html_content, "text/html") msg.send()
def send_email(subject, template_name, context, from_email=settings.EMAIL_HOST_USER, receipts=None, file_path=None, file_name=None, file_content=None, mime_type=None): from django.core.mail.message import EmailMultiAlternatives from django.core.mail import DEFAULT_ATTACHMENT_MIME_TYPE from django.template.loader import render_to_string from django.utils.html import strip_tags if receipts is None: receipts = [] email_message_html = render_to_string(template_name, context=context) email_message_plaintext = strip_tags(email_message_html) email = EmailMultiAlternatives(subject=subject, body=email_message_plaintext, from_email=from_email, to=receipts) email.attach_alternative(email_message_html, 'text/html') if file_path: email.attach_file(file_path, mimetype=DEFAULT_ATTACHMENT_MIME_TYPE) if file_content: email.attach(filename=file_name, content=file_content, mimetype=mime_type) email.send()
def post(self, request): handler = EmailHandler(answer_class=OutboundMessageAnswer) email = request.POST['email'] try: logger.debug("SendGrid Inbound mail webhook POST email\n\n%s" % email) answer = handler.handle(email) answer.send_back() except CouldNotFindIdentifier as e: logger.warn(e) except Exception as e: tb = traceback.format_exc() text_content = "Error the traceback was:\n" + tb #mail_admins('Error handling incoming email', html_message, html_message=html_message) subject = "Error handling incoming email" mail = EmailMultiAlternatives( '%s%s' % (settings.EMAIL_SUBJECT_PREFIX, subject), text_content, # content settings.DEFAULT_FROM_EMAIL, # From [a[1] for a in settings.ADMINS], # To ) mail.attach('mail.txt', email, 'text/plain') mail.send() raise e return HttpResponse()
def dispatch(self, object, *args, **kwargs): self.object = object languages = [get_language(), self.fallback_language] receivers = self.get_receiver_emails() context = self.get_context() context.update(kwargs) attachments = self.get_attachments() template = self.template_name subject = select_template([ 'emails/{}.{}.subject'.format(template, lang) for lang in languages ]) plaintext = select_template([ 'emails/{}.{}.txt'.format(template, lang) for lang in languages ]) html = select_template([ 'emails/{}.{}.html'.format(template, lang) for lang in languages ]) mail = EmailMultiAlternatives( subject=subject.render(context).strip(), body=plaintext.render(context), from_email=settings.DEFAULT_FROM_EMAIL, to=receivers, ) if len(attachments) > 0: mail.mixed_subtype = 'related' for attachment in attachments: mail.attach(attachment) mail.attach_alternative(html.render(context), 'text/html') mail.send() return mail
def send_email(self, emailobj, attachment): if emailobj: email_multimedia = EmailMultimedia.objects.filter( dealer=emailobj.dealer) email_body, emailbodyhtml = self.get_email_body(emailobj) bcc = self.get_bcc(emailobj) cc = self.get_cc(emailobj) mail_to = self.get_to(emailobj) msg = EmailMultiAlternatives(emailobj.subject, emailbodyhtml, emailobj.mail_from, mail_to, bcc=bcc, cc=cc) msg.content_subtype = "html" for obj in email_multimedia: fp = open( os.path.join(settings.MEDIA_ROOT, 'email_media/' + obj.multimedia_file), 'rb') msg_img = MIMEImage(fp.read()) fp.close() msg_img.add_header('Content-ID', '<{}>'.format(obj.multimedia_file)) msg.attach(msg_img) if attachment: msg.attach("CheckinReview.pdf", attachment, "application/pdf") msg.send() print "mail sent"
def send_bulk_emails(cls, subject, body, from_email, to_email_list, dict_images=None): msg_list = [] for email in to_email_list: msg = EmailMultiAlternatives(subject, body, from_email, [email]) if dict_images: for key in dict_images.keys(): image_path = dict_images.get(key) fp = open(image_path, 'rb') mimeImage = MIMEImage(fp.read()) fp.close() mimeImage.add_header('Content-ID', '<'+ key +'>') msg.attach(mimeImage) msg.attach_alternative(body, "text/html") msg.encoding = "utf-8" msg.mixed_subtype = 'related' #msg.content_subtype = "html" # Doute msg_list.append(msg) connection = mail.get_connection() connection.open() ten_msg_list = [] while msg_list <> []: if len(ten_msg_list) < 1000: ten_msg_list.append(msg_list[0]) msg_list.pop(0) else: connection.send_messages(ten_msg_list) ten_msg_list = [] if ten_msg_list <> []: connection.send_messages(ten_msg_list) connection.close()
def send_HTML_email(subject, recipient, html_content, text_content=None, cc=None, email_from=settings.DEFAULT_FROM_EMAIL, file_attachments=None, bcc=None, smtp_exception_skip_list=None): recipient = list(recipient) if not isinstance(recipient, six.string_types) else [recipient] if not isinstance(html_content, six.text_type): html_content = html_content.decode('utf-8') if not text_content: text_content = getattr(settings, 'NO_HTML_EMAIL_MESSAGE', NO_HTML_EMAIL_MESSAGE) elif not isinstance(text_content, six.text_type): text_content = text_content.decode('utf-8') from_header = {'From': email_from} # From-header connection = get_connection() msg = EmailMultiAlternatives(subject, text_content, email_from, recipient, headers=from_header, connection=connection, cc=cc, bcc=bcc) for file in (file_attachments or []): if file: msg.attach(file["title"], file["file_obj"].getvalue(), file["mimetype"]) msg.attach_alternative(html_content, "text/html") try: msg.send() except SMTPSenderRefused as e: if smtp_exception_skip_list and e.smtp_code in smtp_exception_skip_list: raise e else: error_subject = _('ERROR: Could not send "%(subject)s"') % { 'subject': subject, } if e.smtp_code == 552: error_text = _('Could not send email: file size is too large.') else: error_text = e.smtp_error error_text = '%s\n\n%s' % ( error_text, _('Please contact %(support_email)s for assistance.') % { 'support_email': settings.SUPPORT_EMAIL, }, ) error_msg = EmailMultiAlternatives( error_subject, error_text, email_from, recipient, headers=from_header, connection=connection, cc=cc, bcc=bcc, ) error_msg.send()
def send_application_proposal(app_proposal): from mcod.datasets.models import Dataset conn = get_connection(settings.EMAIL_BACKEND) emails = [ config.CONTACT_MAIL, ] title = app_proposal["title"] applicant_email = app_proposal.get('applicant_email', "") img_data = app_proposal.get('image', None) if img_data: data = img_data.split(';base64,')[-1].encode('utf-8') decoded_img = base64.b64decode(data) image = MIMEImage(decoded_img) img_name = slugify(app_proposal['title']) filename = f"{img_name}.{image.get_content_subtype()}" image.add_header('content-disposition', 'attachment', filename=filename) image.add_header('Content-ID', '<app-logo>') datasets = Dataset.objects.filter(id__in=app_proposal.get('datasets', [])) app_proposal['datasets'] = '\n'.join(f"{settings.BASE_URL}/dataset/{ds.id}" for ds in datasets) app_proposal['dataset_links'] = '<br />'.join( f"<a href=\"{settings.BASE_URL}/dataset/{ds.id}\">{ds.title}</a>\n" for ds in datasets) external_datasets = app_proposal.get('external_datasets', []) app_proposal['external_datasets'] = '\n'.join( f"{eds.get('title', '(nie nazwany)')}: {eds.get('url', '(nie podano url)')}\n" for eds in external_datasets) app_proposal['external_dataset_links'] = '<br />'.join(( f"{eds.get('title')}: <a href=\"{eds.get('url')}\">{eds.get('url')}</a>\n" if 'url' in eds else eds.get('title')) for eds in external_datasets) app_proposal['keywords'] = ', '.join(app_proposal.get('keywords', tuple())) app_proposal['host'] = settings.BASE_URL msg_plain = render_to_string('mails/propose-application.txt', app_proposal) msg_html = render_to_string('mails/propose-application.html', app_proposal) if settings.DEBUG and config.TESTER_EMAIL: emails = [config.TESTER_EMAIL] mail = EmailMultiAlternatives(f'Zgłoszono propozycję aplikacji {title}', msg_plain, from_email=config.NO_REPLY_EMAIL, to=emails, connection=conn) mail.mixed_subtype = 'related' mail.attach_alternative(msg_html, 'text/html') if img_data: mail.attach(image) mail.send() return {'application_proposed': f'{title} - {applicant_email}'}
def send_email(self, filename): # send email email = EmailMultiAlternatives(subject='[Olympia GnosisDB backup]', body='GnosisDB backup attached.', from_email=settings.SERVER_EMAIL, to=[a[1] for a in settings.ADMINS]) fd = open(filename, 'r') email.attach('GnosisDB_dump', fd.read(), 'text/plain') email.send()
def send_error_email(email, traceback): text_content = "Error the traceback was:\n" + traceback #mail_admins('Error handling incoming email', html_message, html_message=html_message) subject = "Error handling incoming email" mail = EmailMultiAlternatives('%s%s' % (settings.EMAIL_SUBJECT_PREFIX, subject), text_content, # content settings.DEFAULT_FROM_EMAIL, # From [a[1] for a in settings.ADMINS], # To ) mail.attach('mail.txt', email, 'text/plain') mail.send()
def dispatch(self, object, *args, **kwargs): self.object = object self.kwargs = kwargs receivers = self.get_receivers() context = self.get_context() context.update(kwargs) attachments = self.get_attachments() template = self.template_name mails = [] mail_exceptions = [] for receiver in receivers: context['receiver'] = receiver (subject, text, html) = self.render(template, context) context.pop('receiver') if hasattr(receiver, 'email'): to_address = receiver.email else: to_address = receiver subject_clean = re.sub(r'[\r\n]', '', subject).strip() mail = EmailMultiAlternatives( subject=subject_clean, body=text, from_email=settings.DEFAULT_FROM_EMAIL, to=[to_address], reply_to=self.get_reply_to(), ) if len(attachments) > 0: mail.mixed_subtype = 'related' for attachment in attachments: mail.attach(attachment) mail.attach_alternative(html, 'text/html') mails.append(mail) if self.enable_reporting: try: mail.send() except SMTPException as exc: mail_exceptions.append(exc) else: mail.send() if self.enable_reporting: self.handle_report(mails, mail_exceptions) return mails
def send_smtp(self, context, email_from_string, email_to, subject, cc_emails=None, attachments=None): """ Sends the email over SMTP. Right now using the Amazon SES service to send """ # Handle None or strings for cc_emails if not cc_emails: cc_emails = [] elif isinstance(cc_emails, six.string_types): cc_emails = [cc_emails] attachments = attachments or () # Add subject to the context context['subject'] = subject # Add the sendee so that we can track it with litmus if self.litmus_tracking_code: context['litmus_email_merge_tag'] = email_to context['litmus_tracking_code'] = self.litmus_tracking_code # Get the body via django template template = get_template(self.base_template_dir+self.body_template) body = template.render(context) # Get html body html_body = None if self.html_template: html_template = get_template(self.base_template_dir+self.html_template) html_body = html_template.render(context) # Send email! msg = EmailMultiAlternatives( subject, body, email_from_string, [email_to], headers=self.get_headers() or None, cc=cc_emails ) if html_body: msg.attach_alternative(html_body, "text/html") for attach_ in attachments: msg.attach(attach_) msg.send(fail_silently=True)
def send_mail(self, subject, text_message, html_message, from_email, recipient_list, bcc_list): connection = get_connection(username=None, password=None, fail_silently=False) mail = EmailMultiAlternatives(subject, text_message, from_email, recipient_list, bcc=bcc_list, connection=connection) if html_message: mail.attach('pretty_report.html', html_message, 'text/html') return mail.send()
def send_email_to_coordinator(self, pdf_to_attach, notification_name, report_id): notification = EmailNotification.objects.get(name=notification_name) to = settings.COORDINATOR_EMAIL email = EmailMultiAlternatives(notification.subject, notification.render_body_plain(), self.from_email, [to]) email.attach_alternative(notification.render_body(), "text/html") gpg = gnupg.GPG() school_public_key = settings.COORDINATOR_PUBLIC_KEY imported_keys = gpg.import_keys(school_public_key) #TODO: sign encrypted doc attachment = gpg.encrypt(pdf_to_attach, imported_keys.fingerprints[0], armor=True, always_trust=True) email.attach(self.report_filename.format(report_id), attachment.data, "application/octet-stream") email.send()
def send(self, from_addr=None, fail_silently=False): if isinstance(self.to, basestring): self.to = [self.to] if not from_addr: from_addr = getattr(settings, 'DEFAULT_FROM_EMAIL') msg = EmailMultiAlternatives( self.subject, self._text, from_addr, to=self.to, bcc=self.bcc, ) if self._html: msg.attach_alternative(self._html, 'text/html') if self._attachment: msg.attach(self._attachment.name, self._attachment.read()) msg.send()
def send(self, from_addr=None, fail_silently=False): if isinstance(self.to, basestring): self.to = [self.to] if not from_addr: from_addr = getattr(settings, 'DEFAULT_FROM_EMAIL') msg = EmailMultiAlternatives( self.subject, self._text, from_addr, to=self.to, bcc=self.bcc, ) if self._html: msg.attach_alternative(self._html, 'text/html') if self._attachment: msg.attach(self._attachment.name, self._attachment.read()) msg.send()
def send_HTML_email(subject, recipient, html_content, text_content=None, cc=None, email_from=settings.DEFAULT_FROM_EMAIL, file_attachments=None, bcc=None): if not text_content: text_content = getattr(settings, 'NO_HTML_EMAIL_MESSAGE', NO_HTML_EMAIL_MESSAGE) from_header = {'From': email_from} # From-header connection = get_connection() msg = EmailMultiAlternatives(subject, text_content, email_from, [recipient], headers=from_header, connection=connection, cc=cc, bcc=bcc) for file in (file_attachments or []): if file: msg.attach(file["title"], file["file_obj"].getvalue(), file["mimetype"]) msg.attach_alternative(html_content, "text/html") msg.send()
def send_email(self, context): """ Sends an email to admin containing a csv of all users who have logged in within the given days and have staff access role in active courses (Courses with end date in the future). Arguments: context: context for the email template """ plain_content = self.render_template(self.txt_template_path, context) html_content = self.render_template(self.html_template_path, context) with open(self.csv_filename, 'r') as csv_file: email_message = EmailMultiAlternatives(self.subject, plain_content, self.from_address, to=self.to_addresses) email_message.attach_alternative(html_content, 'text/html') email_message.attach(self.csv_filename, csv_file.read(), 'text/csv') email_message.send() remove(self.csv_filename)
def send_invoice(invoice): """ Sends Invoice to the invoice partner """ template = EmailTemplate.objects.get(name='invoice-email') subject = replace_invoice_vars(template.subject, invoice, 'en') message_plain = replace_invoice_vars(template.plain_text, invoice, 'en') message_html = replace_invoice_vars(template.html_text, invoice, 'en') partner_email = invoice.partner.partner_email or invoice.partner.finance_email # make email msg = EmailMultiAlternatives( subject=subject, body=message_plain, from_email='*****@*****.**', to=[partner_email, ], bcc=['*****@*****.**'], ) msg.attach_alternative(message_html, 'text/html') # make Invoice PDF cmd_options = { 'orientation': 'landscape', 'page-size': 'A4', 'title': invoice.invoice_nr } template = 'adventures/invoice/invoice_pdf.html' context = { 'invoice': invoice, 'partner': invoice.partner, } pdf_data = PDFTemplateResponse(request=None, template=template, context=context, filename=invoice.invoice_nr, show_content_in_browser=True, cmd_options=cmd_options) pdf_data.render() pdf_data.close() filename = "{} invoice Adventure Tickets {}.pdf".format(invoice.created.strftime("%Y-%m-%d"), invoice.invoice_nr) msg.attach(filename, pdf_data.rendered_content, 'application/pdf') msg.send() logger.info("Invoice sent to {}: {}".format(partner_email, str(invoice)))
def send_reply_email(files, recipients, subject, body, fail_silently=False, sender=None): """send email""" if not sender: sender = settings.DEFAULT_FROM_EMAIL msg = EmailMultiAlternatives(subject, body, sender, recipients) if files: for attachment in files: file_to_attach = attachment[1] file_to_attach.open() msg.attach(filename=attachment[0], content=file_to_attach.read()) file_to_attach.close() return msg.send(fail_silently)
def _mail_admins_with_attachment(subject, message, fail_silently=True, connection=None, html_message=None, attachments=None): """ Mimics mail_admins, but allows attaching files to the message""" if not settings.ADMINS: return mail = EmailMultiAlternatives( "%s%s" % (settings.EMAIL_SUBJECT_PREFIX, subject), message, settings.SERVER_EMAIL, [a[1] for a in settings.ADMINS], connection=connection ) if html_message: mail.attach_alternative(html_message, "text/html") if attachments: for attachment_name, attachment_content, attachment_mime in attachments: mail.attach(attachment_name, attachment_content, attachment_mime) mail.send(fail_silently=fail_silently)
def send_email(self,connecion): vars = json.loads(self.message) template_directory = getattr(settings, "EMAIL_TEMPLATE_DIR", 'email') if self.template.endswith('.html') or self.template.endswith('.txt'): try: html_content = render_to_string(template_directory+'/%s'%self.template,vars) except TemplateDoesNotExist: raise TemplateDoesNotExist('Template dir %s does not exist.'%template_directory) text_content = strip_tags(html_content) else: try: t = get_template_from_string(self.template) html_content = t.render(Context(vars)) except TemplateSyntaxError: raise TemplateSyntaxError('Template syntax error.') text_content = strip_tags(html_content) try: if self.content_type == 'html': send_to_list = self.send_to.split(",") if len(send_to_list)>0: msg = EmailMultiAlternatives(self.subject,text_content,from_email=self.send_from,to=[send_to_list[0]],connection=connecion, bcc=send_to_list[1:], headers={'Cc': ','.join(send_to_list[1:])}) else: msg = EmailMultiAlternatives(self.subject,text_content,from_email=self.send_from,to=[send_to_list[0]],connection=connecion) msg.attach_alternative(html_content,"text/html") else: send_to_list = self.send_to.split(",") if len(send_to_list)>0: msg = EmailMessage(self.subject,text_content,from_email=self.send_from,to=[send_to_list[0]],connection=connecion, bcc=send_to_list[1:], headers={'Cc': ','.join(send_to_list[1:])}) else: msg = EmailMessage(self.subject,text_content,from_email=self.send_from,to=[send_to_list[0]],connection=connecion) if ('attachment' in vars['data']) and (vars['data']['attachment']!={}): path = vars['data']['attachment']['att_file_path'] with open(path, 'r') as f: msg.attach(vars['data']['attachment']['att_file_name'], f.read(), vars['data']['attachment']['att_file_type']) f.closed os.remove(path) except Exception: raise Exception('Email message %s can not created.'%self.id) self.delete() return msg
def handle(self, *args, **options): lines = sys.stdin.readlines() if settings.INCOMING_EMAIL_LOGGING == 'ALL': if not settings.ADMINS: return text_content = "New incomming email" subject = "New incomming email" mail = EmailMultiAlternatives( '%s%s' % (settings.EMAIL_SUBJECT_PREFIX, subject), text_content, # content settings.DEFAULT_FROM_EMAIL, # From [a[1] for a in settings.ADMINS] # To ) mail.attach('mail.txt', ''.join(lines), 'text/plain') mail.send() handler = EmailHandler(answer_class=AnswerForManageCommand) try: answer = handler.handle(lines) answer.send_back() except CouldNotFindIdentifier: pass except TemporaryFailure: pass except: tb = traceback.format_exc() text_content = "Error the traceback was:\n" + tb #mail_admins('Error handling incoming email', html_message, html_message=html_message) subject = "Error handling incoming email" mail = EmailMultiAlternatives( '%s%s' % (settings.EMAIL_SUBJECT_PREFIX, subject), text_content, # content settings.DEFAULT_FROM_EMAIL, # From [a[1] for a in settings.ADMINS], # To ) mail.attach('mail.txt', ''.join(lines), 'text/plain') mail.send()
def send_email(self, context, node=None): if not node: recipients = Group.objects.get( name=settings.READ_DATAJSON_RECIPIENT_GROUP).user_set.all() else: recipients = node.admins.all() emails = [user.email for user in recipients] if not emails: # Nothing to do here return start_time = self._format_date(self.task.created) subject = u'[{}] API Series de Tiempo: {}'.format( settings.ENV_TYPE, start_time) msg = render_to_string('indexing/report.txt', context=context) mail = EmailMultiAlternatives(subject, msg, settings.EMAIL_HOST_USER, emails) html_msg = render_to_string('indexing/report.html', context=context) mail.attach_alternative(html_msg, 'text/html') mail.attach('errors.log', self.task.logs, 'text/plain') mail.attach('catalogs.csv', attachments.generate_catalog_attachment(node=node), 'text/csv') mail.attach('datasets.csv', attachments.generate_dataset_attachment(node=node), 'text/csv') mail.attach('distributions.csv', attachments.generate_distribution_attachment(node=node), 'text/csv') mail.attach('series.csv', attachments.generate_field_attachment(node=node), 'text/csv') sent = mail.send() if emails and not sent: raise ValueError
def send_email_to_coordinator(self, pdf_to_attach, notification_name, report_id): notification = EmailNotification.objects.get(name=notification_name) to = settings.COORDINATOR_EMAIL email = EmailMultiAlternatives(notification.subject, notification.render_body_plain(), self.from_email, [to]) email.attach_alternative(notification.render_body(), "text/html") gpg = gnupg.GPG() school_public_key = settings.COORDINATOR_PUBLIC_KEY imported_keys = gpg.import_keys(school_public_key) #TODO: sign encrypted doc attachment = gpg.encrypt(pdf_to_attach, imported_keys.fingerprints[0], armor=True, always_trust=True) email.attach(self.report_filename.format(report_id), attachment.data, "application/octet-stream") email.send()
def on_email_task_save(sender, instance, created, **kwargs): if created: try: tpl = Text.objects.active().get(place=Text.PLACE.EMAIL) except Text.DoesNotExist: return ctx = tpl.get_template_context(instance.customer) text = tpl.render(data=ctx) ctx['msg'] = text ctx['token'] = instance.token ctx['site_url'] = settings.SITE_URL tpl = loader.get_template('email_card.html') text = tpl.render(Context(ctx)) conf = SiteConfiguration.get_solo() msg = EmailMultiAlternatives(subject=conf.email_subject, body=text, to=[instance.customer.email], from_email=settings.DEFAULT_FROM_EMAIL) msg.attach_alternative(text, 'text/html') card_img = MIMEImage( open('content/static/img/card-h.png', 'rb').read()) card_img.add_header('Content-ID', '<card_image>') logo = MIMEImage(open('content/static/img/logo.png', 'rb').read()) logo.add_header('Content-ID', '<logo>') bac_logo = MIMEImage( open('content/static/img/BAC_Logo.png', 'rb').read()) bac_logo.add_header('Content-ID', '<bac_logo>') msg.attach(card_img) msg.attach(logo) msg.attach(bac_logo) try: msg.send(fail_silently=False) except: instance.customer.email_status = EmailStatus.FAILED else: instance.customer.email_status = EmailStatus.SENT instance.when_sent = timezone.now() instance.save() finally: instance.customer.save() else: if instance.when_opened \ and instance.customer.email_status != EmailStatus.OPENED: instance.customer.email_status = EmailStatus.OPENED instance.customer.save()
def send_HTML_email(subject, recipient, html_content, text_content=None, cc=None, email_from=settings.DEFAULT_FROM_EMAIL, file_attachments=None, bcc=None): recipient = list(recipient) if not isinstance(recipient, basestring) else [ recipient ] if not text_content: text_content = getattr(settings, 'NO_HTML_EMAIL_MESSAGE', NO_HTML_EMAIL_MESSAGE) # this is a temporary spam-catcher, to be removed after fb#178059 is resolved if '*****@*****.**' in recipient: notify_error( "Found an email causing spammy emails to " "[email protected]. Here's the HTML content of email" "\n {}".format(html_content)) from_header = {'From': email_from} # From-header connection = get_connection() msg = EmailMultiAlternatives(subject, text_content, email_from, recipient, headers=from_header, connection=connection, cc=cc, bcc=bcc) for file in (file_attachments or []): if file: msg.attach(file["title"], file["file_obj"].getvalue(), file["mimetype"]) msg.attach_alternative(html_content, "text/html") try: msg.send() except SMTPSenderRefused as e: error_subject = _('ERROR: Could not send "%(subject)s"') % { 'subject': subject, } if e.smtp_code == 552: error_text = _('Could not send email: file size is too large.') else: error_text = e.smtp_error error_text = '%s\n\n%s' % ( error_text, _('Please contact %(support_email)s for assistance.') % { 'support_email': settings.SUPPORT_EMAIL, }, ) error_msg = EmailMultiAlternatives( error_subject, error_text, email_from, recipient, headers=from_header, connection=connection, cc=cc, bcc=bcc, ) error_msg.send()
def send_HTML_email(subject, recipient, html_content, text_content=None, cc=None, email_from=settings.DEFAULT_FROM_EMAIL, file_attachments=None, bcc=None, ga_track=False, ga_tracking_info=None): recipient = list(recipient) if not isinstance(recipient, six.string_types) else [recipient] if not isinstance(html_content, six.text_type): html_content = html_content.decode('utf-8') if not text_content: text_content = getattr(settings, 'NO_HTML_EMAIL_MESSAGE', NO_HTML_EMAIL_MESSAGE) elif not isinstance(text_content, six.text_type): text_content = text_content.decode('utf-8') if ga_track and settings.ANALYTICS_IDS.get('GOOGLE_ANALYTICS_API_ID'): ga_data = { 'v': 1, 'tid': settings.ANALYTICS_IDS.get('GOOGLE_ANALYTICS_API_ID'), 'cid': uuid.uuid4().hex, 'dt': subject.encode('utf-8'), 't': 'event', 'ec': 'email' } extra_data = ga_tracking_info if ga_tracking_info else {} ga_data.update(extra_data) post_data = urlencode(ga_data) url = "https://www.google-analytics.com/collect?" + post_data new_content = '<img src="{url}&ea=open"/>\n</body>'.format(url=url) html_content, count = re.subn(r'(.*)</body>', r'\1'+new_content, html_content) assert count != 0, 'Attempted to add tracking to HTML Email with no closing body tag' from_header = {'From': email_from} # From-header connection = get_connection() msg = EmailMultiAlternatives(subject, text_content, email_from, recipient, headers=from_header, connection=connection, cc=cc, bcc=bcc) for file in (file_attachments or []): if file: msg.attach(file["title"], file["file_obj"].getvalue(), file["mimetype"]) msg.attach_alternative(html_content, "text/html") try: msg.send() except SMTPSenderRefused as e: error_subject = _('ERROR: Could not send "%(subject)s"') % { 'subject': subject, } if e.smtp_code == 552: error_text = _('Could not send email: file size is too large.') else: error_text = e.smtp_error error_text = '%s\n\n%s' % ( error_text, _('Please contact %(support_email)s for assistance.') % { 'support_email': settings.SUPPORT_EMAIL, }, ) error_msg = EmailMultiAlternatives( error_subject, error_text, email_from, recipient, headers=from_header, connection=connection, cc=cc, bcc=bcc, ) error_msg.send() if ga_track and settings.ANALYTICS_IDS.get('GOOGLE_ANALYTICS_API_ID'): try: try: requests.get(url + "&ea=send") except SSLError: # if we get an ssl error try without verification requests.get(url + "&ea=send", verify=False) except Exception as e: # never fail hard on analytics logging.exception(u'Unable to send google analytics request for tracked email: {}'.format(e))
def send_HTML_email(subject, recipient, html_content, text_content=None, cc=None, email_from=settings.DEFAULT_FROM_EMAIL, file_attachments=None, bcc=None, smtp_exception_skip_list=None, messaging_event_id=None, domain=None): recipients = list(recipient) if not isinstance(recipient, str) else [recipient] filtered_recipients = get_valid_recipients(recipients, domain) bounced_addresses = list(set(recipients) - set(filtered_recipients)) if bounced_addresses and messaging_event_id: mark_local_bounced_email(bounced_addresses, messaging_event_id) if not filtered_recipients: # todo address root issues by throwing a real error to catch upstream # fail silently for now to fix time-sensitive SES issue return if not isinstance(html_content, str): html_content = html_content.decode('utf-8') if not text_content: text_content = getattr(settings, 'NO_HTML_EMAIL_MESSAGE', NO_HTML_EMAIL_MESSAGE) elif not isinstance(text_content, str): text_content = text_content.decode('utf-8') headers = {'From': email_from} # From-header if settings.RETURN_PATH_EMAIL: headers['Return-Path'] = settings.RETURN_PATH_EMAIL if messaging_event_id is not None: headers[COMMCARE_MESSAGE_ID_HEADER] = messaging_event_id if settings.SES_CONFIGURATION_SET is not None: headers[SES_CONFIGURATION_SET_HEADER] = settings.SES_CONFIGURATION_SET connection = get_connection() msg = EmailMultiAlternatives(subject, text_content, email_from, filtered_recipients, headers=headers, connection=connection, cc=cc, bcc=bcc) for file in (file_attachments or []): if file: msg.attach(file["title"], file["file_obj"].getvalue(), file["mimetype"]) msg.attach_alternative(html_content, "text/html") try: msg.send() except SMTPDataError as e: # If the SES configuration has not been properly set up, resend the message if ( "Configuration Set does not exist" in repr(e.smtp_error) and SES_CONFIGURATION_SET_HEADER in msg.extra_headers ): del msg.extra_headers[SES_CONFIGURATION_SET_HEADER] msg.send() notify_exception(None, message="SES Configuration Set missing", details={'error': e}) else: raise except SMTPSenderRefused as e: if smtp_exception_skip_list and e.smtp_code in smtp_exception_skip_list: raise e else: error_subject = _('ERROR: Could not send "%(subject)s"') % { 'subject': subject, } if e.smtp_code in LARGE_FILE_SIZE_ERROR_CODES: error_text = _('Could not send email: file size is too large.') else: error_text = e.smtp_error error_text = '%s\n\n%s' % ( error_text, _('Please contact %(support_email)s for assistance.') % { 'support_email': settings.SUPPORT_EMAIL, }, ) error_msg = EmailMultiAlternatives( error_subject, error_text, email_from, filtered_recipients, headers=headers, connection=connection, cc=cc, bcc=bcc, ) error_msg.send()
def post(self, request): try: bill_id_str = request.POST['bill_id'] except KeyError: return HttpResponseBadRequest() company = request.company try: bill_id = bson.ObjectId(bill_id_str) except Exception: return HttpResponseBadRequest() bill = Invoice.objects.get_one({'_id': bill_id, 'payer': company._id}) if bill: if timezone.now( ) > bill.expire_date and bill.status != InvoiceStatusEnum.EXPIRED: bill.status = InvoiceStatusEnum.EXPIRED bill.objects.update( {'_id': bill._id}, {'$set': { 'status': InvoiceStatusEnum.EXPIRED }}) if bill.status == InvoiceStatusEnum.EXPIRED: bill = None if not bill: return HttpResponse(simplejson.dumps({ 'error': True, 'error_message': "Такой счет не найден." }), mimetype='application/javascript') plain_text_template = get_template('mails/send_bill.txt') html_template = get_template('mails/send_bill.html') plain_text = plain_text_template.render(Context({})) html = html_template.render(Context({})) email = request.user.email subject, from_email, to, bcc = 'Счет верификации на Rekvizitka.Ru', settings.EMAIL_HOST_USER, [ email, ], [] msg = EmailMultiAlternatives(subject, plain_text, from_email, to, bcc) msg.attach_alternative(html, "text/html") context = bill_default_context_pdf context['recipient']['name'] = bill.recipient context['recipient']['address'] = bill.address context['recipient'][ 'rekvizitka_link'] = 'http://%s/2A82' % settings.SITE_DOMAIN_NAME context['recipient']['account'] = bill.account context['recipient']['account_name'] = bill.account_name context['recipient']['bank']['name'] = bill.bank_name context['recipient']['bank']['bik'] = bill.bank_bik context['recipient']['bank']['account'] = bill.bank_account context['bill']['number'] = bill.number context['bill']['date'] = bill.create_date.strftime("%d.%m.%Y") context['bill']['position'] = bill.position context['bill']['sum']['in_digits'] = bill.price context['bill']['sum']['in_words'] = summ_words( str(bill.price) + ".00") context['bill']['duration'] = get_duration_text(bill.duration_days) context['payer']['name'] = '' bill_pdf = generate_pdf('static/bill.html', context) if bill_pdf: msg.attach(u'verification_bill.pdf', bill_pdf, 'application/pdf') msg.send() return HttpResponse(simplejson.dumps({'error': False}), mimetype='application/javascript')
def send_application_proposal_mail(cls, data): dataset_model = apps.get_model('datasets.Dataset') conn = get_connection(settings.EMAIL_BACKEND) title = data['title'] img_data = data.get('image') illustrative_graphics = data.get('illustrative_graphics') img_name = cls.slugify( title) if img_data or illustrative_graphics else None if img_data: _data = img_data.split(';base64,')[-1].encode('utf-8') image = MIMEImage(base64.b64decode(_data)) filename = f"{img_name}.{image.get_content_subtype()}" image.add_header('content-disposition', 'attachment', filename=filename) image.add_header('Content-ID', '<app-logo>') if illustrative_graphics: _data = illustrative_graphics.split(';base64,')[-1].encode('utf-8') illustrative_graphics_img = MIMEImage(base64.b64decode(_data)) filename = f'{img_name}_illustrative-graphics.{illustrative_graphics_img.get_content_subtype()}' illustrative_graphics_img.add_header('content-disposition', 'attachment', filename=filename) illustrative_graphics_img.add_header('Content-ID', '<illustrative-graphics>') datasets = dataset_model.objects.filter( id__in=data.get('datasets', [])) data['datasets'] = '\n'.join(ds.frontend_absolute_url for ds in datasets) data['dataset_links'] = '<br />'.join( f"<a href=\"{ds.frontend_absolute_url}\">{ds.title}</a>\n" for ds in datasets) external_datasets = data.get('external_datasets', []) data['external_datasets'] = '\n'.join( f"{eds.get('title', '(nienazwany)')}: {eds.get('url', '(nie podano url)')}\n" for eds in external_datasets) data['external_dataset_links'] = '<br />'.join(( f"{eds.get('title')}: <a href=\"{eds.get('url')}\">{eds.get('url')}</a>\n" if 'url' in eds else eds.get('title') ) for eds in external_datasets) data['host'] = settings.BASE_URL emails = [ config.TESTER_EMAIL ] if settings.DEBUG and config.TESTER_EMAIL else [config.CONTACT_MAIL] html_template = 'applicationproposal' if is_enabled( 'S39_mail_layout.be') else 'propose-application' with translation.override('pl'): msg_plain = render_to_string('mails/propose-application.txt', data) msg_html = render_to_string(f'mails/{html_template}.html', data) mail = EmailMultiAlternatives( 'Zgłoszono propozycję aplikacji {}'.format( title.replace('\n', ' ').replace('\r', '')), msg_plain, from_email=config.NO_REPLY_EMAIL, to=emails, connection=conn) mail.mixed_subtype = 'related' mail.attach_alternative(msg_html, 'text/html') if img_data: mail.attach(image) if illustrative_graphics: mail.attach(illustrative_graphics_img) mail.send()
def send_emails_from_template(to_emails, from_email, subject, markdown_template=None, text_template=None, html_template=None, fail_silently=False, context=None, attachments=None, **kwargs): """Send many emails from single template. Each email address listed in the ``to_emails`` will receive an separate email. :param to_emails: list of email address to send the email to :param from_email: the email address the email will be from :param subject: the subject of the email :param markdown_template: the markdown syntax template to use for the email. If provided, this will generate both the text and html versions of the email. You must have the "markdown" library installed in order to use this. pip install markdown. :param text_template: the template for the text version of the email. This can be omitted if the markdown_template is provided. :param html_template: the template for the html version of the email. This can be omitted if the markdown_template is provided. :param context: the context for the email templates :param attachments: list of additional attachments to add to the email (example: email.mime.image.MIMEImage object). The attachments will be added to each email sent. """ if not to_emails: return if context is None: context = {} if markdown_template: try: from markdown import markdown except ImportError: raise ImportError( 'The application is attempting to send an email by using the ' '"markdown" library, but markdown is not installed. Please ' 'install it. See: ' 'http://pythonhosted.org/Markdown/install.html' ) base_html_template = getattr(settings, 'CORE_BASE_HTML_EMAIL_TEMPLATE', 'django_core/mail/base_email.html') text_content = render_to_string(markdown_template, context) context['email_content'] = markdown(text_content) html_content = render_to_string(base_html_template, context) else: text_content = render_to_string(text_template, context) html_content = render_to_string(html_template, context) emails = [] for email_address in to_emails: email = EmailMultiAlternatives( subject=subject, body=text_content, from_email=from_email, to=[email_address], alternatives=[(html_content, 'text/html')] ) if attachments: email.mixed_subtype = 'related' for attachment in attachments: email.attach(attachment) emails.append(email) connection = mail.get_connection() connection.open() connection.send_messages(emails) connection.close()
def send_mail( template_name, subject, to_addresses, cc=None, bcc=None, from_email=None, **context ): """ Helper for sending templated email :param str template_name: Name of the template to send. There should exist a txt and html version :param str subject: Subject line of the email :param str from_email: From address for email :param list to_addresses: List of addresses to email. If str is provided, wrapped in list :param list cc: List of addresses to carbon copy :param list bcc: List of addresses to blind carbon copy :param str custom_message Custom email message - for use instead of a template :kwargs: Context vars for the email template """ context["base_url"] = BASE_URL # For text version: replace images with [IMAGE] so they're not removed entirely context_plain_text = copy.deepcopy(context) # TODO: use a custom filter rather than striptags to preserve image placeholders in the # custom_email template if template_name == "custom_email" and "custom_message" in context_plain_text: image_scheme = re.compile(r"<img .*?>", re.MULTILINE) context_plain_text["custom_message"] = re.sub( image_scheme, "[IMAGE]", context_plain_text["custom_message"] ) # Render into template text_content = get_template("emails/{}.txt".format(template_name)).render( context_plain_text ) html_content = get_template("emails/{}.html".format(template_name)).render(context) if not isinstance(to_addresses, list): to_addresses = [to_addresses] from_address = from_email or EMAIL_FROM_ADDRESS email = EmailMultiAlternatives( subject, text_content, from_address, to_addresses, cc=cc, bcc=bcc ) # For HTML version: Replace inline images with attachments referenced. See # https://gist.github.com/osantana/833045a89ccbc6fc50c1 for reference inline_scheme = re.compile( r' src="data:image/(?P<subtype>.*?);base64,(?P<path>.*?)" ?', re.MULTILINE ) images_data = [] def repl(match): images_data.append((match.group("subtype"), match.group("path"))) return ' src="cid:image-%05d" ' % (len(images_data),) html_content = re.sub(inline_scheme, repl, html_content) for index, (subtype, data) in enumerate(images_data): image = MIMEImage(base64.b64decode(data), _subtype=subtype) image_id = "image-%05d" % (index + 1) image.add_header("Content-ID", image_id) image.add_header("Content-Disposition", "inline") image.add_header("Filename", image_id + "." + subtype) email.attach(image) email.attach_alternative(html_content, "text/html") email.send() return email
def send_HTML_email(subject, recipient, html_content, text_content=None, cc=None, email_from=settings.DEFAULT_FROM_EMAIL, file_attachments=None, bcc=None, smtp_exception_skip_list=None): recipients = list(recipient) if not isinstance(recipient, str) else [ recipient ] recipients = get_valid_recipients(recipients) if not recipients: # todo address root issues by throwing a real error to catch upstream # fail silently for now to fix time-sensitive SES issue return if not isinstance(html_content, str): html_content = html_content.decode('utf-8') if not text_content: text_content = getattr(settings, 'NO_HTML_EMAIL_MESSAGE', NO_HTML_EMAIL_MESSAGE) elif not isinstance(text_content, str): text_content = text_content.decode('utf-8') from_header = {'From': email_from} # From-header if settings.RETURN_PATH_EMAIL: from_header['Return-Path'] = settings.RETURN_PATH_EMAIL connection = get_connection() msg = EmailMultiAlternatives(subject, text_content, email_from, recipients, headers=from_header, connection=connection, cc=cc, bcc=bcc) for file in (file_attachments or []): if file: msg.attach(file["title"], file["file_obj"].getvalue(), file["mimetype"]) msg.attach_alternative(html_content, "text/html") try: msg.send() except SMTPSenderRefused as e: if smtp_exception_skip_list and e.smtp_code in smtp_exception_skip_list: raise e else: error_subject = _('ERROR: Could not send "%(subject)s"') % { 'subject': subject, } if e.smtp_code in LARGE_FILE_SIZE_ERROR_CODES: error_text = _('Could not send email: file size is too large.') else: error_text = e.smtp_error error_text = '%s\n\n%s' % ( error_text, _('Please contact %(support_email)s for assistance.') % { 'support_email': settings.SUPPORT_EMAIL, }, ) error_msg = EmailMultiAlternatives( error_subject, error_text, email_from, recipients, headers=from_header, connection=connection, cc=cc, bcc=bcc, ) error_msg.send()
def send_HTML_email(subject, recipient, html_content, text_content=None, cc=None, email_from=settings.DEFAULT_FROM_EMAIL, file_attachments=None, bcc=None, ga_track=False, ga_tracking_info=None): recipient = list(recipient) if not isinstance(recipient, basestring) else [recipient] if not text_content: text_content = getattr(settings, 'NO_HTML_EMAIL_MESSAGE', NO_HTML_EMAIL_MESSAGE) # this is a temporary spam-catcher, to be removed after fb#178059 is resolved if '*****@*****.**' in recipient: notify_error("Found an email causing spammy emails to " "[email protected]. Here's the HTML content of email" "\n {}".format(html_content) ) if ga_track and settings.ANALYTICS_IDS.get('GOOGLE_ANALYTICS_API_ID'): ga_data = { 'v': 1, 'tid': settings.ANALYTICS_IDS.get('GOOGLE_ANALYTICS_API_ID'), 'cid': uuid.uuid4().hex, 'dt': subject.encode('utf-8'), 't': 'event', 'ec': 'email' } extra_data = ga_tracking_info if ga_tracking_info else {} ga_data.update(extra_data) post_data = urlencode(ga_data) url = "https://www.google-analytics.com/collect?" + post_data new_content = '<img src="{url}&ea=open"/>\n</body>'.format(url=url) html_content, count = re.subn(r'(.*)</body>', r'\1'+new_content, html_content) assert count != 0, 'Attempted to add tracking to HTML Email with no closing body tag' from_header = {'From': email_from} # From-header connection = get_connection() msg = EmailMultiAlternatives(subject, text_content, email_from, recipient, headers=from_header, connection=connection, cc=cc, bcc=bcc) for file in (file_attachments or []): if file: msg.attach(file["title"], file["file_obj"].getvalue(), file["mimetype"]) msg.attach_alternative(html_content, "text/html") try: msg.send() except SMTPSenderRefused as e: error_subject = _('ERROR: Could not send "%(subject)s"') % { 'subject': subject, } if e.smtp_code == 552: error_text = _('Could not send email: file size is too large.') else: error_text = e.smtp_error error_text = '%s\n\n%s' % ( error_text, _('Please contact %(support_email)s for assistance.') % { 'support_email': settings.SUPPORT_EMAIL, }, ) error_msg = EmailMultiAlternatives( error_subject, error_text, email_from, recipient, headers=from_header, connection=connection, cc=cc, bcc=bcc, ) error_msg.send() if ga_track and settings.ANALYTICS_IDS.get('GOOGLE_ANALYTICS_API_ID'): try: try: requests.get(url + "&ea=send") except SSLError: # if we get an ssl error try without verification requests.get(url + "&ea=send", verify=False) except Exception as e: # never fail hard on analytics logging.exception(u'Unable to send google analytics request for tracked email: {}'.format(e))
def send_emails_from_template(to_emails, from_email, subject, markdown_template=None, text_template=None, html_template=None, fail_silently=False, context=None, attachments=None, **kwargs): """Send many emails from single template. Each email address listed in the ``to_emails`` will receive an separate email. :param to_emails: list of email address to send the email to :param from_email: the email address the email will be from :param subject: the subject of the email :param markdown_template: the markdown syntax template to use for the email. If provided, this will generate both the text and html versions of the email. You must have the "markdown" library installed in order to use this. pip install markdown. :param text_template: the template for the text version of the email. This can be omitted if the markdown_template is provided. :param html_template: the template for the html version of the email. This can be omitted if the markdown_template is provided. :param context: the context for the email templates :param attachments: list of additional attachments to add to the email (example: email.mime.image.MIMEImage object). The attachments will be added to each email sent. """ if not to_emails: return if context is None: context = {} if markdown_template: try: from markdown import markdown except ImportError: raise ImportError( 'The application is attempting to send an email by using the ' '"markdown" library, but markdown is not installed. Please ' 'install it. See: ' 'http://pythonhosted.org/Markdown/install.html') base_html_template = getattr(settings, 'CORE_BASE_HTML_EMAIL_TEMPLATE', 'django_core/mail/base_email.html') text_content = render_to_string(markdown_template, context) context['email_content'] = markdown(text_content) html_content = render_to_string(base_html_template, context) else: text_content = render_to_string(text_template, context) html_content = render_to_string(html_template, context) emails = [] for email_address in to_emails: email = EmailMultiAlternatives(subject=subject, body=text_content, from_email=from_email, to=[email_address], alternatives=[(html_content, 'text/html')]) if attachments: email.mixed_subtype = 'related' for attachment in attachments: email.attach(attachment) emails.append(email) connection = mail.get_connection() connection.open() connection.send_messages(emails) connection.close()
def send_calendar_invite(self): """ Send a calendar entry to the participant """ title, _desc_plain, desc_html = self.get_invite_texts() cal_text = self.get_calendar_entry() # "Parts" used in various formats # part_plain = MIMEText(desc_plain, "plain", 'utf-8') # del(part_plain['MIME-Version']) part_html = MIMEText(desc_html, "html", "utf-8") del part_html["MIME-Version"] # part_cal = MIMEText(cal_text, 'calendar; method=REQUEST', 'utf-8') # del(part_cal['MIME-Version']) # ical_atch = MIMEApplication( # cal_text, # 'ics; charset="UTF-8"; name="%s"' % ("invite.ics"), # ) # del(ical_atch['MIME-Version']) # ical_atch.add_header( # 'Content-Disposition', # 'attachment', # filename='invite.ics', # ) # The "Lotus Notes" fomat # msgAlternative = MIMEMultipart('alternative') # del(msgAlternative['MIME-Version']) # msgAlternative.attach(part_html) # msgAlternative.attach(part_cal) # # msgRelated = MIMEMultipart('related') # del(msgRelated['MIME-Version']) # msgRelated.attach(msgAlternative) # msgAlternative.attach(part_html) # # msgMixed = MIMEMultipart('mixed') # del(msgMixed['MIME-Version']) # msgMixed.attach(msgRelated) # msgMixed.attach(ical_atch) # # msg = EmailMultiAlternatives(subject='test invite', # body=None, # to=['*****@*****.**']) # msg.attach(msgMixed) # # The "Google Calendar" format # msgAlternative = MIMEMultipart('alternative') # del(msgAlternative['MIME-Version']) # msgAlternative.add_header( # 'Content-class', # 'urn:content-classes:calendarmessage', # ) # msgAlternative.attach(part_plain) # msgAlternative.attach(part_html) # msgAlternative.attach(part_cal) # # # Create the message object # msg = EmailMultiAlternatives(subject=title, # body=None, # to=[self.person.email]) # msg.attach(msgAlternative) # msg.attach(ical_atch) # The "Outlook" format from_full = "{0} on behalf of {1} <{2}>".format( settings.ONEEVENT_SITE_BRAND, self.event.owner.get_full_name(), settings.ONEEVENT_CALENDAR_INVITE_FROM, ) reply_to_full = "{0} <{1}>".format( self.event.owner.get_full_name(), self.event.owner.email, ) # Create the message object msg = EmailMultiAlternatives( subject=title, body=None, to=[self.person.email], from_email=from_full, reply_to=[reply_to_full], ) msg.extra_headers[ "Content-class"] = "urn:content-classes:calendarmessage" msg.attach(part_html) filename = "invite.ics" part = MIMEBase("text", "calendar", method="REQUEST", name=filename) part.set_payload(cal_text) encoders.encode_base64(part) part.add_header("Content-Description", filename) part.add_header("Content-class", "urn:content-classes:calendarmessage") part.add_header("Filename", filename) part.add_header("Path", filename) msg.attach(part) print(cal_text) # Send the message return msg.send(fail_silently=False) == 1
def post(self, request): try: bill_id_str = request.POST['bill_id'] except KeyError: return HttpResponseBadRequest() company = request.company try: bill_id = bson.ObjectId(bill_id_str) except Exception: return HttpResponseBadRequest() bill = Invoice.objects.get_one({'_id' : bill_id, 'payer' : company._id}) if bill: if timezone.now() > bill.expire_date and bill.status != InvoiceStatusEnum.EXPIRED: bill.status = InvoiceStatusEnum.EXPIRED bill.objects.update({'_id' : bill._id}, {'$set' : {'status' : InvoiceStatusEnum.EXPIRED}}) if bill.status == InvoiceStatusEnum.EXPIRED: bill = None if not bill: return HttpResponse(simplejson.dumps({'error' : True, 'error_message' : "Такой счет не найден."}), mimetype='application/javascript') plain_text_template = get_template('mails/send_bill.txt') html_template = get_template('mails/send_bill.html') plain_text = plain_text_template.render(Context({})) html = html_template.render(Context({})) email = request.user.email subject, from_email, to, bcc = 'Счет верификации на Rekvizitka.Ru', settings.EMAIL_HOST_USER, [email,], [] msg = EmailMultiAlternatives(subject, plain_text, from_email, to, bcc) msg.attach_alternative(html, "text/html") context=bill_default_context_pdf context['recipient']['name']= bill.recipient context['recipient']['address']=bill.address context['recipient']['rekvizitka_link']='http://%s/2A82' % settings.SITE_DOMAIN_NAME context['recipient']['account']=bill.account context['recipient']['account_name']=bill.account_name context['recipient']['bank']['name']=bill.bank_name context['recipient']['bank']['bik']=bill.bank_bik context['recipient']['bank']['account']=bill.bank_account context['bill']['number'] = bill.number context['bill']['date'] = bill.create_date.strftime("%d.%m.%Y") context['bill']['position']=bill.position context['bill']['sum']['in_digits']=bill.price context['bill']['sum']['in_words']=summ_words(str(bill.price)+".00") context['bill']['duration']=get_duration_text(bill.duration_days) context['payer']['name'] = '' bill_pdf = generate_pdf('static/bill.html', context) if bill_pdf: msg.attach(u'verification_bill.pdf', bill_pdf, 'application/pdf') msg.send() return HttpResponse(simplejson.dumps({'error' : False}), mimetype='application/javascript')