Retrieving info from contact form django - django

I keep working with django and I was building a contact form.
I want to retrieve the information in the contact form, which I was able to do so far, but I am facing the problem that the user that fills in the form is also receiving an email with the information and MY email ( which I don't want ).
I am using the function EmailMultiAlternatives in my view, and have configured propertly my settings.py with the email account, and extra data needed for emails.
Can the information from a form be only received by me (administrator)?
Here is my view:
form = ContactForm(request.POST)
if form.is_valid():
email = form.cleaned_data['email']
name = form.cleaned_data['name']
message = form.cleaned_data['message']
to = #my email
html_content = "received from [%s] ***message*** %s"%(email,message)
msg = EmailMultiAlternatives('Subject', html_content, 'from#server.com', [to])
msg.attach_alternative(html_content, 'text/html')
msg.send()

Related

Getting user credentials by email

I'm making a small solution to restore user credentials. I decided to try to do it with my algorithm. I request the user's mail and compare it with the database of postal addresses. If the mail exists, I want to send the user his credentials (login and password). I have already done the acceptance and verification of mail, as well as configured the sending of emails to postal addresses. But how to get access to credentials with only mail and the fact that the user is not logged in, I do not understand. I know that maybe my solution based on security is not very good, but there was interest and I really want to understand how to do it.
It may be possible to make a quick login and get data from there, or it can do without it? As a result, I have to send the used as a message to views.py this data.
views.py
def recovery(request):
if request.user.is_authenticated:
return redirect("/accounts/exit/")
else:
if request.method == 'POST':
email_form = UserRecoveryForm(request.POST)
if email_form.is_valid():
email = email_form.cleaned_data['email']
try:
send_mail("Восстановление учетных данных.", "message", "from#gmail.com", [email], fail_silently=False)
except BadHeaderError:
return HttpResponse('Ошибка в теме письма.')
return render(request, 'registration/recovery_done.html')
else:
email_form = UserRecoveryForm()
return render(request, 'registration/recovery.html', {'email_form': email_form})
Just in case forms.py
class UserRecoveryForm(forms.ModelForm):
email = forms.EmailField(label='Почта', help_text='На почту мы отправим дополнительную информация в случае необходимости')
class Meta:
model = User
fields = ('email',)
def clean_email(self):
email = self.cleaned_data.get('email')
username = self.cleaned_data.get('username')
if (not(email and User.objects.filter(email=email).exclude(username=username).exists())):
raise forms.ValidationError('Такой почты не существует.')
return email

django email fails to send in production, works for errors, fails for a particular view

I'm trying to automatically send an email with a django contact us form.
The contact form view works in development properly via django.core.mail.backends.console.EmailBackend
Sending of emails to admins for errors in procution works properly.
However sending emails for the contact view/form doesn't work in production.
No errors are produced in production when submitting the contact form.
the post request appears in the logs, but there isn't any other useful information (that I can see) apart from that.
I'm not sure how best to pinpoint the error?
view:
#require_http_methods(['GET', 'HEAD', 'POST'])
def contact_view(request):
form = ContactForm()
if request.method == 'POST':
form = ContactForm(request.POST)
if form.is_valid():
contact_name = form.cleaned_data.get('contact_name', '')
contact_email = form.cleaned_data.get('contact_email', '')
email_content = form.cleaned_data.get('message', '')
email = EmailMessage(
subject="New contact form submission",
body=email_content,
to=('support#somedomain.com',),
from_email=f'{contact_name} <{contact_email}>',
reply_to=(contact_email,),
)
email.send()
messages.success(request,
"Your email has been sent. Thanks for contacting us, we'll get back to you shortly")
return redirect('contact')
context = {'form': form}
return render(request, 'pages/contact.html', context)
production email settings:
DEFAULT_FROM_EMAIL = env('DJANGO_DEFAULT_FROM_EMAIL',
default=' <noreply#some_domain.com>')
EMAIL_SUBJECT_PREFIX = env('DJANGO_EMAIL_SUBJECT_PREFIX', default='[some_domain]')
SERVER_EMAIL = env('DJANGO_SERVER_EMAIL', default=DEFAULT_FROM_EMAIL)
# Anymail with Mailgun
INSTALLED_APPS += ("anymail", )
ANYMAIL = {
"MAILGUN_API_KEY": env('DJANGO_MAILGUN_API_KEY'),
"MAILGUN_SENDER_DOMAIN": env('MAILGUN_SENDER_DOMAIN')
}
EMAIL_BACKEND = "anymail.backends.mailgun.EmailBackend"
Your admin emails work because they are using DEFAULT_FROM_EMAIL which is allowed.
Your email provider may not allow you to send emails from the address entered on the contact form.
You should use your email address for the from_email, and use the email address from the form as the reply_to email address.

Django send mail back to the user who sends in form

I have a contactform on my site.
When submitted a mail is sent to me. But I also want to send the user a mail, letting the user know that I have received the form submission.
When I try to put the email value as a recipient, I get this error: AssertionError: "to" argument must be a list or tuple
Anyone see what is wrong with my code?
def show_contactform(request):
if request.method == 'POST':
form = ContactForm(request.POST)
if form.is_valid():
f = ContactForm(request.POST)
f.save()
email = form.cleaned_data['email']
subject = "New contact from website"
recipients = ['contact#company.com']
rendered = render_to_string('forms/email_body.html', {'form':form)
to_user_subject = "Contact registred"
to_user_rendered = render_to_string('form/to_user_email_contact.html', {'form_headline':subject})
#Send content to celery worker for asynchronous mail outbox - sending to company
tasks.send_email.delay(subject=subject, rendered=rendered, email=email, recipients=recipients)
#Send content to celery worker for asynchronous mail outbox - sending to the user who sent the form
tasks.send_email.delay(subject=to_user_subject, rendered=to_user_rendered, email=recipients, recipients=email)
return HttpResponseRedirect('/form/contact/success/')
else:
form = ContactForm() # An unbound form
return render(request, 'contact/form.html', {
'form': form,
})
#task()
def send_email(subject, rendered, email, recipients):
msg = EmailMultiAlternatives(subject, rendered, email, recipients)
msg.attach_alternative(rendered, "text/html")
msg.send()

Django send_mail() in GAE

I want a logged in user to be able to send a copy of the model object they created that has been saved in the database. Am using the get(pk=id) to recognize the particular one the user wants to send. The problem is, the send_mail() doesn't recognize the recipient email (to).
#login_required
def email_query(request, id):
history = Carloan_form.objects.get(pk=id)
subject = 'Nigerian Loan Calculator Query e-mail'
from_email = 'xxxx#gmail.com'
email = request.user.email
to = "email"
send_mail(subject,get_template('carloan/loancalc-query.txt').render(Context({'history':history})),\
from_email,[to], fail_silently=False)
return HttpResponse('sent')
Update
#login_required
def email_query(request, id):
history = Carloan_form.objects.get(pk=id)
subject = 'Nigerian Loan Calculator Query e-mail'
from_email = 'ajibike.ca#gmail.com'
email = request.user.email
send_mail(subject,get_template('carloan/loancalc-query.txt').render(Context({'history':history})),\
from_email,[email,], fail_silently=False)
return HttpResponse('/history_query_sent/')
Just decided to pass the email straight into the send_mail() and it worked. Thanks
Because you've set to to the string "email". I doubt that is what you wanted to do.
Why not pass the email variable directly into the send_mail call?

Django - Iterate through postdata from ModelMultipleChoiceField

I am creating a form which will allow a user to send an email to multiple people (students).
I have used ModelMultipleChoiceField to create checkboxes for each user, however I'm not sure how to deal with the data that gets posted.
Here's my view so far:
if request.method == 'POST':
subject = request.POST['subject']
message = request.POST['message']
email = EmailMessage(subject, message, 'from#example.com',
recipient_addresses)
email.send()
else:
students = Student.objects.exclude(email='')
form = StudentListForm(students=students)
The form just posts the ID numbers of the selected recipients. Do I have to filter Student objects like this:
Student.objects.filter(pk__in=request.POST['students'])
Or is there a 'better' way?
Any advice would be appreciated.
Thanks
You're missing most of the point of using a form, which is to rely on it for validation and data conversion, as well as simply showing fields in HTML.
if request.method == 'POST':
form = StudentListForm(data=request.POST)
if form.is_valid():
subject = form.cleaned_data['subject']
message = form.cleaned_data['message']
recipients = form.cleaned_data['recipients']
recipient_addresses = [r.email for r in recipients]
email = ...
Basically, you should always access form.cleaned_data instead of request.POST.