def feedback(request): if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): hostname = request.get_host() time = datetime.datetime.now() if settings.MANAGERS: subject = '%s / Feedback' % hostname message_data = form.cleaned_data.copy() message_data['time'] = time.strftime('%d-%m-%Y, %-1I:%M %p') message = '''From: %(name)s <%(email)s>\n\nType: %(type)s\n\nTime: %(time)s \nText: %(comments)s''' % message_data mail = EmailMultiAlternatives('%s%s' % (settings.EMAIL_SUBJECT_PREFIX, subject), message, message_data['email'], [a[1] for a in settings.MANAGERS], headers = {'Reply-To': message_data['email']}) mail.send(fail_silently=True) feedback = Feedback(time=time, **form.cleaned_data) feedback.save() return HttpResponseRedirect( reverse('feedback_thanks') ) else: form = ContactForm() try: page_info = Page.objects.get(alias='feedback') except Page.DoesNotExist: page_info = {} return render_to_response("feedback/contact.html", {'form': form, 'page_info': page_info}, context_instance=RequestContext(request))
def form_valid(self, form): data = form.cleaned_data email = data['email'] try: user = User.objects.get(email=email) password = User.objects.make_random_password() user.set_password(password) user.save() t = loader.get_template('commerce/mails/recover-password.html') c = Context({ 'host': COMMERCE_URL, 'password': password, }) message = EmailMultiAlternatives( _(u'Password recover'), '', COMMERCE_EMAIL_FROM, [user.email]) message.attach_alternative(t.render(c), 'text/html') message.send() except ObjectDoesNotExist: pass messages.success( self.request, _(u'New password was successfully sent on your email.')) return super(RecoverView, self).form_valid(form)
def send_mail(subject, message, from_email, recipient_list, fail_silently=False, auth_user=None, auth_password=None, connection=None, html_message=None): """ 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. """ 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') return mail.send()
def send(self): try: model_name = ContentType.objects.get_for_model(self.related_object) except: set_log('info', 'The related object has been deleted when trying to send mail to {0}'.format(self.email_addresses)) self.is_sent = True return True emails = self.email_addresses.split(',') sended = [] for email in emails: subject, text, html = getattr(self, '_'.join(['_pack', model_name.name.lower().replace(' ', '_')]))(email) message = EmailMultiAlternatives(subject, text, settings.DEFAULT_FROM_EMAIL, [email]) if html: message.attach_alternative(html, "text/html") try: message.send() except Exception, e: set_log('error', 'Mail Server eror: ' + str(e)) self.email_addresses = ','.join(set(emails) - set(sended)) return False else: sended.append(email) self.mark_sent()
def fixSizes(): from django.core.mail.message import EmailMultiAlternatives from django.template.loader import render_to_string from django.utils.html import strip_tags from rts.models import ReturnedItemDetails, rts_status for item in ReturnedItemDetails.objects.filter(status = rts_status.REFUNDED,isEmailSent=False): from_email = "<*****@*****.**>" from_name = str(FROM_EMAIL_NAME) #to = item.order_item.customer_email to = "*****@*****.**" subject = str(FROM_EMAIL_SUBJECT) html_content = render_to_string('zidaya_return_email_template_1.html', { 'billing_name':item.order_item.billing_name.title(), 'order_date': str(item.order_item.order_date.day).zfill(2)+"."+str(item.order_item.order_date.month).zfill(2)+"."+str(item.order_item.order_date.year), 'order_nr':item.order_item.order_nr, 'paid_price':item.order_item.paid_price, 'refund_reference_number':item.refund_reference_number, 'product_image':"http://static.zidaya.com/p/-"+str(item.order_item.id_catalog_config)[::-1]+"-1-catalog.jpg", 'name':item.order_item.name, 'new_coupon':item.new_coupon, 'sku':item.order_item.sku }) text_content = strip_tags(html_content) msg = EmailMultiAlternatives(subject, text_content, from_name+" "+from_email, [to]) msg.attach_alternative(html_content, "text/html") try: msg.send() item.isEmailSent = True item.save() except: pass
def send_active_email(active_form,user_email): subject,form_email,to = u'数据服务平台-激活邮件','*****@*****.**',user_email text_content = u'数据服务平台-激活邮件' html_content = active_form msg = EmailMultiAlternatives(subject,text_content,form_email,[to]) msg.attach_alternative(html_content, 'text/html') msg.send()
def mail_multiple( subject, message, email_addresses, from_email=settings.ORGANIZERS_EMAIL, cc=None, bcc=None, html_message=None, connection=None, fail_silently=True, ): """ Sends a message to multiple email addresses. Based on django.core.mail.mail_admins() """ for email_address in email_addresses: mail = EmailMultiAlternatives( u"%s%s" % (settings.EMAIL_SUBJECT_PREFIX, subject), message, bcc=bcc, cc=cc, connection=connection, from_email=from_email, to=[email_address], ) if html_message: mail.attach_alternative(html_message, "text/html") mail.send(fail_silently=fail_silently)
def deliver_to(self, user, context, notification, language): to_email = self.get_email(user) context.update({ 'to_email': to_email, }) subject = render_to_string( ( "notifyme/notification_types/%s/email/subject.txt" % notification.identifier, "notifyme/notification_types/generic/email/subject.txt", ), context_instance=context ) body = render_to_string( ( "notifyme/notification_types/%s/email/body.txt" % notification.identifier, "notifyme/notification_types/generic/email/body.txt", ), context_instance=context ) body_html = render_to_string( ( "notifyme/notification_types/%s/email/body.html" % notification.identifier, "notifyme/notification_types/generic/email/body.html", ), context_instance=context ) # send the HTML Email email_msg = EmailMultiAlternatives(subject, body, self.get_from_email(user), [to_email], headers={}) email_msg.attach_alternative(body_html, "text/html") email_msg.send()
def forget_password(self, request): email = request.DATA.get('email', False) # validate posted params errors = {} if not email: errors['email'] = 'Required' pattern = r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)" if not re.match(pattern, email): errors['email'] = 'Please input valid email address.' if not errors: user = User.objects.filter(username=email).first() if user: user_code, created = UserCode.objects.get_or_create(user=user, code=random_key(), is_signup=False) reg_url = settings.DOMAIN + 'api/password_reset/' + user_code.code + '/' plaintext = get_template('pw_reset.txt') htmly = get_template('pw_reset.html') d = Context({'url': reg_url}) subject, from_email, to = 'Password Reset [InAppTranslation]', '*****@*****.**', user.username text_content = plaintext.render(d) html_content = htmly.render(d) msg = EmailMultiAlternatives(subject, text_content, from_email, [to]) msg.attach_alternative(html_content, "text/html") msg.send() return Response({'status': 'success'}) else: errors['email'] = "We can't find any user with the email." return Response(errors, status=status.HTTP_400_BAD_REQUEST)
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_HTML_email(subject, recipient, html_content, text_content=None, cc=None, email_from=None): if not text_content: text_content = getattr(settings, 'NO_HTML_EMAIL_MESSAGE', NO_HTML_EMAIL_MESSAGE) # If you get the return_path header wrong, this may impede mail delivery. It appears that the SMTP server # has to recognize the return_path as being valid for the sending host. If we set it to, say, our SMTP # server, this will always be the case (as the server is explicitly serving the host). if email_from is None: #todo: verify that this is even necessary here since it seems like email_return_path == email_from email_return_path = getattr(settings, 'EMAIL_RETURN_PATH', None) if email_return_path is None: email_return_path = settings.EMAIL_LOGIN email_from = getattr(settings, 'EMAIL_FROM', None) if email_from is None: email_from = email_return_path else: email_return_path = email_from from_header = {'From': email_from} # From-header connection = get_connection() msg = EmailMultiAlternatives(subject, text_content, email_return_path, [recipient], headers=from_header, connection=connection, cc=cc) msg.attach_alternative(html_content, "text/html") msg.send()
def handle(self, *args, **options): while True: last_hour = datetime.datetime.utcnow().replace(tzinfo=utc) - datetime.timedelta(hours=1) profiles = Profile.objects.select_related().filter( user__date_joined__gte=last_hour, user_referrer__profile__enable_email_updates=True, user_referrer__is_active=True, ) for profile in profiles: if not profile.user_referrer.email: continue try: FriendJoinedEmailLog.objects.get(user=profile.user_referrer, user_referred=profile.user) except FriendJoinedEmailLog.DoesNotExist: dict_context = { 'site': self.site, 'referred_profile': profile, 'referring_profile': profile.user_referrer.get_profile(), } email_subject = render_to_string('emails/friend-joined/subject.txt', dict_context).strip() email_txt = render_to_string('emails/friend-joined/message.txt', dict_context) email_html = render_to_string('emails/friend-joined/message.html', dict_context) email = EmailMultiAlternatives( email_subject, email_txt, settings.DEFAULT_FROM_EMAIL, [profile.user_referrer.email,] ) email.attach_alternative(email_html, 'text/html') email.send() FriendJoinedEmailLog.objects.create(user=profile.user_referrer, user_referred=profile.user) self.close_db_connection() time.sleep(600)
def mail_admins_contact(request, subject, message, context, sender): ''' Sends a message to the admins, as defined by the ADMINS setting. ''' weblate.logger.info( 'contact from from %s: %s', sender, subject, ) if not settings.ADMINS: messages.error( request, _('Message could not be sent to administrator!') ) weblate.logger.error( 'ADMINS not configured, can not send message!' ) return mail = EmailMultiAlternatives( u'%s%s' % (settings.EMAIL_SUBJECT_PREFIX, subject % context), message % context, to=[a[1] for a in settings.ADMINS], headers={'Reply-To': sender}, ) mail.send(fail_silently=False) messages.success( request, _('Message has been sent to administrator.') )
def contacto_view(request): info_enviado = False email = '' titulo = '' contenido = '' if request.method == 'POST': formulario = ContactoForm(request.POST) if formulario.is_valid(): info_enviado = True email = formulario.cleaned_data['email'] titulo = formulario.cleaned_data['titulo'] contenido = formulario.cleaned_data['contenido'] #configuracion para enviar el mensaje a GMAIL html_content = 'Informacion recibida <br/> <br/> <h3> ******* Mensaje de %s ******* </h3> <br/> <br/>' \ '<h4>Titulo: %s </h4>' \ '<p>%s</p>' % (email, titulo, contenido) to = '*****@*****.**' msje = EmailMultiAlternatives('Correo de contacto', html_content, '*****@*****.**', [to]) msje.attach_alternative(html_content, 'text/html') msje.send() else: formulario = ContactoForm() ctx = {'enviado': info_enviado, 'email': email, 'titulo': titulo, 'contenido': contenido, 'form': formulario} return render_to_response('contacto.html', ctx, context_instance=RequestContext(request))
def send_mail_account_confirmation(user, code, marketplace): """ Send message to the user to confirm your account """ link = "http://www.%s/buy/confirmemail/%s/" % (marketplace.base_domain , code) subject = "%s Account Confirmation" % marketplace.name text_content = _(""" Hi %(username)s, You recently registered at %(marketplace_name)s. Please confirm your account by following this link: %(link)s Thanks. %(marketplace_name)s Team.""") % {'username': user.username, 'link': link, 'marketplace_name': marketplace.name} msg = EmailMultiAlternatives(subject, text_content, settings.EMAIL_FROM, [user.email, settings.EMAIL_FROM], headers={'X-SMTPAPI': '{\"category\": \"Account Confirmation\"}'}) logging.critical(text_content); try: msg.send() except: logging.exception("failure sending mail")
def execute(self): print >> sys.stdout, 'Executing DeferredNotificationsTask' start = time.time() notifications = Notification.objects.collection.find({'is_sent': False, 'send_date': {'$lte': timezone.now()} }).sort('send_date', -1) for notification in notifications: msg = EmailMultiAlternatives(notification['subject'], notification['message_text'], settings.EMAIL_HOST_USER, [notification['email'], ], []) if len(notification['message_html']): msg.attach_alternative(notification['message_html'], "text/html") # mustdo: implement attaches # attaches = NotificationAttaches.objects.filter(nid=notification) # sys.stdout.write(u' Find %d attache files\n' % attaches.count()) # # if attaches.count(): # for attache in attaches: # sys.stdout.write(u' Attache file: %s\n' % attache.file) # msg.attach_file(attache.file) msg.send() Notification.objects.update({'_id' : notification['_id']}, {'$set' : {'is_sent' : True}}) finish = time.time() run_time = finish - start if run_time > SECONDS_LIMIT: return
def send(self): try: mail = EmailMultiAlternatives(self.subject, self.html_body, self.sender, self.recipients, connection=self.connection) mail.attach_alternative(self.html_body, 'text/html') mail.send() except Exception as e: print "Unexpected error while sending email:", e
def index(request): if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): t = loader.get_template('feedback/emails/body.txt') c = { 'data': form.cleaned_data, 'site': Site.objects.get_current(), 'date': datetime.now(), } subject = render_to_string('feedback/emails/subject.txt', c).replace('\n','') html_body = t.render(Context(c)) text_body = strip_tags(html_body) msg = EmailMultiAlternatives(subject, text_body, form.cleaned_data['email'], settings.MANAGERS) msg.attach_alternative(html_body, "text/html") msg.send() form = ContactForm() messages.success(request, "Ваше сообщение успешно отправлено!") else: form = ContactForm() return render(request, 'feedback/index.html', {'form':form})
def contact_view(request): if request.method == "POST": form1 = ContactoForm(request.POST,request.FILES) form2 = MensajeContactoForm(request.POST,request.FILES) if form1.is_valid() and form2.is_valid() : nombre = form1.cleaned_data['nombre'] apellido = form1.cleaned_data['apellido'] email = form1.cleaned_data['email'] mensaje =form2.cleaned_data['mensaje'] email_context = { 'titulo': 'Has recibido un correo del usuario:', 'usuario': nombre +','+ apellido, 'mensaje': mensaje, } # se renderiza el template con el context email_html = render_to_string('email_contacto.html', email_context) email_text = strip_tags(email_html) correo = EmailMultiAlternatives('Mensaje de Usuario: '+nombre+', '+apellido, email_text, email,['*****@*****.**'],) # se especifica que el contenido es html correo.attach_alternative(email_html, 'text/html') # se envía el correo correo.send() return render_to_response('RecursosDeEmpresa/message_sent.html',context_instance=RequestContext(request)) else: form1 = ContactoForm() form2 = MensajeContactoForm() boton = 'Enviar Solicitud' ctx = {'form1': form1,'form2':form2,'boton':boton} return render_to_response('contacto.html',ctx,context_instance=RequestContext(request))
def send_feedback(request): if request.method == "POST": form = FeedbackForm(request.POST) if form.is_valid(): html_message = render_to_string("email/ask_admin.html", { "user": request.user, "url": form.cleaned_data["url"], "question": form.cleaned_data["question"], }) message = render_to_string("email/ask_admin.txt", { "user": request.user, "url": form.cleaned_data["url"], "question": form.cleaned_data["question"], }) # Using adapted version from Django source code current_site = Site.objects.get(id=settings.SITE_ID) subject = u'[%s] %s asked a question' % (current_site.domain, request.user.get_profile().name) mail = EmailMultiAlternatives(subject, message, FROM_EMAIL, [settings.CONTACT_EMAIL,], headers={"Reply-To": request.user.email}) mail.attach_alternative(html_message, 'text/html') mail.send() # mail_admins("[%s] Message for admins" % current_site.domain, # message, html_message=html_message, headers={'Reply-To': request.user.email}) if request.is_ajax(): return HttpResponse(json.dumps({"success": True}), mimetype="application/json") return HttpResponseRedirect(form.cleaned_data["url"]) raise Http404
def save(self, domain_override=None, subject_template_name='authentication/password_reset_subject.txt', email_template_name='registration/password_reset_email.html', use_https=False, token_generator=default_token_generator, from_email=None, request=None): """ Generates a one-use only link for resetting password and sends to the user. """ for user in self.users_cache: if not domain_override: current_site = get_current_site(request) site_name = current_site.name domain = current_site.domain else: site_name = domain = domain_override c = { 'email': user.email, 'domain': domain, 'site_name': site_name, 'uid': int_to_base36(user.pk), 'user': user, 'token': token_generator.make_token(user), 'protocol': use_https and 'https' or 'http', } subject = loader.render_to_string('authentication/password_reset_subject.txt', c) # Email subject *must not* contain newlines subject = ''.join(subject.splitlines()) message_text = loader.render_to_string('authentication/password_reset_email.txt', c) message_html = loader.render_to_string('authentication/password_reset_email.html', c) msg = EmailMultiAlternatives(subject, message_text, settings.DEFAULT_FROM_EMAIL, [self.user.email]) msg.attach_alternative(message_html, "text/html") msg.send()
def send_mail_with_template( subject, from_email, recipient_list, plaintext_template, html_template, context, fail_silently=False, auth_user=None, auth_password=None, connection=None, headers=None, bcc_list=None, ): connection = connection or get_connection(username=auth_user, password=auth_password, fail_silently=fail_silently) headers = headers or {"Reply-To": from_email} plaintext = get_template(plaintext_template) text_content = plaintext.render(context) msg = EmailMultiAlternatives(subject, text_content, from_email, recipient_list, bcc_list) if html_template is not None: html = get_template(html_template) html_content = html.render(context) msg.attach_alternative(html_content, "text/html") return msg.send()
def mail_admins_contact(request, subject, message, context, sender, to): """Send a message to the admins, as defined by the ADMINS setting.""" LOGGER.info( 'contact form from %s', sender, ) if not to and settings.ADMINS: to = [a[1] for a in settings.ADMINS] elif not settings.ADMINS: messages.error( request, _('Message could not be sent to administrator!') ) LOGGER.error( 'ADMINS not configured, can not send message!' ) return mail = EmailMultiAlternatives( '{0}{1}'.format(settings.EMAIL_SUBJECT_PREFIX, subject % context), message % context, to=to, headers={'Reply-To': sender}, ) mail.send(fail_silently=False) messages.success( request, _('Message has been sent to administrator.') )
def common_send_email(subject, text_template_path, html_template_path, context_data, recipients, from_email=None): """ This method is a common method to send email via the bhane system. """ coupon_obj = context_data['second_chance_obj'] if not from_email: from_email = DEFAULT_FROM_EMAIL #get templates from file system text_raw_content = get_template(text_template_path) try: html_raw_content = get_template(coupon_obj.vendor.email_content.path)#will return absolute path except: html_raw_content = get_template(html_template_path)#else pickup common_vendor_email.html #render the raw data in the template d = Context(context_data) text_content = text_raw_content.render(d) html_content = html_raw_content.render(d) #contstruct the message and send it msg = EmailMultiAlternatives(subject, text_content, from_email, recipients) '''if coupon_obj.image.name: msg.attach_file(coupon_obj.image.path)''' msg.attach_alternative(html_content, "text/html") msg.send()
def send_contact_message(communication_type, sender_username, sender_email, message, fail_silently=False, connection=None): subject = "%s | %s <%s>" % (communication_type.title, sender_username, sender_email) headers = {'Reply-To': sender_email} destination = communication_type.destination if not destination: if not settings.MANAGERS: logger.error('Could not send a contact message because there is no destination email configured neither in the communication type or the MANAGERS setting.') return else: to = [m[1] for m in settings.MANAGERS] else: to = [destination] mail = EmailMultiAlternatives( u'%s%s' % (settings.EMAIL_SUBJECT_PREFIX, subject), message, settings.SERVER_EMAIL, to, connection=connection, headers=headers, ) mail.send(fail_silently=fail_silently)
def send(self, outbound_message): # Here there should be somewhere the contacts # Returns a tuple with the result_of_sending, fatal_error # so False, True means that there was an error sending and you should not try again try: writeitinstance = outbound_message.message.writeitinstance template = writeitinstance.mailit_template except: return False, False author_name = outbound_message.message.author_name context = { 'subject': outbound_message.message.subject, 'content': outbound_message.message.content, 'content_indented': process_content(outbound_message.message.content), 'person': outbound_message.contact.person.name, 'author': author_name, 'writeit_url': writeitinstance.get_absolute_url(), 'message_url': outbound_message.message.get_absolute_url(), 'writeit_name': writeitinstance.name, 'owner_email': writeitinstance.owner.email, } text_content = template.get_content_template().format(**context) html_content = template.content_html_template.format(**escape_dictionary_values(context)) subject = template.subject_template.format(**context) if settings.SEND_ALL_EMAILS_FROM_DEFAULT_FROM_EMAIL: from_email = author_name + " <" + settings.DEFAULT_FROM_EMAIL + ">" else: from_domain = writeitinstance.config.custom_from_domain or settings.DEFAULT_FROM_DOMAIN from_email = ( author_name + " <" + writeitinstance.slug + "+" + outbound_message.outboundmessageidentifier.key + '@' + from_domain + ">" ) # There there should be a try and except looking # for errors and stuff try: to_email = writeitinstance.owner.email if writeitinstance.config.testing_mode else outbound_message.contact.value msg = EmailMultiAlternatives( subject, text_content, from_email, [to_email], connection=writeitinstance.config.get_mail_connection(), ) if html_content: msg.attach_alternative(html_content, "text/html") msg.send(fail_silently=False) log = "Mail sent from %(from)s to %(to)s" log = log % { 'from': from_email, 'to': outbound_message.contact.value, } logging.info(log) except SMTPServerDisconnected, e: return False, False
def send_mail(subject, message, recipient_list, from_email=None, **kwargs): """ Wrapper around Django's EmailMultiAlternatives as done in send_mail(). Custom from_email handling and special Auto-Submitted header. """ if not from_email: if hasattr(settings, 'WAGTAILADMIN_NOTIFICATION_FROM_EMAIL'): from_email = settings.WAGTAILADMIN_NOTIFICATION_FROM_EMAIL elif hasattr(settings, 'DEFAULT_FROM_EMAIL'): from_email = settings.DEFAULT_FROM_EMAIL else: from_email = 'webmaster@localhost' connection = kwargs.get('connection', False) or get_connection( username=kwargs.get('auth_user', None), password=kwargs.get('auth_password', None), fail_silently=kwargs.get('fail_silently', None), ) kwargs = { 'connection': connection, 'headers': { 'Auto-Submitted': 'auto-generated', } } mail = EmailMultiAlternatives(subject, message, from_email, recipient_list, **kwargs) html_message = kwargs.get('html_message', None) if html_message: mail.attach_alternative(html_message, 'text/html') return mail.send()
def send_email(self, prefix): subject_file = 'authemail/%s_subject.txt' % prefix txt_file = 'authemail/%s.txt' % prefix html_file = 'authemail/%s.html' % prefix subject = render_to_string(subject_file).strip() from_email = settings.DEFAULT_EMAIL_FROM to = self.user.email bcc_email = settings.DEFAULT_EMAIL_BCC # Make some context available ctxt = { 'email': self.user.email, 'first_name': self.user.first_name, 'last_name': self.user.last_name, 'code': self.code, 'MEDIA_URL': settings.MEDIA_URL, 'STATIC_URL': settings.STATIC_URL, 'BASE_URL': settings.BASE_URL } text_content = render_to_string(txt_file, ctxt) html_content = render_to_string(html_file, ctxt) msg = EmailMultiAlternatives(subject, text_content, from_email, [to], bcc=[bcc_email]) msg.attach_alternative(html_content, 'text/html') msg.send()
def send_feedback(request): """send feedback.""" if request.method == "POST": form = FeedbackForm(request.POST) if form.is_valid(): html_message = render_to_string( "email/ask_admin.html", {"user": request.user, "url": form.cleaned_data["url"], "question": form.cleaned_data["question"]}, ) message = render_to_string( "email/ask_admin.txt", {"user": request.user, "url": form.cleaned_data["url"], "question": form.cleaned_data["question"]}, ) challenge = challenge_mgr.get_challenge() # Using adapted version from Django source code subject = u"[%s] %s asked a question" % (challenge.competition_name, request.user.get_profile().name) if challenge.email_enabled: mail = EmailMultiAlternatives( subject, message, FROM_EMAIL, [challenge.contact_email], headers={"Reply-To": request.user.email} ) mail.attach_alternative(html_message, "text/html") mail.send() # print "email sent %s" % html_message if request.is_ajax(): return HttpResponse(json.dumps({"success": True}), mimetype="application/json") raise Http404
def check_new_submissions(): """Check the action submission queue and send out notifications to admin when there is new submissions in the queue. algorithm for queue processing: 1. on zero to one transition: send email unless email already sent within N minutes. """ submission_count = ActionMember.objects.filter( action__type="activity", approval_status="pending").count() if submission_count: try: admin = User.objects.get(username=settings.ADMIN_USER) action = Action.objects.get(slug=SETUP_WIZARD_ACTIVITY) reminder = EmailReminder.objects.filter(user=admin, action=action) if not reminder: EmailReminder.objects.create(user=admin, action=action, send_at=datetime.datetime.today(), sent=True) challenge = challenge_mgr.get_challenge() subject = "[%s] %d New Pending Action Submissions" % (challenge.name, submission_count) message = "There are %d new pending action submissions as of %s." % ( submission_count, datetime.datetime.today()) if challenge.email_enabled and challenge.contact_email: print "Sending new submission notification to %s" % challenge.contact_email mail = EmailMultiAlternatives(subject, message, challenge.contact_email, [challenge.contact_email, ]) mail.send() except ObjectDoesNotExist: pass
def sendEmail(subject, add_to, html_content): from django.conf import settings if isinstance(add_to, six.string_types): addr1 = add_to add_to = list() add_to.append(addr1) subject = force_text(subject) if subject.find(settings.EMAIL_SUBJECT_PREFIX) < 0: subject = settings.EMAIL_SUBJECT_PREFIX + subject # send_mail(subject, html_content, settings.EMAIL_HOST_USER, # add_to, fail_silently=False) # text_content = 'This is an important message.' # html_content = '<p>This is an <strong>important</strong> message.</p>' msg = EmailMultiAlternatives(subject, html_content, settings.EMAIL_HOST_USER, add_to) msg.attach_alternative(html_content, "text/html") msg.send()
def payment_automatic(user, card, plan, number_payment): to = user.email data = {'domain_fron': 'app.ezonseller.com', 'url': settings.URL, 'username': user.username, 'msg': 'Payment Confirmation', 'card': card, 'creditCard': card.number_card[-4:], 'plan': plan, 'numberPayment': number_payment } subject, from_email = data['msg'], EMAIL_HOST_USER text_content = render_to_string("email/payment_automatic.html", data) html_content = render_to_string("email/payment_automatic.html", data) send = EmailMultiAlternatives(subject, text_content, from_email, [to], headers={'From': 'Ezonseller <'+from_email+'>', 'Reply-to': 'Ezonseller <'+from_email+'>'}) send.attach_alternative(html_content, "text/html") send.send() return True
def send_multi_format_email(template_prefix, template_ctxt, target_email, request=None): subject_file = 'authemail/%s_subject.txt' % template_prefix txt_file = 'authemail/%s.txt' % template_prefix html_file = 'authemail/%s.html' % template_prefix subject = render_to_string(subject_file, request=request).strip() from_email = settings.EMAIL_FROM to = target_email bcc_email = settings.EMAIL_BCC text_content = render_to_string(txt_file, template_ctxt, request=request) html_content = render_to_string(html_file, template_ctxt, request=request) msg = EmailMultiAlternatives(subject, text_content, from_email, [to], bcc=[bcc_email]) msg.attach_alternative(html_content, 'text/html') msg.send()
def send_email_for_seo_review(course): """ Send email when course is submitted for seo review. Arguments: course (Object): Course object """ txt_template = 'publisher/email/course/seo_review.txt' html_template = 'publisher/email/course/seo_review.html' subject = _('Legal review requested: {title}').format(title=course.title) # pylint: disable=no-member try: legal_team_users = User.objects.filter(groups__name=LEGAL_TEAM_GROUP_NAME) project_coordinator = course.project_coordinator to_addresses = [user.email for user in legal_team_users] from_address = settings.PUBLISHER_FROM_EMAIL course_page_path = reverse('publisher:publisher_course_detail', kwargs={'pk': course.id}) context = { 'course_name': course.title, 'sender_team': _('Course team'), 'recipient_name': _('Legal Team'), 'org_name': course.organizations.all().first().name, 'contact_us_email': project_coordinator.email, 'course_page_url': 'https://{host}{path}'.format( host=Site.objects.get_current().domain.strip('/'), path=course_page_path ) } template = get_template(txt_template) plain_content = template.render(context) template = get_template(html_template) html_content = template.render(context) email_msg = EmailMultiAlternatives( subject, plain_content, from_address, to_addresses ) email_msg.attach_alternative(html_content, 'text/html') email_msg.send() except Exception: # pylint: disable=broad-except logger.exception('Failed to send email notifications for legal review requested of course %s', course.id)
def execute(self): print >> sys.stdout, 'Executing DeferredNotificationsTask' start = time.time() notifications = Notification.objects.collection.find({ 'is_sent': False, 'send_date': { '$lte': timezone.now() } }).sort('send_date', -1) for notification in notifications: msg = EmailMultiAlternatives(notification['subject'], notification['message_text'], settings.EMAIL_HOST_USER, [ notification['email'], ], []) if len(notification['message_html']): msg.attach_alternative(notification['message_html'], "text/html") # mustdo: implement attaches # attaches = NotificationAttaches.objects.filter(nid=notification) # sys.stdout.write(u' Find %d attache files\n' % attaches.count()) # # if attaches.count(): # for attache in attaches: # sys.stdout.write(u' Attache file: %s\n' % attache.file) # msg.attach_file(attache.file) msg.send() Notification.objects.update({'_id': notification['_id']}, {'$set': { 'is_sent': True }}) finish = time.time() run_time = finish - start if run_time > SECONDS_LIMIT: return
def account_summary_emails(): # The period for which the report is to be built datetime_now = datetime.datetime.now(tz=pytz.UTC) date_from = datetime_now - settings.ACCOUNT_SUMMARY_INTERVAL date_to = datetime_now template_html = 'emails/notifications_summary.html' subject = u'PSC Notification Summary' from_email = settings.DEFAULT_FROM_EMAIL # Send reports to all active accounts for account in Account.objects.filter(is_active=True): user_contact_emails = account.user_contact_information.filter( is_active=True).values_list('email', flat=True) account_contact_emails = account.contactinformation_set.values_list( 'email', flat=True) email_to = list(user_contact_emails) + list(account_contact_emails) if not email_to and account.owner.email: # If no additional recipient is specified # the report will be sent to owner account email_to = [account.owner.email, ] if email_to: # Get all account notifications notifications = Notification.objects.filter( Q(user__account=account) | Q(user__owner=account), created_at__range=[date_from, date_to] ).order_by('-created_at') if notifications: context = { 'notifications': notifications, } html_content = render_to_string(template_html, context=context) msg = EmailMultiAlternatives( subject, html_content, from_email, email_to) msg.attach_alternative(html_content, "text/html") msg.send()
def send_email_for_studio_instance_created(course_run): """ Send an email to course team on studio instance creation. Arguments: course_run (CourseRun): CourseRun object """ try: object_path = reverse('publisher:publisher_course_run_detail', kwargs={'pk': course_run.id}) subject = _('Studio instance created') to_addresses = course_run.course.get_group_users_emails() from_address = settings.PUBLISHER_FROM_EMAIL context = { 'course_run': course_run, 'course_run_page_url': 'https://{host}{path}'.format( host=Site.objects.get_current().domain.strip('/'), path=object_path) } txt_template_path = 'publisher/email/studio_instance_created.txt' html_template_path = 'publisher/email/studio_instance_created.html' txt_template = get_template(txt_template_path) plain_content = txt_template.render(context) html_template = get_template(html_template_path) html_content = html_template.render(context) email_msg = EmailMultiAlternatives(subject, plain_content, from_address, to=[settings.PUBLISHER_FROM_EMAIL], bcc=to_addresses) email_msg.attach_alternative(html_content, 'text/html') email_msg.send() except Exception: # pylint: disable=broad-except logger.exception( 'Failed to send email notifications for course_run [%s]', course_run.id)
def task_send_proposal(proposal): urlsafe_token = proposal.generate_token() subject = "Presupuesto" from_email = settings.ADMIN_EMAIL to = proposal.event.customer.email template = loader.get_template("base/email/proposal.html") domain = settings.CATERFULL_BASE_URL context = Context({'token':urlsafe_token,'domain':domain, 'proposal':proposal, 'pidb64':urlsafe_base64_encode(force_bytes(proposal.id))}) html_content = template.render(context) msg = EmailMultiAlternatives(subject, html_content, from_email, [to]) msg.content_subtype = "html" # msg.attach_alternative(html_content, "text/html") proposal_pdf = generate_proposal_pdf(proposal=proposal) msg.attach_file(proposal_pdf.name, 'application/pdf') try: msg.send(fail_silently=False) proposal.has_been_sent() return OK except SMTPException as e: proposal.reset_token() return ERROR
def handle(self, *args, **options): while True: last_hour = datetime.datetime.utcnow().replace( tzinfo=utc) - datetime.timedelta(hours=1) profiles = Profile.objects.select_related().filter( user__date_joined__gte=last_hour, user_referrer__profile__enable_email_updates=True, user_referrer__is_active=True, ) for profile in profiles: if not profile.user_referrer.email: continue try: FriendJoinedEmailLog.objects.get( user=profile.user_referrer, user_referred=profile.user) except FriendJoinedEmailLog.DoesNotExist: dict_context = { 'site': self.site, 'referred_profile': profile, 'referring_profile': profile.user_referrer.get_profile(), } email_subject = render_to_string( 'emails/friend-joined/subject.txt', dict_context).strip() email_txt = render_to_string( 'emails/friend-joined/message.txt', dict_context) email_html = render_to_string( 'emails/friend-joined/message.html', dict_context) email = EmailMultiAlternatives( email_subject, email_txt, settings.DEFAULT_FROM_EMAIL, [ profile.user_referrer.email, ]) email.attach_alternative(email_html, 'text/html') email.send() FriendJoinedEmailLog.objects.create( user=profile.user_referrer, user_referred=profile.user) self.close_db_connection() time.sleep(600)
def mail_managers(subject, message, fail_silently=False, connection=None, html_message=None): """ Sends a message to the managers, as defined by the MANAGERS setting and to the users in managers group.""" emails = _get_managers_mails() if not emails: return mail = EmailMultiAlternatives(u'%s%s' % (settings.EMAIL_SUBJECT_PREFIX, subject), message, settings.SERVER_EMAIL, emails, connection=connection) if html_message: mail.attach_alternative(html_message, 'text/html') mail.send(fail_silently=fail_silently)
def send_message(request): data = { 'name': request.DATA.get('name'), 'email': request.DATA.get('email'), 'msg': request.DATA.get('message') } plaintext = get_template('message.txt') htmly = get_template('message.html') d = Context(data) subject, from_email, to = '%s wrote you a note[InAppTranslation]' % data['email'], '*****@*****.**', \ settings.SUPPORT_EMAIL text_content = plaintext.render(d) html_content = htmly.render(d) msg = EmailMultiAlternatives(subject, text_content, from_email, [to]) msg.attach_alternative(html_content, "text/html") msg.send() return Response({'status': 'success'})
def send_notification_email(self, subject, recipient, template_name): # TODO this could be async to avoid too long api calls in case of mail server issue serializer = TravelMailSerializer(self, context={}) url = 'https://{host}/t2f/edit-travel/{travel_id}/'.format( host=settings.HOST, travel_id=self.id) html_content = render_to_string(template_name, { 'travel': serializer.data, 'url': url }) # TODO what should be used? sender = settings.DEFAULT_FROM_EMAIL msg = EmailMultiAlternatives(subject, '', sender, [recipient]) msg.attach_alternative(html_content, 'text/html') try: msg.send(fail_silently=False) except ValidationError: log.exception(u'Was not able to send the email.')
def send_templated_email(template_code, context, recipients=None): try: email_template = EmailTemplate.objects.get(slug=template_code) except EmailTemplate.DoesNotExist: return c = Context(context) t = Template(email_template.template) message_html = t.render(c) message_clean = strip_tags(message_html) sender = email_template.sender if not recipients: recipients = email_template.recipients recipients = recipients.split(',') mail = EmailMultiAlternatives(email_template.subject, message_html, sender, recipients, headers={'Reply-To': sender}) if message_html != message_clean: mail.attach_alternative(message_html, 'text/html') mail.send(fail_silently=False)
def cancel_subscription(user, plan): try: to = EMAIL_HOST_USER_SUPPORT data = { 'url': settings.URL, 'username': user.username, 'email': user.email, 'plan': plan, 'msg': 'Cancel subscription', } subject, from_email = data['msg'], EMAIL_HOST_USER text_content = render_to_string("email/cancel_subscrition.html", data) html_content = render_to_string("email/cancel_subscrition.html", data) send = EmailMultiAlternatives(subject, text_content, from_email, [to], headers={'From': 'Ezonseller <'+from_email+'>', 'Reply-to': 'Ezonseller <'+from_email+'>'}) send.attach_alternative(html_content, "text/html") send.send() return True except: return False
def password_reset_token_created(sender, instance, reset_password_token, *args, **kwargs): """ Handles password reset tokens When a token is created, an e-mail needs to be sent to the user :param sender: View Class that sent the signal :param instance: View Instance that sent the signal :param reset_password_token: Token Model Object :param args: :param kwargs: :return: """ # send an e-mail to the user context = { 'current_user': reset_password_token.user, 'email': reset_password_token.user.email, 'reset_password_url': "{}?token={}".format(reverse('password_reset:reset-password-request'), reset_password_token.key) } # render email text email_html_message = render_to_string('email/user_reset_password.html', context) email_plaintext_message = render_to_string('email/user_reset_password.txt', context) msg = EmailMultiAlternatives( # title: "Password Reset for {title}".format(title="Some website title"), # message: email_plaintext_message, # from: "*****@*****.**", # to: [reset_password_token.user.email]) msg.attach_alternative(email_html_message, "text/html") msg.send()
def send_email(emails, email_title, email_content): """ 发送邮件接口 :param subject: :param add_to: :param html_content: :return: """ logger = logging.getLogger("third_party") email_addr = list() if isinstance(emails, basestring): email_addr.append(emails.decode('utf8')) elif isinstance(emails, list): email_addr.extend(emails) elif isinstance(emails, tuple): emails_list = list(emails) email_addr.extend(emails_list) if isinstance(email_title, str): email_title = email_title.decode('utf8') if email_title.find(settings.EMAIL_SUBJECT_PREFIX) < 0: email_title = settings.EMAIL_SUBJECT_PREFIX + email_title mulit_email = EmailMultiAlternatives(email_title, email_content, settings.EMAIL_HOST_USER, email_addr) mulit_email.attach_alternative(email_content, "text/html") try: mulit_email.send() logger.debug(u"SMTP Emails:{} Title:{} Content:{} ".format( email_addr, email_title, email_content)) except Exception as e: logger.error( u"SMTP Emails:{} Title:{} Content:{} Exception: {}".format( email_addr, email_title, email_content, e)) raise e
def send_mail(self, subject_template_name, email_template_name, context, from_email, to_email, html_email_template_name=None): """ Send a django.core.mail.EmailMultiAlternatives to `to_email`. """ subject = loader.render_to_string(subject_template_name, context) # Email subject *must not* contain newlines subject = ''.join(subject.splitlines()) body = loader.render_to_string(email_template_name, context) from apps.notifications.mail_server_config import MailServerConfig from apps.common.app_vars import SUPPORT_EMAIL backend = MailServerConfig.make_connection_config() email = EmailMultiAlternatives(subject=subject, body=body, from_email=SUPPORT_EMAIL.val or settings.DEFAULT_FROM_EMAIL, to=[to_email], connection=backend) if html_email_template_name is not None: html_email = loader.render_to_string(html_email_template_name, context) email.attach_alternative(html_email, 'text/html') email.send(fail_silently=False)
def mail_admins_sender(subject, message, sender, fail_silently=False, connection=None, html_message=None): ''' Sends a message to the admins, as defined by the ADMINS setting. ''' if not settings.ADMINS: return mail = EmailMultiAlternatives(u'%s%s' % (settings.EMAIL_SUBJECT_PREFIX, subject), message, sender, [a[1] for a in settings.ADMINS], connection=connection) if html_message: mail.attach_alternative(html_message, 'text/html') mail.send(fail_silently=fail_silently)
def mail_managers_replyable(subject, message, fail_silently=False, connection=None, html_message=None, reply_email=None): """Sends a message to the managers, as defined by the MANAGERS setting.""" if not settings.MANAGERS: return if reply_email: headers = {'Reply-To': reply_email} else: headers = {} mail = EmailMultiAlternatives( '%s%s' % (settings.EMAIL_SUBJECT_PREFIX, subject), message, settings.SERVER_EMAIL, [a[1] for a in settings.MANAGERS], connection=connection, headers=headers) if html_message: mail.attach_alternative(html_message, 'text/html') mail.send(fail_silently=fail_silently)
def save_model(self, request, obj, form, change): obj.save() #Send email for newly assigned incidents if ('assignee' in form.changed_data or change == False) and obj.assignee != None: email_body_tpl = """Hi %(first_name)s, You have been assigned a new incident. To follow up, click this link: https://vincent.berniesanders.com/incidents/%(incident_id)s Reported by: %(reporter_name)s %(reporter_phone)s Type: %(type)s Description: %(description)s""" plain_text_body = email_body_tpl % {'first_name': obj.assignee.first_name, 'description': obj.description, 'type': obj.nature, 'reporter_name': obj.reporter_name, 'reporter_phone': obj.reporter_phone, 'incident_id': obj.id} html_body = linebreaks(urlize(plain_text_body)) email_message = EmailMultiAlternatives(subject='New Vincent Assignment', body=plain_text_body, from_email='Voter Incident Reporting System <*****@*****.**>', to=[obj.assignee.email], reply_to=[obj.creator_email, '*****@*****.**'], headers={'X-Mailgun-Track': False}) email_message.attach_alternative(html_body, "text/html") email_message.send(fail_silently=False)
def mail_managers(subject, message, fail_silently=False, connection=None, html_message=None): """Send a message to the managers, as defined by the MANAGERS setting.""" if not settings.MANAGERS: return if not all( isinstance(a, (list, tuple)) and len(a) == 2 for a in settings.MANAGERS): raise ValueError('The MANAGERS setting must be a list of 2-tuples.') mail = EmailMultiAlternatives( '%s%s' % (settings.EMAIL_SUBJECT_PREFIX, subject), message, settings.SERVER_EMAIL, [a[1] for a in settings.MANAGERS], connection=connection, ) if html_message: mail.attach_alternative(html_message, 'text/html') mail.send(fail_silently=fail_silently)
def contact(request): form = ContactForm(request.POST or None) success = None if request.method == "POST": if form.is_valid(): text_content = u"Email: " + form.cleaned_data[ 'email'] + u". Wiadomość: " + form.cleaned_data['message'] html_content = u"<b>Email:</b> " + form.cleaned_data[ 'email'] + u"<br /> <b>Wiadomość:</b> " + form.cleaned_data[ 'message'] msg = EmailMultiAlternatives( u'Kontakt przez portfolio od: ' + unicode(form.cleaned_data['name']), text_content, form.cleaned_data['email'], ['*****@*****.**']) msg.attach_alternative(html_content, "text/html") msg.send() form = ContactForm() success = "Wiadomość została wysłana." return TemplateResponse(request, 'portfolio/contact.html', { 'form': form, 'success': success })
def mail_admins(subject, message, fail_silently=False, connection=None, html_message=None): """Send a message to the admins, as defined by the ADMINS setting.""" if not settings.ADMINS: return if not all( isinstance(a, (list, tuple)) and len(a) == 2 for a in settings.ADMINS): raise ValueError("The ADMINS setting must be a list of 2-tuples.") 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") mail.send(fail_silently=fail_silently)
def send_email(self, prefix): subject_file = 'authemail/%s_subject.txt' % prefix txt_file = 'authemail/%s.txt' % prefix html_file = 'authemail/%s.html' % prefix subject = render_to_string(subject_file).strip() from_email = settings.DEFAULT_EMAIL_FROM to = self.user.email bcc_email = settings.DEFAULT_EMAIL_BCC # Make some context available ctxt = { 'email': self.user.email, 'first_name': self.user.first_name, 'last_name': self.user.last_name, 'code': self.code } text_content = render_to_string(txt_file, ctxt) html_content = render_to_string(html_file, ctxt) msg = EmailMultiAlternatives(subject, text_content, from_email, [to], bcc=[bcc_email]) msg.attach_alternative(html_content, 'text/html') msg.send()
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 text_content = get_template( "emails/{}.txt".format(template_name)).render(context) 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) email.attach_alternative(html_content, "text/html") email.send()
def send_activation_email(request, user_profile): ctx_dict = { 'host_name': settings.EXTERNAL_HOST_NAME, 'use_https': settings.USE_HTTPS, 'user_name': user_profile.user.username, 'activation_key': user_profile.activation_key, 'expiration_days': settings.ACCOUNT_ACTIVATION_DAYS } subject = render_to_string('ecm/auth/activation_email_subject.txt', ctx_dict, context_instance=Ctx(request)) # Email subject *must not* contain newlines subject = ''.join(subject.splitlines()) txt_content = render_to_string('ecm/auth/activation_email.txt', ctx_dict, Ctx(request)) html_content = render_to_string('ecm/auth/activation_email.html', ctx_dict, Ctx(request)) msg = EmailMultiAlternatives(subject, body=txt_content, to=[user_profile.user.email]) msg.attach_alternative(html_content, "text/html") msg.send()
def SendEmail(request): subject, from_email = 'Violation Message', '*****@*****.**' to = ['*****@*****.**'] address = '' if 'reqAddress' in request.POST: address = request.POST['reqAddress'] if 'emailText' in request.POST: userEmail = request.POST['emailText'] to.append(userEmail) county_code = datamodel.get_county_code_by_address(address) pws_info = datamodel.get_pws_details_by_county(county_code) #Get Template emailTemplate = get_template('email.html') data = Context({ 'pws_info': pws_info }) emailContent = emailTemplate.render(data) msg = EmailMultiAlternatives(subject, 'Sample', from_email, to) msg.attach_alternative(emailContent, "text/html") msg.send() return HttpResponse(str(0), content_type="text/plain")
def send_mail( context, template_name, to_email_list, from_email=settings.DEFAULT_FROM_EMAIL, bcc=None, cc=None, file_path=None, ): """ A static method that takes inputs and sends mail & sms """ if bcc is None: bcc = [] subject = render_to_string("{}{}.txt".format(template_name, "sub"), context) message = EmailMultiAlternatives( subject=subject, body=render_to_string("{}{}.txt".format(template_name, "msg"), context), from_email=from_email, to=to_email_list, bcc=bcc, cc=cc, alternatives=[ ( render_to_string("{}{}.html".format(template_name, "msg"), context), "text/html", ), ], ) # attach file if file_path: message.attach_file(file_path) message.send()
def sender(template_name, to=None, cc=None, bcc=None, attach_files=[], **kvp): try: tmpl = Mail.objects.get(template_name=template_name) except Mail.DoesNotExist: return if to and cc: for v in to: try: cc.remove(v) except ValueError: continue if to and bcc: for v in to: try: bcc.remove(v) except ValueError: continue subject = tmpl.subject.format(**kvp) body = PartialFormatter().format(tmpl.message, **kvp) from_email = DEFAULT_FROM_EMAIL connection = get_connection(fail_silently=False) mail = EmailMultiAlternatives( subject=subject, body=body, from_email=from_email, to=to, cc=cc, bcc=bcc, connection=connection) for attach_file in attach_files: mail.attach_file(attach_file) try: mail.send() except SMTPDataError as e: logger.error(e)
def mail_admins_with_from( subj, msg, from_addr, fail_silently=False, connection=None, html_message=None ): """ mail admins but allow specifying of from address """ if not settings.ADMINS: return # set plain text message msg_raw = strip_tags(msg) mail = EmailMultiAlternatives( f"{settings.EMAIL_SUBJECT_PREFIX}{subj}", msg, from_addr, [a[1] for a in settings.ADMINS], connection=connection, ) # attach html message mail.attach_alternative(msg.replace("\n", "<br />\n"), "text/html") mail.send(fail_silently=fail_silently)