def hernya2(): try: deliveryes = Delivery.objects.filter(delivery_test=False, ) except Delivery.DoesNotExist: deliveryes = None else: for delivery in deliveryes: try: aaa=EmailMiddleDelivery.objects.\ get(delivery=delivery, updated_at__lte=delivery.updated_at, ) print aaa, delivery.updated_at except: email_middle_delivery = EmailMiddleDelivery() email_middle_delivery.delivery = delivery email_middle_delivery.delivery_test_send = False email_middle_delivery.delivery_send = True email_middle_delivery.save() from django.utils.html import strip_tags from django.core.mail import get_connection backend = get_connection(backend='django.core.mail.backends.smtp.EmailBackend', fail_silently=False, ) from django.core.mail import EmailMultiAlternatives from proj.settings import Email_MANAGER msg = EmailMultiAlternatives(subject=delivery.subject, body=strip_tags(delivery.html, ), from_email=u'*****@*****.**', to=[real_email.email, ], connection=backend, ) msg.attach_alternative(content=delivery.html, mimetype="text/html", ) msg.content_subtype = "html" print real_email.email
def render_email(subject, template_prefix, to_email, context, from_email=None): """ Renders a template to an Email object. Check if a html version of the template exists, if so attaches that as an alternative. """ from_email = from_email or settings.DEFAULT_FROM_EMAIL bodies = {} for ext in ['html', 'txt']: try: template_name = '{0}.{1}'.format(template_prefix, ext) bodies[ext] = render_to_string(template_name, context).strip() except TemplateDoesNotExist: pass if not bodies: raise TemplateDoesNotExist( f'A template with the prefix {template_prefix} does not exist.') if 'txt' in bodies: msg = EmailMultiAlternatives(subject, bodies['txt'], from_email, [to_email]) if 'html' in bodies: msg.attach_alternative(bodies['html'], 'text/html') else: msg = EmailMessage(subject, bodies['html'], from_email, [to_email]) msg.content_subtype = 'html' return msg
def email_unread_notifications(timeframe): """ Looks for all unread notifcations and sends each user one email with a summary. Marks any sent notifications as "read". timeframe may be: * 'daily' - only send to users who have the daily email setting * 'weekly' - only send to users who have the weekly email setting * 'all' - send all notifications """ users = db.notifications.find({"read": False}).distinct("uid") for uid in users: profile = UserProfile(id=uid) if profile.settings["email_notifications"] != timeframe and timeframe != 'all': continue notifications = NotificationSet().unread_for_user(uid) try: user = User.objects.get(id=uid) except User.DoesNotExist: continue message_html = render_to_string("email/notifications_email.html", { "notifications": notifications, "recipient": user.first_name }) #message_text = util.strip_tags(message_html) subject = "New Activity on Sefaria from %s" % notifications.actors_string() from_email = "The Sefaria Project <*****@*****.**>" to = user.email msg = EmailMultiAlternatives(subject, message_html, from_email, [to]) msg.content_subtype = "html" # Main content is now text/html #msg.attach_alternative(message_text, "text/plain") msg.send() notifications.mark_read(via="email")
def validate_new_user_by_email(request, user): tpl_email_subject = 'accounts/activation_email_subject.html' tpl_email_body = 'accounts/activation_email_body.html' website_domain = request.META['SERVER_NAME'] context_subject = {'website_domain': website_domain} subject = render_to_string(tpl_email_subject, context_subject) email_subject = ''.join(subject.splitlines()) token_manager = TokenManager() context_body = { 'protocol': 'https' if request.is_secure() else 'http', 'website_domain': website_domain, 'uuid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': token_manager.generate(user), } email_body = render_to_string(tpl_email_body, context_body) email_from = settings.DEFAULT_FROM_EMAIL email_to = [user.email] msg = EmailMultiAlternatives(email_subject, email_body, email_from, email_to) msg.content_subtype = "html" msg.send()
def send_email_extended(title, to_list=[], cc_list=[], bcc_list=[], email_words_dict={}, request='', attachment=''): try: template_obj = Emailtemplates.objects.get(title=title) if template_obj.is_active: if not to_list: to_list = str(template_obj.to_list).split(',') if not cc_list: cc_list = str(template_obj.cc_list).split(',') if not bcc_list: bcc_list = str(template_obj.bcc_list).split(',') body = str(template_obj.description) from_email = extractTLDfromHost(str(template_obj.from_email), '[DOMAIN]', 'email_sender', request) subject = template_obj.subject subject = evariableReplace(subject, email_words_dict) email_text = evariableReplace(body, email_words_dict) # from_email = '*****@*****.**' msg = EmailMultiAlternatives(subject, email_text, from_email, to=to_list,cc=cc_list, bcc=bcc_list) if attachment: msg.attach(attachment['title'], attachment['file'] , attachment['type']) msg.content_subtype = "html" msg.send() if email_words_dict: template_obj.placeholders = '\n'.join([k for k in email_words_dict.keys()]) template_obj.save() except Exception,ex: print traceback.print_exc(5) print str(ex)
def contact(request): if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): fromemail = form.cleaned_data['from_email'] header = form.cleaned_data['subject'] to = DEFAULT_ADMIN_EMAIL_LIST content = form.cleaned_data['content'] msg = EmailMultiAlternatives(header, content, fromemail, to) msg.content_subtype = "html" msg.send() return HttpResponseRedirect('/virtual/confirm/?h=success&t=Email Sent!&c=We will try to come back to you ASAP! &b1=main&b2=console') else: if request.user.is_authenticated(): init_data = {'from_email':request.user.email} form = ContactForm(initial=init_data) else: form = ContactForm() args = {} args.update(csrf(request)) args['contactform'] = form args['user'] = request.user return render_to_response('contact_form.html', args)
def send_mail(): subject, from_email, to = 'hello', 'im22ic()@163.com', '*****@*****.**' text_content = 'This is an important message.' html_content = '<p>This is an <strong>important</strong> message.</p>' msg = EmailMultiAlternatives(subject, text_content, from_email, [to]) msg.attach_alternative(html_content, "text/html") msg.send() # msg.content_subtype = "text" msg.content_subtype = "html" # Main content is now text/html msg.send() # with get_connection( # backend='demz.settings.backend_163' # ) as connection: # EmailMessage( # 'subject1', 'body1', '*****@*****.**', ['*****@*****.**'], # connection=connection, # ).send() with get_connection(host='smtp.163.com', username='******', password='******') as connection: EmailMessage( 'subject1', 'body1', '*****@*****.**', ['*****@*****.**'], connection=connection, ).send()
def notify_student(sender, instance, created, **kwargs): '''Оповещает студента о добавлении нового объявления.''' if created: signer = Signer() if ALLOWED_HOSTS: host = 'http://' + ALLOWED_HOSTS[0] + '/accounts/profile/' + str( instance.pk) else: host = 'http://localhost:8000/accounts/profile/' + str(instance.pk) subject = 'Додане нове оголошення' html_message = '<p>Для вашої групи було додано нове оголошення.</p>' \ '<p>Для того, щоб його подивитись, перейдіть за посиланням: <br\>' \ '<a href="%s">%s</a></p> ' \ '<p>З повагою, адміністрація сайту Teach&Study</p> ' \ % (host, host) admin = AdvUser.objects.filter(username='******') email = '' for a in admin: email = a.email from_addr = email students = AdvUser.objects.filter(group=instance.group) students_email = [] for s in students: if s.email not in students_email: students_email.append(s.email) for e in students_email: recipient_list = (e, ) msg = EmailMultiAlternatives(subject, html_message, from_addr, recipient_list) msg.content_subtype = "html" # Main content is now text/html msg.send()
def adjust_stock(sender, instance, **kwargs): if not instance.active: #Decrement stock counts orders = BookOrder.objects.filter(cart=instance) for order in orders: book = order.book book.stock -= order.quantity book.save() #Send thank you email subject = 'Thank you for Shopping with Mystery Books' from_email = '*****@*****.**' to_email = {instance.user.email} email_context = Context({ 'username': instance.user.username, 'orders': orders }) text_email = render_to_string('email/purchase_email.txt', email_context) html_email = render_to_string('email/purchase_email.html', email_context) msg = EmailMultiAlternatives(subject, text_email, from_email, to_email) msg.attach_alternative(html_email, 'text/html') msg.content_subtype = 'html' msg.send()
def send_activation_email(activation): user = activation.user email = user.email first_name = user.first_name last_name = user.last_name email_template = get_template('activation/email.html') email_content = email_template.render({ 'first_name': first_name, 'last_name': last_name, 'availability': { 'unit': AVAILABILITY_UNIT, 'value': AVAILABILITY_VALUE }, 'activation_url': '{HOST}{ACTIVATION_ROUTE}'.format( HOST=Site.objects.get_current().domain, ACTIVATION_ROUTE=reverse('activation:activate', args=[activation.token])) }) mail = EmailMultiAlternatives('Activate your account', email_content, settings.EMAIL_HOST_USER, [email]) mail.content_subtype = 'html' mail.send()
def register(request): serializer = UserCreateSerializer(data=request.data) if not serializer.is_valid(): return response.Response(serializer.errors, status.HTTP_400_BAD_REQUEST) user = serializer.save() user.is_active = False user.save() current_site = get_current_site(request) mail_subject = 'Activate your account' to_email = user.email message = render_to_string( 'confirmation.html', { 'user': user, 'domain': current_site, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user) }) email = EmailMultiAlternatives(mail_subject, message, settings.EMAIL_HOST_USER, to=[to_email]) email.content_subtype = 'html' email.send(fail_silently=False) return response.Response('Email was send for confirmation', status.HTTP_201_CREATED)
def regist(request): if request.method == 'POST': name = request.POST.get('name') password = request.POST.get('password') # user = BookUser.objects.create_user(username=name, password=password) try: user = BookUser.objects.create_user(username=name, password=password) user.is_active = False user.save() except: user = None if user: email = request.POST.get('email') recvlist = [email] try: msg = EmailMultiAlternatives( '测试2', "<p><a href='http://127.0.0.1:8000/booktest2/active/%s'>点击</a></p>" % (user.id, ), settings.EMAIL_HOST_USER, recvlist) msg.content_subtype = 'html' msg.send() print('成功') # send_mail('测试邮件','这是一个测试邮件', settings.EMAIL_HOST_USER, recvlist) except Exception as a: print(a) return redirect(reverse('booktest2:login')) else: return render(request, 'booktest2/login.html', {'errors': '注册失败'})
def render_mail(self, template_prefix, email, context): """ Renders an e-mail to `email`. `template_prefix` identifies the e-mail that is to be sent, e.g. "account/email/email_confirmation" """ to = [email] if isinstance(email, str) else email subject = render_to_string("{0}_subject.txt".format(template_prefix), context) # remove superfluous line breaks subject = " ".join(subject.splitlines()).strip() subject = self.format_email_subject(subject) from_email = self.get_from_email() bodies = {} for ext in ["html", "txt"]: try: template_name = "{0}_message.{1}".format(template_prefix, ext) bodies[ext] = render_to_string( template_name, context, self.request, ).strip() except TemplateDoesNotExist: if ext == "txt" and not bodies: # We need at least one body raise if "txt" in bodies: msg = EmailMultiAlternatives(subject, bodies["txt"], from_email, to) if "html" in bodies: msg.attach_alternative(bodies["html"], "text/html") else: msg = EmailMessage(subject, bodies["html"], from_email, to) msg.content_subtype = "html" # Main content is now text/html return msg
def enviarContacto(request): """ Funcion: "enviarContacto" Descripcion: Esta funcion permite al usuario de la pagina enviar los datos que ingreso en el formulario de contactenos del sitio web. Fecha de Creacion: Julio 06/2016 Fecha de Modificacion: Julio 23/2016 """ if (request.method == 'POST'): """nombre,email,telefono,asunto""" nombre = request.POST.get('nombre', None) asunto = "Infomacion de contacto de" + " " + nombre from_email = request.POST.get('email', None) to_email=settings.EMAIL_HOST_USER telefono = request.POST.get('telefono', None) contenido_mensaje = request.POST.get('mensaje', None) if asunto and contenido_mensaje and from_email: try: titulo = '<h2>Formulario de Contáctenos</h2><br>' c_nombre = '<p ><strong>Nombre: </strong>' + nombre c_email = '</p><br><p><strong>Email: </strong>' + from_email c_telefono ='</p><br><p><strong>Teléfono: </strong>' + telefono c_mensaje = '</p><br><p><strong>Mensaje: </strong>' + contenido_mensaje + '</p>' html_content = titulo + c_nombre + c_email + c_telefono + c_mensaje msg = EmailMultiAlternatives(asunto, html_content, from_email, [to_email]) msg.content_subtype = "html" msg.send() return HttpResponseRedirect('/contacto/') except BadHeaderError: return HttpResponse('Invalid header found.') return HttpResponseRedirect('/contact/thanks/') else: return HttpResponse('Make sure all fields are entered and valid.')
def send_mail(self, template_prefix, email, context): """ Sends an e-mail to `email`. `template_prefix` identifies the e-mail that is to be sent, e.g. "account/email/email_confirmation" """ subject = render_to_string('{0}_subject.txt'.format(template_prefix), context) # remove superfluous line breaks subject = " ".join(subject.splitlines()).strip() subject = self.format_email_subject(subject) bodies = {} for ext in ['html', 'txt']: try: template_name = '{0}_message.{1}'.format(template_prefix, ext) bodies[ext] = render_to_string(template_name, context).strip() except TemplateDoesNotExist: if ext == 'txt' and not bodies: # We need at least one body raise if 'txt' in bodies: msg = EmailMultiAlternatives(subject, bodies['txt'], settings.DEFAULT_FROM_EMAIL, [email]) if 'html' in bodies: msg.attach_alternative(bodies['html'], 'text/html') else: msg = EmailMessage(subject, bodies['html'], settings.DEFAULT_FROM_EMAIL, [email]) msg.content_subtype = 'html' # Main content is now text/html msg.send()
def email_unaccredited(task, pk_coh, pks_coe, pks_mcoe): from .models import ( CampusOnlineHolding, CampusOnlineEntry, ManualCampusOnlineEntry, ) coh = CampusOnlineHolding.objects.get(pk=pk_coh) if pks_coe: coes = CampusOnlineEntry.objects.filter(pk__in=pks_coe) else: coes = CampusOnlineEntry.objects.empty() if pks_mcoe: mcoes = ManualCampusOnlineEntry.objects.filter(pk__in=pks_mcoe) else: mcoes = ManualCampusOnlineEntry.objects.empty() logger.info(f"Sending mail for {coh}") context = {"coh": coh, "coes": coes, "mcoes": mcoes} msg = EmailMultiAlternatives( _(f"External attendees for {coh.course_group_termi.coursegroup}"), render_to_string("attendance/mail/external_attendees.txt", context), settings.DEFAULT_FROM_EMAIL, [coh.course_group_term.person.email], ) msg.attach_alternative( render_to_string("attendance/mail/external_attendees.html", context), "text/html", ) msg.content_subtype = "html" msg.send()
def comprar(request): filter = request.GET['filter'] producto=perfume.objects.get(id=filter) if request.method == 'POST': validator = FormContacto(request.POST) validator.required = ['name', 'email', 'telefono', 'direccion'] if validator.is_valid(): htmly = get_template('mailCompra.html') name = request.POST['name'] from_email = request.POST['email'] telefono = request.POST['telefono'] direccion = request.POST['direccion'] producto = request.POST['producto'] ast = "Venta Perfumes Pink/826" precio = request.POST['precio'] body = render_to_string('mailCompra.html',{'name':name,'producto':producto,'direccion':direccion, 'from_email':from_email,'telefono':telefono, 'precio':precio}) msg = EmailMultiAlternatives(ast, body , from_email , [ settings.EMAIL_HOST_USER]) msg.content_subtype = "html" msg.send() return render_to_response('compraExitosa.html', {'success': True, 'error':validator.getMessage()}, context_instance = RequestContext(request)) else: return render_to_response('comprar.html', {'error': validator.getMessage()}, context_instance=RequestContext(request)) return render_to_response('comprar.html', {'producto':producto, 'filtro': filter}, context_instance = RequestContext(request))
def home(request): send_to = request.POST["email_to"] message = request.POST["email_body"] attach = request.FILES['documents'] #hdr = Emailheader.objects.last() #print(hdr.img) #fdr = Emailfooter.objects.all() subject, from_email, to = 'hello', '*****@*****.**', send_to text_content = 'This is an important message.' html_content = render_to_string("cotrav_email_template.html") msg = EmailMultiAlternatives(subject, text_content, from_email, [to]) msg.content_subtype = "html" msg.attach_alternative(html_content, "text/html") msg.attach(attach.name, attach.read(), attach.content_type) msg.send() #res = msg.send() return render("cotrav_email_template.html")
def handle(self, *args, **options): count = 0 skaters = Skater.objects.filter(registration_completed__isnull=True) #skaters = Skater.objects.filter(pk=1) for skater in skaters: html = render_to_string('emails/pre-reg-reminder.html', { 'skater' : skater, 'skater_short_name': skater.get_short_name(), } ) msg = EmailMultiAlternatives( "Reminder - Mad Wreckin' Dolls Fall 2016 Registration", html, settings.FROM_EMAIL, [ skater.email ], [ settings.FROM_EMAIL ], headers = { 'Reply-To' : settings.FROM_EMAIL, 'CC' : "*****@*****.**", 'Content-Type' : 'text/html' }, ) msg.content_subtype = "html" msg.send(fail_silently = False) self.stdout.write( str(count) + " OK! " + skater.email ) count = count + 1
def send_email(request): if request.method == 'POST': try: from django.core.mail import EmailMultiAlternatives behalf = request.POST['behalf'] to = request.POST['to'] cc = request.POST['cc'] bcc = request.POST['bcc'] subject = request.POST['subject'] body = request.POST['body'] if hasattr(settings, 'REPLY_TO'): reply_to = {'Reply-To': settings.REPLY_TO, 'Return-Path': settings.REPLY_TO} else: reply_to = {} e = EmailMultiAlternatives( subject=subject, from_email=behalf, to=to.split(';'), cc=cc.split(';'), bcc=bcc.split(';'), headers=reply_to ) e.attach_alternative(markdown2.markdown(body, extras=["link-patterns", "tables"], link_patterns=registry.link_patterns(request), safe_mode=True), 'text/html') e.content_subtype = 'html' e.send() return HttpResponse(dumps({'status': 'ok'}), content_type="application/json") except Exception, e: return HttpResponse(dumps({'status': 'ko', 'error': str(e)}), content_type="application/json")
def index(request): if request.POST: if 'sendEmail' in request.POST: fromemail = request.user.email header = request.POST['subject'] to = request.POST['emailto'].split(',') content = request.POST['content'] msg = EmailMultiAlternatives(header, content, fromemail, to) msg.content_subtype = "html" msg.send() return HttpResponseRedirect('/dashboard/confirm/?h=success&t=Email Sent! &b1=back&b2=dashboard') else: if is_guest(request.user): objs = Patient.objects.filter(visible_to=1).order_by('DB_ID') marked = Patient.objects.filter(visible_to=1).filter(tagged=True).order_by('DB_ID') else: objs = Patient.objects.filter(visible_to=2).order_by('DB_ID')#(surgeon__iexact=u'刘忠军')#request.user.username).order_by('DB_ID') marked = Patient.objects.filter(visible_to=2).filter(tagged=True).order_by('DB_ID')#(surgeon__iexact=u'刘忠军')#request.user.username).order_by('DB_ID') args = {} args.update(csrf(request)) args['user'] = request.user args['objs'] = objs args['marked'] = marked args['banner'] = request.GET.get('banner', '').split('_') return render_to_response('consoleView/account.html',args)
def send_enrollment_notification(user, transit): """ Sends an email notification to the person who submitted the transit subsidy request. @param user: the person who requested the subsidy @param transit: L{TransitSubsidy} the transit subsidy claim object """ _sender = SENDER _subject = 'Transit Subsidy Program: Thank You for Beginning Your Enrollment' message = Template(""" <style>html,p{font-family: arial, helvetica}</style> <p>Dear {{user.first_name}},</p> <p>Thank you for your enrollment in the Transit Subsidy Program!</p> <p>You submitted a Transit Subsidy request on {{ transit.timestamp }} for ${{ transit.amount }} per month.</p> """) ctx = Context({'user':user,'transit':transit}) # send_mail('Transit Subsidy Request Confirmation', message.render(ctx), sender, [user.email]) subject, from_email, to = _subject, _sender, user.email text_content = message.render(ctx) html_content = message.render(ctx) e = EmailMultiAlternatives(subject, html_content, from_email, [to]) e.attach_alternative(html_content, "text/html") e.content_subtype = "html" e.send()
def handle(self, *args, **options): from apps.authModel.models import Email emails = Email.objects.all() i = 0; n = 1 email_content = '' for email in emails: if i > 10: from django.core.mail import get_connection backend = get_connection(backend='django.core.mail.backends.smtp.EmailBackend', fail_silently=False, ) from django.core.mail import EmailMultiAlternatives msg = EmailMultiAlternatives(subject="Email's № %d" % n, body=email_content, from_email=u'*****@*****.**', to=[u'*****@*****.**', ], connection=backend, ) msg.content_subtype = "html" msg.send(fail_silently=False, ) n += 1 print n email_content = '' print email_content i = 0 else: i += 1 print i email_content += '%s, ' % email.email
def send_withdrawl_notification(user): """ Sends an email notification to the person who requested to be withdrawn from the program. @param user: the person who requested the subsidy """ _sender = SENDER _subject = 'Transit Subsidy Program: Thank You for Beginning Your Enrollment' message = Template(""" <style>html,p{font-family: arial, helvetica}</style> <p>Dear {{user.first_name}},</p> <p>You have been withdrawn from the Transit Subsidy Program on {{ transit.timestamp }}.</p> <p>This will be reflected in the next cycle. Also, if you need to re-enroll, please visit the enrollment application again. </p> """) ctx = Context({'user':user}) subject, from_email, to = _subject, _sender, user.email text_content = message.render(ctx) html_content = message.render(ctx) e = EmailMultiAlternatives(subject, html_content, from_email, [to]) e.attach_alternative(html_content, "text/html") e.content_subtype = "html" e.send()
def send_message(self, message): assert message.type == message.TYPES.OUTBOUND assert message.processed is None kwargs = {} kwargs[u'connection'] = self.connection kwargs[u'subject'] = message.subject kwargs[u'from_email'] = message.from_formatted kwargs[u'to'] = (r.formatted for r in message.recipients_to) kwargs[u'cc'] = (r.formatted for r in message.recipients_cc) kwargs[u'bcc'] = (r.formatted for r in message.recipients_bcc) kwargs[u'attachments'] = ((a.name, a.content, a.content_type) for a in message.attachments) kwargs[u'headers'] = message.headers if message.text and message.html: msg = EmailMultiAlternatives(body=message.text, **kwargs) msg.attach_alternative(message.html, u'text/html') elif message.html: msg = EmailMessage(body=message.html, **kwargs) msg.content_subtype = u'html' else: msg = EmailMessage(body=message.text, **kwargs) msg.send() for recipient in message.recipients: recipient.status = recipient.STATUSES.SENT recipient.save(update_fields=[u'status'])
def Contactenos(request): error = False if request.method == 'POST': c = Contacto() c.mensaje = request.POST['message'] c.nombre = request.POST['name'] c.correo = request.POST['email'] c.save() body = render_to_string('email.html', { 'nombre': c.nombre , 'email':c.correo , 'mensaje':c.mensaje }) asunto = "Contacto con Crecimiento y Desarrollo" correo ='*****@*****.**' msg = EmailMultiAlternatives(asunto, body, EMAIL_HOST_USER, [ correo ] ) msg.content_subtype = "html" msg.send() return render_to_response('Contacto.html', {'success': True } , context_instance = RequestContext(request)) else: return render_to_response('Contacto.html' , context_instance = RequestContext(request))
def send_email(request): if request.method == 'POST': try: from django.core.mail import EmailMultiAlternatives behalf = request.POST['behalf'] to = request.POST['to'] cc = request.POST['cc'] bcc = request.POST['bcc'] subject = request.POST['subject'] body = request.POST['body'] if hasattr(settings, 'REPLY_TO'): reply_to = {'Reply-To': settings.REPLY_TO, 'Return-Path': settings.REPLY_TO} else: reply_to = {} e = EmailMultiAlternatives( subject=subject, from_email=behalf, to=to.split(';'), cc=cc.split(';'), bcc=bcc.split(';'), headers=reply_to ) e.attach_alternative(body, 'text/html') e.content_subtype = 'html' e.send() return HttpResponse(dumps({'status': 'ok'}), content_type="application/json") except Exception, e: return HttpResponse(dumps({'status': 'ko', 'error': str(e)}), content_type="application/json")
def reset_password(self, mail): userlikees = User.objects.get(email__iexact=mail) if userlikees: hash = settings.HASH_SALT + userlikees.email token = hashlib.md5(hash).hexdigest() # Contruccion del link de validacion link = settings.TEMPLATE_DOMAIN + 'accounts/remember/?token=' + token + '&username='******'users/mail-recover-password.html', { 'user': userlikees, 'link': link, 'TEMPLATE_DOMAIN': settings.TEMPLATE_DOMAIN }) m = EmailMultiAlternatives(subject, msg, fro, [mail]) m.content_subtype = "html" m.send() # Activamos el user por si acaso no esta activado userlikees.is_active = 1 userlikees.save()
def _reset_password(error_message=''): ''' subfunction used to reset password ''' if request.method == "POST" and request.POST['reset_pass']: if not request.POST['reset_email']: error_message = 'Email field are empty.' else: associated_users= User.objects.filter(Q(email=request.POST['reset_email'])|Q(username=request.POST['reset_email'])) if associated_users.exists(): for user in associated_users: email_temp_data = Context({ 'email': user.email, 'domain': request.META['HTTP_HOST'], 'site_name': '127.0.0.2:8000', 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'time': urlsafe_base64_encode(force_bytes(datetime.now())), 'user': user, 'token': default_token_generator.make_token(user), 'protocol': 'http', }) text_subject = get_template('chtor_admin/_res_/reset_subject.txt').render() html_content = get_template('chtor_admin/_res_/reset_email.html').render(email_temp_data) msg = EmailMultiAlternatives(text_subject, html_content, '*****@*****.**', [request.POST['reset_email']]) msg.content_subtype = "html" msg.send() messages.error(request, error_message) return render(request, 'chtor_admin/reset_password_done.html', { 'email': user.email }) else: messages.error(request, 'This username does not exist in the system.') return render(request, 'chtor_admin/reset_password.html') # send_mail('Subject here', 'Here is the message.', '*****@*****.**', [request.POST['reset_email']], fail_silently=False) messages.error(request, error_message) return render(request, 'chtor_admin/reset_password.html')
def sendMail(expert, expert_email, project_list): print(expert_email) email_project_str = '' for project in project_list: email_project_str = email_project_str + project['name'] + '<br>' accept_url = '180.76.111.16:8003/expert?email=%s&code=%s' % ( expert_email, expert['code']) msg = EmailMultiAlternatives( 'T2-中年魔法兄贵的专家邀请邮件', ''' %s,你好。<br> 是否要参加本届比赛的评审?<br> 需要评审的参赛作品如下:<br> %s <br> 接受评审请点击以下链接或复制到浏览器打开<br> <a href="%s">%s</a><br> 如不想参与评审请忽略此邮件<br> ''' % (expert['name'], email_project_str, accept_url, accept_url), '*****@*****.**', [expert_email], ) msg.content_subtype = 'html' try: msg.send() print('send %s email success' % expert['name']) except: print('send %s email fail' % expert['name'])
def form_valid(self, form): """Method trigered when form is valid. It assigns random confirmation code to user object.self Args: form: valid registartion form object Returns: Django http redirect object to success url """ user = form.save() user.confirmation_code = code_generator() user.save() messages.info(self.request, "Thank you for registartion. We sent " "you an email with confirmation link.") subject = "Account activation" from_mail = "sh-miR designer <*****@*****.**>" to = [user.email] html_content = u"""<html>Click on the link to activate your account: <a href="http://{0}{1}"> {0}{1}</a></html> """.format( self.request.get_host(), reverse('accounts:confirm', kwargs={'code': user.confirmation_code}) ) msg = EmailMultiAlternatives(subject, html_content, from_mail, to) msg.content_subtype = 'html' msg.send() return redirect(self.success_url)
def send_email(subject: str, content: str, domain: str, to_email: list): subject = subject content = content sender = email_config.values()[0]["email"] # to_email.append(settings.EMAIL_HOST_USER) receiver = to_email msg = EmailMultiAlternatives(subject, content, sender, receiver) msg.content_subtype = "html" # 证书位置 ssl_key_file = os.path.join(CERT_DIR, domain, domain + ".key") ssl_cert_file = os.path.join(CERT_DIR, domain, "fullchain.cer") # 添加附件 if os.path.isfile(ssl_key_file) and os.path.isfile(ssl_cert_file): # 复制一份证书链文件,加上域名作为标识 new_ssl_cert_file = os.path.join(CERT_DIR, domain, domain + ".fullchain.cer") shutil.copy(ssl_cert_file, new_ssl_cert_file) msg.attach_file(ssl_key_file) msg.attach_file(new_ssl_cert_file) msg.send() log.info("Email was successfully sent to {}".format(receiver))
def provision(request, product_code): pax = list() result_dict = dict() session = request.session result_dict['hotel'] = session['hotel_name'] result_dict['destination'] = session['destination'] pax_generator = xrange(int(request.session['pax'])) result = book_processor.provision(product_code) if request.method == 'POST': name = request.POST.getlist('name') for name in name: name_list = name.split() last_name = name_list[-1] name_list.pop() first_name = ' '.join(name_list) pax.append('1,{},{},adult'.format(first_name, last_name)) book_result = book_processor.book(result['code'], {'name': pax}) if book_result['status'] == 'succeeded': bookings = book_processor.bookings(book_result['code']) request.session['book_code'] = book_result['code'] room = book_result['confirmation_numbers'][0]['rooms'][0] booking = Booking.objects.create( user=request.user, provision_code=result['code'], hotel_code=book_result['hotel_code'], booking_code=crypto.get_random_string(length=12), coral_booking_code=book_result['code'], room_type=room['room_type'], room_description=room['room_description'], pax_count=request.session['pax'], pax_names=", ".join(request.POST.getlist('name')), price=book_result['price'], status=book_result['status']) booking.save() info = message(request, response=bookings) subject, to = 'Booking Info', request.POST.get('email') email = EmailMultiAlternatives(subject, body=info, to=[to]) email.content_subtype = 'html' email.send() return render_to_response('book.html', {'book_result': bookings}) else: result_dict['price'] = result['price'] return render( request, 'provision.html', { 'product_code': product_code, 'pax_generator': pax_generator, 'result_dict': result_dict })
def send_email(self, emails, subject, text_content=None, html_content=None, main_content=None): """ @subject, @text_content and @html_content are intuitive. @to must have be a string (email) or a list of strings (emails). @main_content must be 'text', 'html' or None. If None, it will be set to 'html' if html_content if provided, 'text' in other case. Returns True if success, False otherwise. """ if USING_CELERY: from email_manager.tasks import send_email send_email.delay(emails, subject, text_content, html_content, main_content) return None try: if not emails: return None if isinstance(emails, str): emails = [emails] to = [emails[0]] bcc = emails[1:] # used for network optimization formatted_subject = "%s %s" % (settings.EMAIL_SUBJECT_PREFIX, subject) msg = EmailMultiAlternatives(formatted_subject, text_content, to=to, bcc=bcc) if html_content: msg.attach_alternative(html_content, "text/html") if main_content == "html" or not main_content: msg.content_subtype = "html" # else default is plain/text msg.send(fail_silently=False) for email in emails: EmailLog.create_log(email, subject) return True except SMTPException as e: EmailLog.create_log(email, subject, success=False, error=str(e)) return False
def contacto(request): # pdb.set_trace() if request.method == 'POST': validator = FormContacto(request.POST) validator.required = ['name', 'email', 'telefono', 'asunto', 'mensaje'] if validator.is_valid(): htmly = get_template('mail.html') name = request.POST['name'] from_email = request.POST['email'] telefono = request.POST['telefono'] asunto = request.POST['asunto'] ast = "Dudas o inquietud Perfumes Pink/826" mensaje = request.POST['mensaje'] body = render_to_string('mail.html',{'name':name,'asunto':asunto,'from_email':from_email,'telefono':telefono, 'mensaje':mensaje}) #contexto = Context({name}) #html_content = htmly.render(contexto) msg = EmailMultiAlternatives(ast, body , from_email , [ settings.EMAIL_HOST_USER]) #msg.attach_alternative(html_content, "text/html") #msg.send() msg.content_subtype = "html" msg.send() #send_mail(asunto, body, from_email , [ settings.EMAIL_HOST_USER] ) return render_to_response('contacto.html', {'success': True, 'error':validator.getMessage()}, context_instance = RequestContext(request)) else: return render_to_response('contacto.html', {'error': validator.getMessage()}, context_instance=RequestContext(request)) return render_to_response('contacto.html', context_instance=RequestContext(request))
def regist(request): """注册""" if request.method == 'GET': return render(request, 'poll/regist.html') elif request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') recvlist = [request.POST.get('email')] try: user = PollUser.objects.create_user(username=username, password=password) newuser = PollUser.objects.last() # 定义序列化工具 serializer = TimedJSONWebSignatureSerializer(settings.SECRET_KEY) serializerstr = serializer.dumps({ 'newuserid': newuser.id }).decode('utf-8') # dumps将对象序列化成字符串 loads将字符串反序列化成对象 mail = EmailMultiAlternatives( "Python发送HTML邮件", "<h1><a href='http://192.168.0.0.1:8000/active/%s/'>" "点我激活</a></h1>" % (serializerstr), settings.EMAIL_HOST_USER, recvlist) mail.content_subtype = 'html' mail.send() newuser.is_active = False newuser.save() except: return None if user: return redirect(reverse('poll:login')) else: return redirect(reverse('poll:regist'))
def send_email(subject, to_email, html_content): """ Enviamos un correo con HTML """ msg = EmailMultiAlternatives(subject, html_content, settings['EMAIL']['DEFAULT_FROM_EMAIL'], [to_email]) msg.content_subtype = "html" msg.send()
def post(self, req): try: username = req.POST.get('username') password = req.POST.get('password') email = req.POST.get('email') user = MyUser.objects.create_user(username=username, email=email, password=password) user.is_active = False user.save() userid = user.id from django.conf import settings util = TimedJSONWebSignatureSerializer( secret_key=settings.SECRET_KEY) userid = util.dumps({'userid': userid}).decode('utf-8') info = '请激活<a href="http://127.0.0.1:8000/active/%s/"> 点我激活%s</a>' % ( userid, username, ) from django.conf import settings mail = EmailMultiAlternatives("请激活", info, settings.DEFAULT_FROM_EMAIL, [email]) mail.content_subtype = 'html' mail.send() if user: return redirect(reverse('vote:login')) except: lf = MyUserLoginForm() rf = MyUserRegistForm() errormessage = '注册失败' return render(req, 'vote/login.html', locals())
def adjust_stock(sender,instance, **kwargs): if not instance.active: #Decrement stock counts orders= BookOrder.objects.filter(cart=instance) for order in orders: book=order.book book.stock -= order.quantity book.save() #Send Thank You mail subject = 'Thanks for shopping with Mystery Books!' from_email= '*****@*****.**' to_email= [instance.user.email] email_context= Context({ 'username': instance.user.username, 'orders': orders }) text_email= render_to_string('email/purchase_email.txt', email_context) html_email= render_to_string('email/purchase_email.html', email_context) msg= EmailMultiAlternatives(subject,text_email,from_email,to_email) msg.attach_alterntives(html_email, 'text/html') msg.content_subtype = 'html' msg.send()
def send_email_signal_handler(sender, **kwargs): emailto = kwargs['emailto'] title = kwargs['title'] content = kwargs['content'] images = kwargs['images'] msg = EmailMultiAlternatives(title, content, from_email=settings.DEFAULT_FROM_EMAIL, to=emailto) msg.content_subtype = "html" msg.mixed_subtype = 'related' if images is not None: for key, value in images.items(): full_path = os.path.join(EMAIL_FILES, key) if os.path.isfile(full_path): img_data = open(full_path, 'rb').read() img = MIMEImage(img_data, value) img.add_header('Content-Id', key) img.add_header("Content-Disposition", "inline", filename=key) msg.attach(img) from servermanager.models import EmailSendLog log = EmailSendLog() log.title = title log.content = content log.emailto = ','.join(emailto) try: result = msg.send() log.send_result = result > 0 except Exception as e: logger.error(e) log.send_result = False log.save()
def support(request): from masterinterface.scs.forms import ContactUs reported = False if request.method == "POST": contactForm = ContactUs(request, request.POST) if contactForm.is_valid(): from django.template import loader from django.core.mail import EmailMultiAlternatives text_content = loader.render_to_string( "scs/%s.txt" % "support_mail", dictionary={"contactForm": contactForm, "reported": reported} ) html_content = loader.render_to_string( "scs/%s.html" % "support_mail", dictionary={"contactForm": contactForm, "reported": reported} ) mail_from = "*****@*****.**" mail_to = "%s %s <%s>" % ("vph-share", "support", "*****@*****.**") msg = EmailMultiAlternatives("Support request [VPH-Bug-Report]", text_content, mail_from, [mail_to]) msg.attach_alternative(html_content, "text/html") msg.content_subtype = "html" msg.send() reported = True else: contactForm = ContactUs(request) return render_to_response( "scs/support.html", {"contactForm": contactForm, "reported": reported}, RequestContext(request) )
def process_confirm(self, request, obj, *args, **kwargs): booking = BookingRequest.objects.filter(pk=obj)[:1].get() subject = 'Confirmed Experienced#' + str(booking.id) text_content, company_email, to, admin_email = 'Text Content', '*****@*****.**', booking.email, '*****@*****.**' artist_name = booking.artist.firstname + " " + booking.artist.surname #image = get_image(booking.artist.meet_up_location_image) get image context = { "username": booking.payer_name, "artist_name": artist_name, "hour_spend": booking.artist.hour, "exp_skill": booking.artist.skill, "amentities": booking.artist.amenities, "booking_time": booking.booking_time, "meet_up_location": booking.pickup_location, "passport_id": booking.passport_id, "total_fee": booking.total_price, "service_type": booking.service_type, "total_guest": booking.guest_no, "booking_date": booking.booking_date, "booking_time": booking.booking_time, "booking_id": booking.id } html_content = get_template('booking/confirmMail.html').render(context) msg_customer = EmailMultiAlternatives(subject, text_content, company_email, [to], [admin_email]) msg_customer.attach_alternative(html_content, "text/html") msg_customer.content_subtype = "html" #msg_customer.attach(image) attach image msg_customer.send() booking.state = 'Confirmed' booking.save() return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
def get_message(self): """Returns the appropriate EmailMessage instance.""" txt_template = self.payload['txt_template'] html_template = self.payload['html_template'] if html_template and txt_template: msg = EmailMultiAlternatives( subject=self.payload['subject'], body=self.render(txt_template), from_email=self.payload['sender'], to=[self.payload['recipient']] ) msg.attach_alternative(self.render(html_template), 'text/html') return msg elif html_template: # html only msg = EmailMessage( subject=self.payload['subject'], body=self.render(html_template), from_email=self.payload['sender'], to=[self.payload['recipient']] ) msg.content_subtype = 'html' return msg elif txt_template: # txt only return EmailMessage( subject=self.payload['subject'], body=self.render(txt_template), from_email=self.payload['sender'], to=[self.payload['recipient']] )
def sendEmail(email, template, data): if not email.has_key('sender'): email['sender'] = settings.DEFAULT_FROM_EMAIL if not email.has_key('receiver'): return False if not email.has_key('copy'): email['copy'] = [] if not template: return False if not data: return False subject = 'RIVE – B2B UPDATE' html_content = loader.render_to_string( template, # 需要渲染的html模板 data) try: msg = EmailMultiAlternatives(subject, html_content, email['sender'], email['receiver'], email['copy']) msg.content_subtype = "html" msg.send() except Exception as e: # print e.message return False else: return True
def render_mail(self, template_prefix, email, context, request): """ Renders an e-mail to `email`. `template_prefix` identifies the e-mail that is to be sent, e.g. "account/email/email_confirmation" """ subject = render_to_string("{0}_subject.txt".format(template_prefix), context) # remove superfluous line breaks subject = " ".join(subject.splitlines()).strip() subject = self.format_email_subject(subject) sender_email = self.get_from_email(request) bodies = {} for ext in ["html", "txt"]: try: template_name = "{0}_message.{1}".format(template_prefix, ext) bodies[ext] = render_to_string(template_name, context).strip() except TemplateDoesNotExist: if ext == "txt" and not bodies: # We need at least one body raise if "txt" in bodies: msg = EmailMultiAlternatives(subject, bodies["txt"], sender_email, [email]) if "html" in bodies: msg.attach_alternative(bodies["html"], "text/html") else: msg = EmailMessage(subject, bodies["html"], sender_email, [email]) msg.content_subtype = "html" # Main content is now text/html return msg
def payment_received(sender, **kwargs): """обрабатываем сигнал оплаты от платежной системы""" order = Order.objects.get(id=kwargs['InvId']) order.is_paid = True order.save() subject = u'заявка от %s' % order.user.first_name message = u'Номер заказа: %s \n Имя: %s \n телефон: %s' % (order.id, order.user.last_name, order.user.phone) send_mail(subject, message, '*****@*****.**', [ADMIN_EMAIL], fail_silently=False) subject = u'Заказ на kastoreum.ru%s' % order.user.first_name message = u'Номер заказа %s \n Спасибо, %s! \n Ваша заявка принята! ' % (order.id, order.user.first_name,) send_mail(subject, message, '*****@*****.**', [order.user.email], fail_silently=False) cart_id = order.cart_id items = CartItem.objects.filter(cart_id=cart_id) context_dict = { 'name': order.user.get_full_name(), 'cart_items': items, 'price': order.total_price(), 'absolut_link': ABSOLUT_LINK } subject = u'Супер письмо' message = render_to_string( 'core/email.html', context_dict) from_email = '*****@*****.**' to = "*****@*****.**" msg = EmailMultiAlternatives(subject, message, from_email, [to]) msg.content_subtype = "html" msg.send()
def email_message(template_name, context, *message_args, **message_kwargs): """Construct an email message from a template. The template is passed `context` as template context. The template is expected to contain ``{% block subject %}`` and ``{% block body %}``. In addition, an HTML-formatted body may be added by the use of a ``{% block html %}``. Both subject and body default to `None` if absent. :rtype: ``EmailMultiAlternatives`` """ template = render_to_string(template_name, context) subject = _find_block(template, 'subject') body = _find_block(template, 'body') html = _find_block(template, 'html') assert subject is not None, "'subject' block is mandatory (but may be empty)" assert body is not None or html is not None, "One of 'html' or 'body' is mandatory (but may be empty)" subject = subject.strip() body = body.strip() if body and html: mail = EmailMultiAlternatives(subject, body, *message_args, **message_kwargs) mail.attach_alternative(html, 'text/html') elif body: mail = EmailMultiAlternatives(subject, body, *message_args, **message_kwargs) else: mail = EmailMultiAlternatives(subject, html, *message_args, **message_kwargs) mail.content_subtype = 'html' return mail
def adjust_stock(sender, instance, **kwargs): if not instance.active: #decrement stock counts orders = BookOrder.objects.filter(cart=instance) for order in orders: book = order.book book.stock -= order.quantity book.save() #sending thankyou mail subject = 'Thanks for shopping with Spark Store!' from_email = '*****@*****.**' to_email = [instance.user.email] email_context = Context({ 'username': instance.user.username, 'orders': orders }) text_email = render_to_string('email/purchase_email.txt', email_context) html_email = render_to_string('email/purchase_email.html', email_context) msg = EmailMultiAlternatives(subject, text_email, from_email, to_email) msg.attach_alternative(html_email, 'text/html') msg.content_subtype = 'html' msg.send()
def send(request, to, subject, body, behalf=None, cc='', bcc=''): reply_to = {} if hasattr(settings, 'REPLY_TO'): reply_to = {'Reply-To': settings.REPLY_TO, 'Return-Path': settings.REPLY_TO} if behalf is None and hasattr(settings, 'EMAIL_FROM'): behalf = settings.EMAIL_FROM cc = _combine_with_settings(cc, 'EMAIL_CC') bcc = _combine_with_settings(bcc, 'EMAIL_BCC') e = EmailMultiAlternatives( subject=subject, from_email=behalf, to=to.split(';'), cc=cc, bcc=bcc, headers=reply_to ) e.attach_alternative(markdown2.markdown( body, extras=["link-patterns", "tables", "code-friendly"], link_patterns=registry.link_patterns(request), safe_mode=True ), 'text/html') e.content_subtype = 'html' e.send()
def send_mymail(request): if request.method == "POST": to_user = request.POST.get('to_user') to_subject = request.POST.get('to_subject') to_content = request.POST.get('to_content') file = request.FILES['to_file'] # subject 主题 content 内容 to_addr 是一个列表,发送给哪些人 msg = EmailMultiAlternatives(to_subject, to_content, settings.DEFAULT_FROM_EMAIL, [to_user]) msg.content_subtype = "text/html" # 添加附件(可选) msg.attach(file.name, file.file.getvalue(), mimetypes.guess_type(file.name)[0]) #email.attach(self.report_filename.format(report_id), attachment.data, "application/octet-stream") # 发送 msg.send() # send_mail的参数分别是 邮件标题,邮件内容,发件箱(settings.py中设置过的那个),收件箱列表(可以发送给多个人),失败静默(若发送失败,报错提示我们) #send_mail(to_subject, to_content, settings.EMAIL_HOST_USER, [to_user], fail_silently=False) # html = file(filestr).read() # _sendEmail(ToUser, (filestr, html), u'') print "send ok" return HttpResponse("ok")
def sendMail(self, mailFrom='*****@*****.**', mailTo=None, mailCC=None, mailBCC=None, replyTo=None, subject=None, bodyHTML=None, bodyText=None): surpress = (EmailSuppression.objects.filter(suppression_date=date.today()).count() > 0) if surpress: log.warn("Surpressing e-mail") return if bodyText and bodyHTML: message = EmailMultiAlternatives() message.body = bodyText message.attach_alternative(transform(bodyHTML), "text/html") elif bodyText: message = EmailMessage() message.body = bodyText elif bodyHTML: message = EmailMessage() message.body = transform(bodyHTML) message.content_subtype = "html" else: raise TypeError("bodyHTML or bodyText must be set") if not (mailTo or mailCC or mailBCC): raise TypeError("Message must have at least one recipient") if subject: message.subject = subject overrideEmail = None #Try to get override email from settings try: overrideEmail = [settings.ENRICHMENT_OVERRIDE_EMAIL] except AttributeError: pass #Take presidence on the parameter if self.overrideEmail: overrideEmail = self.overrideEmail if not overrideEmail: if mailTo: message.to = list(mailTo) if mailCC: message.cc = list(mailCC) if mailBCC: message.bcc = list(mailBCC) else: message.to = overrideEmail if replyTo: message.reply_to = list(replyTo) message.from_email = mailFrom message.send()
def register(request): if request.method == 'POST': username = request.POST.get('username_1') pwd = request.POST.get('pwd_1') pwd1 = request.POST.get('pwd_2') email = request.POST.get('email') # print(username,pwd,pwd1) errors = None if pwd != pwd1: errors = '密码不一致' return render(request, 'vote/login.html', {'errors': errors}) else: user = MyUser.objects.create_user(username=username, password=pwd) user.is_active = False user.save() #得到序列化工具 serutil = Serializer(settings.SECRET_KEY) #使用工具对字典对象序列化 result = serutil.dumps({'userid': user.id}).decode('utf-8') mail = EmailMultiAlternatives( '点击激活用户', '<a href="http://127.0.0.1:8000/vote/active/%s/">点击激活</a>' % (result, ), settings.DEFAULT_FROM_EMAIL, [email]) mail.content_subtype = 'html' mail.send() return render(request, 'vote/login.html', {'error': '请在一小时内激活'})
def user_post_save(instance, **kwargs): # register bonus if settings.REGISTER_BONUS_ENABLE: kw = dict( client=instance, amount=Decimal(str(settings.REGISTER_BONUS)), description='register %s up' % instance.pk ) transaction = BonusTransaction.objects.filter(**kw) if not transaction: transaction = BonusTransaction.objects.create(**kw) instance.reload_bonus_score(rebuild=True) if not any ((instance.is_verified, instance.verification)): Verification.objects.create(user=instance) email = instance.email link = reverse('accounts:account-verify', args=(instance.verification.sid,)) link = settings.SITE_URL + link subject = u"Подтверждение регистрации" #information = unicode(settings.REGISTER_VERIFICATION_MESSAGE % {'link': link}) #send_mail( # subject=subject, # message=unicode(settings.REGISTER_VERIFICATION_MESSAGE % {'link': link}), # from_email=settings.EMAIL_FROM, # recipient_list=[email, ] #) information = render_to_string('mail/register.html', { 'link': link }) message = EmailMulti(subject, information, settings.EMAIL_FROM, [email]) message.content_subtype ='html' message.send() return instance
def send_html_mail(self, subject, html, to_mails): while True: if type(to_mails) == str: to_mails = [to_mails] elif type(to_mails) == list: to_mails = to_mails else: result = False msg = '邮箱地址格式不正确' break from_email = settings.EMAIL_HOST_USER try: msg = EmailMultiAlternatives(subject, html, from_email, to_mails) msg.content_subtype = "html" # 添加附件(可选) # msg.attach_file('./twz.pdf') # 发送 result = msg.send() except Exception as e: result = False msg = e break if result: result = True msg = '发送成功' break else: result = False msg = '发送失败' break self.__record(subject, html, to_mails, result, msg) return result
def payment_received(sender, **kwargs): order = Order.objects.get(id=kwargs['InvId']) order.status = Order.PAID # order.paid_sum = kwargs['OutSum'] order.save() """отправка писем""" order_items = OrderItem.objects.filter(order=order) items = '' for item in order_items: items = items + '%s \n' % item.name if order.payment_method == 1: payment_method = u'Оплата курьером' else: payment_method = u'Оплата онлайн' subject = u'podarkoff-moscow.ru заявка от %s' % order.shipping_name message = u'Заказ №: %s \n Имя: %s \n телефон: %s \n почта: %s \n id заказа: %s \n Товары: %s \n Стоимость: %s \n Способ оплаты: %s' % (order.transaction_id, order.shipping_name, order.phone, order.email, order.id, items, order.total, payment_method) send_mail(subject, message, '*****@*****.**', [ADMIN_EMAIL], fail_silently=False) context_dict = { 'transaction': order.transaction_id, 'id': order.id, 'items': items, 'total': order.total, 'payment_method': payment_method, } message = render_to_string('checkout/email.html', context_dict) from_email = '*****@*****.**' to = '%s' % order.email msg = EmailMultiAlternatives(subject, message, from_email, [to]) msg.content_subtype = "html" msg.send()
def dict_to_email(messagedict): messagedict = copy.deepcopy(messagedict) extra_attrs = {} if settings.CELERY_EMAIL_MESSAGE_EXTRA_ATTRIBUTES: for attr in settings.CELERY_EMAIL_MESSAGE_EXTRA_ATTRIBUTES: if attr in messagedict: extra_attrs[attr] = messagedict.pop(attr) if isinstance(messagedict, dict) and "content_subtype" in messagedict: content_subtype = messagedict["content_subtype"] del messagedict["content_subtype"] else: content_subtype = None if isinstance(messagedict, dict) and "mixed_subtype" in messagedict: mixed_subtype = messagedict["mixed_subtype"] del messagedict["mixed_subtype"] else: mixed_subtype = None if hasattr(messagedict, 'from_email'): ret = messagedict elif 'alternatives' in messagedict: ret = EmailMultiAlternatives(**messagedict) else: ret = EmailMessage(**messagedict) for attr, val in extra_attrs.items(): setattr(ret, attr, val) if content_subtype: ret.content_subtype = content_subtype messagedict["content_subtype"] = content_subtype # bring back content subtype for 'retry' if mixed_subtype: ret.mixed_subtype = mixed_subtype messagedict["mixed_subtype"] = mixed_subtype # bring back mixed subtype for 'retry' return ret
def render_mail(self, template_prefix, email, context): """ Renders an e-mail to `email`. `template_prefix` identifies the e-mail that is to be sent, e.g. "account/email/email_confirmation" """ subject = render_to_string('{0}_subject.txt'.format(template_prefix), context) # remove superfluous line breaks subject = " ".join(subject.splitlines()).strip() subject = self.format_email_subject(subject) bodies = {} for ext in ['html', 'txt']: try: template_name = '{0}_message.{1}'.format(template_prefix, ext) bodies[ext] = render_to_string(template_name, context).strip() except TemplateDoesNotExist: if ext == 'txt' and not bodies: # We need at least one body raise if 'txt' in bodies: msg = EmailMultiAlternatives(subject, bodies['txt'], settings.DEFAULT_FROM_EMAIL, [email]) if 'html' in bodies: msg.attach_alternative(bodies['html'], 'text/html') else: msg = EmailMessage(subject, bodies['html'], settings.DEFAULT_FROM_EMAIL, [email]) msg.content_subtype = 'html' # Main content is now text/html return msg
def send_message_about_buy(request: object, user: object, product: object) -> object: """Send message about buy product on email admin.""" current_site = get_current_site(request) mail_subject = 'Покупка продукта' product_image = Path(product.image.name).name message = render_to_string( 'alfastaff-products/buy_message.html', { 'user': user, 'domain': current_site.domain, 'bonus': product, 'bonus_image': product_image, 'time': datetime.now().strftime('%d.%m.%Y в %H:%M:%S') }) to_email = settings.EMAIL_HOST_USER email = EmailMultiAlternatives(mail_subject, message, to=[to_email]) email.content_subtype = 'html' email.attach_alternative(message, "text/html") email.mixed_subtype = 'related' image = MIMEImage(requests.get(product.image.url).content) image.add_header('Content-ID', f"<{product_image}>") email.attach(image) email.send() return JsonResponse({"buy": "ok"})