How can my user upload an image to email to me [Django] - python

I've got a simple website for a Screenprinting company built using Django 1.10 and Python 3.5.2, but I am having issues with my "Get a Quote" page.
The idea is a user can go to www.example.com/quote/ and they are presented with a form. Here they put in their Name, Email Address, a Brief Message, and most importantly they can upload an image.
When they click submit, this data gets sent to my email address as an email using the EmailMessage method. I have set up a simple email form plenty of times in the past so I know my settings.py file is fine.
Here is my forms.py:
class QuoteForm(forms.Form):
name = forms.CharField(required=True)
from_email = forms.EmailField(required=True)
subject = "Quote"
uploaded_image = forms.ImageField()
message = forms.CharField(widget=forms.Textarea)
Here is my views.py:
def quote(request):
form = QuoteForm(request.POST)
if form.is_valid():
name = form.cleaned_data['name']
from_email = form.cleaned_data['from_email']
message = form.cleaned_data['message']
message = "From: " + name + "\n" + "Return Email: " + from_email + "\n" + "Subject: " + subject + "\n" + "Message: " + message
uploaded_image = form.cleaned_data['uploaded_image']
msg = EmailMessage(subject, message, from_email, ['example#email.com'], reply_to=[from_email])
msg.attach_file(uploaded_image)
try:
msg.send()
except BadHeaderError:
return HttpResponse('Invalid header found')
return HttpResponseRedirect('thankyou')
return render(request, "quote.html", {'form': form})
When I test this on 127.0.0.1 I click submit and the form refreshes with the same info, except the image is no longer there.
Also, When I test it using the console.EmailBackend there are no errors. In fact, clicking submit doesn't seem to have any effect other than it reloads a few css files.
Any ideas?

A file is not in the request.POST attribute, it is in request.FILES. Your views.py should look like this:
def quote(request):
form = QuoteForm(request.POST, request.FILES)
if form.is_valid():
...
uploaded_image = request.FILES.getlist('uploaded_image')
...
Please note that this is a raw draft. I haven't tested it. Also note that you might have to sanitize the file for your own safety. For example: checking on the maximum filesize and contenttype.
More information about all of this: https://docs.djangoproject.com/en/1.10/topics/http/file-uploads/

Related

How to send a reset password email in Django on User creation?

I want to be able to let an admin create user accounts and then, instead of setting up a password for the user, the user would automatically receive a reset password email.
The view for the user creation, which also includes a Member model, is the following:
def newmember(request):
if request.method == 'POST':
nu_form = NewUser(request.POST)
nm_form = NewMember(request.POST)
if nu_form.is_valid() and nm_form.is_valid():
nusave = nu_form.save()
nmsave = nm_form.save(commit = False)
nmsave.user = nusave
nmsave.save()
return redirect(members)
else:
print(nu_form.errors)
print(nm_form.errors)
else:
nu_form = NewUser()
nm_form = NewMember()
context = {
'nu_form': nu_form,
'nm_form': nm_form}
return render(request, 'web/newmember.html', context)
How can I make so that upon creation of a new user, Django automatically sends an email to that new user requestion a password reset?
In order to send an email on user creation you need to define a method which shoot an email like below :-
Create a text file name such as 'email_content.txt'
Please reset password for your profile {{username}}
Click Here
Update the newmember method and add below code into it :-
template = get_template('email_content.txt')
context = {"usename": nmsave.user.username}
content = template.render(context)
email = EmailMessage(
"Congratulation, please reset your account password", content, 'App Name' <sender_email>
)
email.content_subtype = "html"
email.send()
add above code in try catch block
In your models.py:
def save(self, *args, **kwargs):
send_mail('subject', 'message', 'your email', 'user email')
return super().save(*args, **kwargs)

Django - how to get email links to work on mobile?

My Django site sends out an email confirmation link, and everything seems to work fine on desktop. On mobile devices, however, the link text is highlighted blue and underlined (i.e. it looks like a link) but nothing happens when the user clicks it. It should open a browser tab and say, "you have confirmed your email, etc"
Thanks for any tips!
views.py:
def signup(request):
if request.method == 'POST':
#send signup form
email_address = request.POST['email']
if request.POST['password1'] == request.POST['password2']:
try:
user = User.objects.get(email=email_address)
return render(request, 'accounts/signup.html', {'error': "Email already in use."})
except User.DoesNotExist:
user = User.objects.create_user(request.POST['email'], password=request.POST['password1'])
#auth.login(request, user)
#send email confirmation link then redirect:
#user = User.objects.get(email=email_address)
current_site = get_current_site(request)
mail_subject = 'Welcome to My Site'
plain_msg = 'Thank you for signing up to My Site! Click this link to activate your account:\n\n'+current_site.domain+'/accounts/activated/'+urlsafe_base64_encode(force_bytes(user.pk)).decode()+'/'+account_activation_token.make_token(user)+'/'
msg = '<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>title</title></head><body>Confirm your email address to continue:<br/>Confirm my email address</body></html>'
print(msg)
send_mail(mail_subject, plain_msg, 'my_email#gmail.com', [email_address], html_message=msg)
return render(request, 'accounts/activation-link-sent.html', {'email': email_address})
#truncated for Stack Overflow post
You should use build_absolute_uri to create fully qualified links that include the current domain and protocol, then use this link in your email
link = request.build_absolute_uri('/accounts/activated/'+urlsafe_base64_encode(force_bytes(user.pk)).decode()+'/'+account_activation_token.make_token(user)+'/')
Do you have a url pattern that matches this URL? You should consider using reverse for building URLs
path = reverse('activate', kwargs={
'pk': user.pk,
'token': account_activation_token.make_token(user)
})
link = request.build_absolute_uri(path)

Send email to address getting from HTML input via Django

I'm searching for solution to this problem for many hours but can't find anything related. I want to get user's email from input and send mail from admin to that email address. Here are my codes:
views.py:
def index(request):
context = {
'questions': Question.objects.all(),
'applicants': Applicant.objects.filter(status=1),
'empty_cards': range(4 - Applicant.objects.filter(status=1).count())
}
if request.method == "POST":
if request.POST.get('message_text'):
Message.objects.create(
sender_name = request.POST.get('sender_name'),
sender_email = request.POST.get('sender_email'),
message_text = request.POST.get('message_text'))
if request.method == 'POST':
subject = 'Welcome !'
message = 'We will back to you.'
from_email = settings.EMAIL_HOST_USER
recipient_list = 'don't know how to get email'
send_mail(subject, message, from_email, recipient_list)
return render(request, 'index.html', context)
from your code I assume that you already have access to the user's mail
inside the request.
so you can try this:
sender_email = sender_request.POST.get('sender_email')
recipient_list = [sender_email]

"to" argument must be a list or tuple in Django

I have a bug like in subject of this question:
"to" argument must be a list or tuple
I want to create a email form and I can't find a error. Maybe someone help me?
My files are:
forms.py
from django import forms
class WyslijEmail(forms.Form):
name = forms.CharField(max_length=25)
subject = forms.CharField(max_length=255)
email = forms.EmailField()
message = forms.CharField(required=True, widget=forms.Textarea)
views.py
from django.shortcuts import render, redirect
from django.core.mail import send_mail, BadHeaderError
from .forms import WyslijEmail
def kontakt(request):
if request.method == 'GET':
form = WyslijEmail()
else:
form = WyslijEmail(request.POST)
if form.is_valid():
name = form.cleaned_data['name']
subject = form.cleaned_data['subject']
email = form.cleaned_data['email']
message = form.cleaned_data['message']
try:
send_mail(name,subject,email,message, ['admin#gmail.com',])
except BadHeaderError:
return render('Niewlasciwe cos tam')
return redirect('sukces')
return render(request,'bajki/kontakt.html', {'form':form})
def sukces(request):
return render('Sukces udało sie')
kontakt.html
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<p><input type="submit" value="Wyślij wiadomość"></p>
</form>
What I must define to fix this problem?
Os so I updated my files and now theyare looking like this:
views.py
from django.shortcuts import render, redirect
from django.core.mail import send_mail
from .forms import WyslijEmail
def kontakt(request):
sent = False
if request.method == 'POST':
form = WyslijEmail(request.POST)
if form.is_valid():
subject = form.cleaned_data['subject']
from_email = form.cleaned_data['from_email']
message = form.cleaned_data['message']
send_mail(subject, message, from_email,['login#gmail.com'])
sent = True
else:
form = WyslijEmail()
return render(request,'bajki/kontakt.html', {'form':form, 'sent': sent})
But its a second problem. When I trying to sent email from page the system responded me a error like this:
SMTPAuthenticationError at /kontakt/
(535, b'5.7.8 Username and Password not accepted. Learn more at\n5.7.8 https://support.google.com/mail/?p=BadCredentials h63sm1453929ljf.36 - gsmtp')
I change the settings in my google account to accept the all emails. I dont know how to fix it.
Here's how to structure send_mail from the Django Documentation:
send_mail(subject,
message,
from_email,
recipient_list,
fail_silently=False,
auth_user=None,
auth_password=None,
connection=None,
html_message=None)
You should change the arguments in your send_mail function accordingly.
Your send_mail method should have four arguments.
send_mail(subject, message, from_email, recipient_list)
EX:
subject == string
message == string
from_email == string
recipient_list == list
Looks like you have additional argument 'name'. And you have not mentioned the from_email argument.
I believe your problem is at the send_mail() function.
I would advise you save your form.clean_data in a variable for reusability
i.e cd = form.clean_data.
Then for the send_mail pass the parameter correctly, and wrap your cd['to'] in a list
send_mail(subject, message, 'admin#myblog.com', [cd['to']])
The issues in your updated code is that the to_email argument takes a list. Instead of writing ['login#gmail.com'], you need to write ['login#gmail.com',] with a comma to make it into a list.

Django sending email with google SMTP

I have been trying to get emails working with my Django application and have not been able to. Ive been reading around on similar questions and still haven't been able to pin point my error.
My settings.py looks like :
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = 'email#domain'
EMAIL_HOST_PASSWORD = 'pass'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
MY code to send the email looks like :
def application(request):
if request.method == 'GET':
form = ApplyForm()
else:
form = ApplyForm(request.POST)
if (form.is_valid()):
try:
subject = 'Overland Application'
from_email = form.cleaned_data['useremail']
phone = form.cleaned_data['phone']
names = form.cleaned_data['names']
year = form.cleaned_data['year']
make = form.cleaned_data['make']
model = form.cleaned_data['model']
message = str(names) + '\n' + str(from_email) + '\n' + str(phone) + '\n' + str(year) + '\n' + str(make) + '\n' + str(model)
try:
send_mail(subject, message, settings.EMAIL_HOST_USER, ['email#domain.com'], fail_silently=False)
except BadHeaderError:
return HttpResponse('Invalid header found.')
return redirect('thanks')
except:
pass
return render(request, "overland/apply.html", {'form': form})
Some additional information is that it seems to be accessing my email account as I did receive an email from google saying there was suspicious access on my account from the location of the server.
I also pinged the smtp server from the live server to make sure that it was communicating.
I am not sure if it is a small syntax error on my part somewhere or I am using the django mail function incorrectly because locally it seemed to work and would redirect to my thanks page, but when I do this live it seems to just reload the page and not send anything.
Thanks in advance for any information.
This was an issue with gmail itself. Anybody running into this issue should first try going to security settings and allowing access to less secure apps. if that doesn't work try visiting https://accounts.google.com/DisplayUnlockCaptcha and then use your application to send the email again.

Categories

Resources