## Views.py

 

def control_newslettersend(request):
    form = NewsletterSendForm
    form = NewsletterSendForm(request.POST or None)
    if form.is_val... ">

I am Sending email through TinyMCE Editor it sends mail with html tags how to fix it


## Views.py

 

def control_newslettersend(request):
    form = NewsletterSendForm
    form = NewsletterSendForm(request.POST or None)
    if form.is_valid():
        instance = form.save()
        newslettersend = NewsletterSend.objects.get(id=instance.id)
        if newslettersend.status == "Published":
            subject = newslettersend.subject
            body = newslettersend.body
            from_email = settings.EMAIL_HOST_USER
            for email in newslettersend.email.all():

                content_subtype = 'html'
                send_mail(subject=subject, from_email=from_email, recipient_list=[email.email], message=body, fail_silently=True)
    context = { 'forms':form, }
    template = 'controlpannel/newslettersend_form.html'
    return render(request, template, context)


 

 

Category: Django
Asked at Oct. 30, 2018, 10:23 a.m. by sangramrajekakade

16 Answers


Are you referring to our site or your project? We did notice we had an issue on our site and this fix will happen shortly. We are launching a new version of the site hopefully in a week or so.

If you are referring to your project then you can look into Strip Tags template tag in Django.

Answered on: Oct. 30, 2018, 12:15 p.m.
Answered by: admin

actually, I am going with your newsletter app, Now I want to send email through HTML editor I am using TinyMCE. When I am sending mail through TinyMCE but It sends with HTML tags like this <p><strong>Hello<strong></p> . here is my Views.py code ---> https://codeshare.io/24mQXE

 

 

Answered on: Oct. 30, 2018, 12:49 p.m.
Answered by: sangramrajekakade

I see now. You need to use EmailMultiAlternative here is the link to the documentation. https://docs.djangoproject.com/en/2.1/topics/email/#sending-alternative-content-types remove your send_mail() and use the EmailMultiAlternative method. This will allow you to send an email in plain text where I would strip the HTML tags and also an HTML formatted message. 

Answered on: Oct. 30, 2018, 1:38 p.m.
Answered by: admin
its shows this error  ""   _init__() got an unexpected keyword argument  """  to every field

 

(subject=subject, from_email=from_email, recipient_list=[email.email],  fail_silently=True)

 

 

Answered on: Oct. 30, 2018, 1:58 p.m.
Answered by: sangramrajekakade

Remove all the keyword arguments.

msg = EmailMultiAlternatives(subject, text_content, from_email, [to])

The above example is how it should look. Make sure you check the documentation. Below is an example of one for the upcoming new MasterCode.Online

user_email = request.user.email
sender_email = settings.DEFAULT_FROM_EMAIL
subject, from_email, to = f'Your Post - {subject}', f'{sender_email}', f'{user_email}'
forum_pk = post.thread.pk
posts_pk = post.thread.pk
pk = post.pk
text_content = f'Your post has been published. It can be found at https://mastercode.online/forums/forums/{forum_pk}/{posts_pk}/{pk}\n {body}'
html_content = f'<p>Your post has been published. It can be found at <a href="https://mastercode.online/forums/forums/{forum_pk}/{posts_pk}/{pk}">{subject}</a></p><p>{body}</p>'
msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
msg.attach_alternative(html_content, "text/html")
msg.send()

 

Answered on: Oct. 30, 2018, 2:07 p.m.
Answered by: admin

when i was sending {{ object.name }} through its sends like string

Answered on: Oct. 31, 2018, 4:48 a.m.
Answered by: sangramrajekakade

sir please sir give me reply

 

Answered on: Oct. 31, 2018, 6:29 a.m.
Answered by: sangramrajekakade

Sir we are in different time zones I am sleeping while you are coding. What do you mean it sends like string? Do you mean it is sending with quotes?

Answered on: Oct. 31, 2018, 12:17 p.m.
Answered by: admin

I want to send an email with the user's name and his email. in TinyMCE HTML editor I put this string       

Hello {{ object.name }} this is your email {{ object.email }}

 

but in email shows  Hello {{ object.name }} this is your email {{ object.email }} 

 

I want to send proper his/her name and email 

###Views.py

 

def control_newslettersend(request):
    form = NewsletterSendForm
    form = NewsletterSendForm(request.POST or None)
    if form.is_valid():
        instance = form.save()
        newslettersend = NewsletterSend.objects.get(id=instance.id)
        if newslettersend.status == "Published":
            subject = newslettersend.subject
            body = newslettersend.body
            from_email = settings.EMAIL_HOST_USER

            for email in newslettersend.email.all():

                msg = EmailMultiAlternatives(subject=subject, from_email=from_email, to=[email.email])
                # msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
                msg.attach_alternative(body, "text/html")
                msg.send()


    context = { 'forms':form, }

    template = 'controlpannel/newslettersend_form.html'
    return render(request, template, context)
    class control_newslettersend(DetailView):
        model = NewsletterSend

 

 

 

Answered on: Oct. 31, 2018, 12:31 p.m.
Answered by: sangramrajekakade

please reply

 

Answered on: Nov. 1, 2018, 4:40 a.m.
Answered by: sangramrajekakade

Sir we are in different time zones I am sleeping while you are coding. What do you mean it sends like string? Do you mean it is sending with quotes?

Answered on: Nov. 1, 2018, 10:51 a.m.
Answered by: admin

You are sending the email via the view not a template in your approach.

If you are using Python 3.6+ try this:

subject = f'{newslettersend.subject}'

body = f'{newslettersend.body'}

This approach uses Python f-strings you can learn more about them here at https://www.mastercode.online/courses/tutorial/f-string-in-python/

If you are using any other version of Python then the solution would be:

subject = '{}'.format(newslettersend.subject)

body = '{}'.format(newslettersend.body)

 

Answered on: Nov. 1, 2018, 10:58 a.m.
Answered by: admin

hello sir, 

I am trying to send an Activation link to a new subscriber for activating email for getting daily newsletter.

when I try to send the encoded link to the user one error occurred 

 

TypeError at /newsletter/subscribe/

a bytes-like object is required, not 'str'

 

 


def NewsletterView(request):
    form = NewsletterForm(request.POST or None)
    template_name = 'newsletter/send_subscribers.html'
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['now'] = timezone.now()
        return context

    if form.is_valid():
        Newsletter.email_confirmed = False
        instance = form.save(commit=False)
        if Newsletter.objects.filter(email=instance.email).exists():
            print("Sorry! This Email already exists")

        else:
            # instance.save()
            subject = "Thank You For subscribe Our News Letter"
            from_email = settings.EMAIL_HOST_USER
            to_email = [instance.email]
            message = render_to_string('newsletter/send_subscribers.html',{'to_email':to_email,'uid': urlsafe_base64_encode(force_bytes(Newsletter.pk).decode()),'token': account_activation_token.make_token(Newsletter)})


            # signup_message = """ Welcome To Our NewsLetter You will get Daily Update from us """
            # send_mail(subject=subject, from_email=from_email, recipient_list=to_email, message=signup_message, fail_silently=True) 

            send_mail = EmailMultiAlternatives(subject=subject,from_email=from_email, to=to_email)
            # html_template = get_template("newsletter/send_subscribers.html").render()
            send_mail.attach_alternative(message, 'text/html')
            send_mail.send()

    context = { 'form':form, }        

    template = 'newsletter/subscribers.html'
    
    return render(request, template, context)

 

 

 

think error shows red line

 

 

i alredy created urls and token.py files

Answered on: Nov. 1, 2018, 1:17 p.m.
Answered by: sangramrajekakade

you will get full code here

 

https://codeshare.io/G6JMXN

Answered on: Nov. 1, 2018, 1:21 p.m.
Answered by: sangramrajekakade

verification link not working it goes in else:  Activation link is invalid!

 

 

def activate(request,uidb64, token):
    try:
        uid = force_text(urlsafe_base64_decode(uidb64))

        News_letter = Newsletter.objects.get(pk=uid)

    except(TypeError, ValueError, OverflowError, Newsletter.DoesNotExist):
        News_letter = None

    if News_letter is not None and account_activation_token.check_token(News_letter, token):
        News_letter.email_confirmed = True
        News_letter.save()
        # return render(request, '/')
        return HttpResponse('Thank you for your email confirmation.')
        # return render(request, 'login.html', {'form': form})
    else:
        return HttpResponse('Activation link is invalid!')
 

Answered on: Nov. 2, 2018, 5:52 a.m.
Answered by: sangramrajekakade

What version of Python and Django are you using?

'token': account_activation_token.make_token(Newsletter)

Newsletter? Where is this coming into play?

Normally we put the User into make token.

I am also trying to figure out why you need a activation link for a newsletter. Most people who signup for a newsletter are not going to confirm the activation. You have less than 3 seconds to get a user to signup for a Newsletter once they do that they move on.

My suggestion would be to move on from the activation link. Have them add their email and then send them a email stating they signed up but provide an unsubscribe link at the bottom of the email. If they want to unsubscribe they can. 

If you are concerned about people signing up a ton of emails that are fake then you can record the IP address of the person submitting the email and only allow one email per an ip address.

Here is a series on vetting spam in Django https://www.mastercode.online/courses/tutorial/create-an-anti-spam-app-in-django-part-1/

Answered on: Nov. 2, 2018, 1:36 p.m.
Answered by: admin