Answer the question
In order to leave comments, you need to log in
Form not sending email?
Hello.
I am writing a feedback form. The form basically works in basis saves the message, but on soap does not send?
Tell me where is the mistake!
model
from django.db import models
class MailBox(models.Model):
class Meta:
db_table = 'contact_form'
verbose_name = 'Контактная форма'
verbose_name_plural = 'Форма обратной связи'
subject = models.CharField(max_length=150, verbose_name='Имя пользователя')
sender = models.EmailField(verbose_name='E-mail - пользователя')
phone = models.CharField(max_length=15, verbose_name='Телефон')
message = models.TextField(verbose_name='Сообщение')
copy = models.BooleanField()
def __unicode__(self):
return self.subject
from django.forms import ModelForm
from mystudio.models import MailBox
class ContactForm(ModelForm):
class Meta:
model = MailBox
fields = ['subject', 'sender', 'phone', 'message', 'copy']
def contact(reguest):
if reguest.method == 'POST':
form = ContactForm(reguest.POST)
# Если форма заполнена корректно, сохраняем все введённые пользователем значения
if form.is_valid():
subject = form.cleaned_data['subject']
sender = form.cleaned_data['sender']
phone = form.cleaned_data['phone']
message = form.cleaned_data['message']
copy = form.cleaned_data['copy']
recepients = ['[email protected]']
# Положим копию письма в базу данных
MailBox.objects.create(subject=subject, sender=sender, phone=phone, message=message, copy=copy)
# Если пользователь захотел получить копию себе, добавляем его в список получателей
if copy:
recepients.append(sender)
try:
send_mail(subject, message, phone, ['[email protected]'], recepients)
except BadHeaderError: #Защита от уязвимости
return HttpResponse('Invalid header found')
# Переходим на другую страницу, если сообщение отправлено
return HttpResponseRedirect('/mystudio/thanks/')
else:
form = ContactForm()
# Выводим форму в шаблон
return render(reguest, 'mystudio/contact.html', {'form': form})
EMAIL_HOST = 'smtp.mail.ru'
EMAIL_HOST_USER = '[email protected]'
EMAIL_HOST_PASSWORD = 'mypassword'
EMAIL_PORT = 465
EMAIL_USE_SSL = True
DEFAULT_FROM_EMAIL = '[email protected]'
<form id="contact-form" action="{% url 'contact' %}" method="post">
{% csrf_token %}
{{ form.non_field_errors }}
<fieldset>
<label>{{ form.subject.errors }}
<input name="subject" type="text" value="Имя" onBlur="if(this.value=='') this.value='Имя'" onFocus="if(this.value =='Имя' ) this.value=''" />
</label>
<label>{{ form.sender.errors }}
<input name="sender" type="text" value="E-mail" onBlur="if(this.value=='') this.value='E-mail'" onFocus="if(this.value =='E-mail' ) this.value=''" />
</label>
<label>{{ form.phone.errors }}
<input name="phone" type="text" value="phone" onBlur="if(this.value=='') this.value='phone'" onFocus="if(this.value =='phone' ) this.value=''" />
</label>
{{ form.message.errors }}
<textarea name="message" onBlur="if(this.value=='') this.value='Сообщение'" onFocus="if(this.value =='Сообщение' ) this.value=''">Сообщение</textarea>
{{ form.copy.errors }}
<label for="id_copy">{{ form.copy }} Отправить копию себе </label>
<div class="buttons-wrapper">
<a class="button" onClick="document.getElementById('contact-form').reset()">Очистить</a>
<a class="button" onClick="document.getElementById('contact-form').submit(type)">Отправить</a>
</div>
</fieldset>
</form>
Answer the question
In order to leave comments, you need to log in
https://docs.djangoproject.com/en/1.9/topics/email...
send_mail(subject, message, phone, ['[email protected]'], recepients)
send_mail(subject, message, from_email, recipient_list, fail_silently=False, auth_user=None, auth_password=None, connection=None, html_message=None)
Guys, I rewrote the feedback form differently without saving it to the database and it works! Please look at the non-working code and the worker, what is my mistake?
Here is the working code.
forms.py
# -*- coding: UTF-8 -*-
from django import forms
#from django.forms import ModelForm
# from mystudio.models import MailBox
class ContactForm(forms.Form):
subject = forms.CharField(max_length=100)
sender = forms.EmailField()
#phone = forms.CharField(max_length=15)
message = forms.CharField()
copy = forms.BooleanField(required=False)
def contact(reguest):
if reguest.method == 'POST':
form = ContactForm(reguest.POST)
# Если форма заполнена корректно, сохраняем все введённые пользователем значения
if form.is_valid():
subject = form.cleaned_data['subject']
sender = form.cleaned_data['sender']
#phone = form.cleaned_data['phone']
message = form.cleaned_data['message']
copy = form.cleaned_data['copy']
recepients = ['[email protected]']
# Положим копию письма в базу данных
#MailBox.objects.create(subject=subject, sender=sender, phone=phone, message=message, copy=copy)
# Если пользователь захотел получить копию себе, добавляем его в список получателей
if copy:
recepients.append(sender)
try:
send_mail(subject, message, '[email protected]', recepients)
except BadHeaderError: #Защита от уязвимости
return HttpResponse('Invalid header found')
# Переходим на другую страницу, если сообщение отправлено
return redirect('/mystudio/thanks/')
else:
form = ContactForm()
# Выводим форму в шаблон
return render(reguest, 'mystudio/contact.html', {'form': form})
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question