Adding more fields to send_mail - django

I see people using the send_mail function like this:
send_mail(subject, message, from_email, ['admin#example.com'])
My form have more fields such as 'name' and 'phone_number'. How can I pass those extra fields to the send_mail function?
forms.py
class ContactForm(forms.Form):
name = forms.CharField(required=True)
phone_number = forms.CharField(required=True)
from_email = forms.EmailField(required=True)
subject = forms.CharField(required=True)
message = forms.CharField(widget=forms.Textarea, required=True)
views.py
def contactView(request):
if request.method == 'GET':
form = ContactForm()
else:
form = ContactForm(request.POST)
if form.is_valid():
subject = form.cleaned_data['subject']
from_email = form.cleaned_data['from_email']
message = form.cleaned_data['message']
try:
send_mail(subject, message, from_email, ['admin#example.com'])
except BadHeaderError:
return HttpResponse('Invalid header found.')
return redirect('success')
return render(request, "email.html", {'form': form})

no, the fields in the sendmail correspond to the data in the email header. If you want to add more contact data to the email, you should render it in the body (for examole as a disclaimer). You can also check this thread: add sender's name in the from field of the email in python

Related

django form is not valid but validation not working

When I submit form it doesn't show any validation error and form is not valid
views.py
def institute(request):
context = {}
if request.POST and request.FILES:
form = InstituteForm(request.POST, request.FILES)
context['form'] = form
if form.is_valid():
form.save()
messages.add_message(
request, messages.SUCCESS, "Successfully Added Institute Information")
return redirect('accounts:profile')
else:
context['form'] = InstituteForm()
return render(request, 'institute.html',context)
according to forms.py it should return email or phone validation error but there is no errors in template
and form data is saving in database
forms.py
class InstituteForm(forms.ModelForm):
class Meta:
model = Institute
fields = '__all__'
exclude = ('create', 'update', 'admin')
def clean_phone(self):
phone = self.cleaned_data['phone']
emp = Employee.objects.filter(phone=phone).count()
ins = Institute.objects.filter(phone=phone).count()
if emp > 0 or ins:
raise ValidationError('This Phone Number is already used, try new one')
return phone
def clean_email(self):
email = self.cleaned_data.get('email')
emp = Employee.objects.filter(email=email).count()
ins = Institute.objects.filter(email=email).count()
if ins > 0 or emp:
raise ValidationError('This email is already used, try new one')
return email

How to create user base on data from form?

forms.py
'''
class AddUserForm(forms.Form):
username = forms.CharField(label='Login', min_length=1)
password = forms.CharField(label='Password', widget=forms.PasswordInput)
repeat_password = forms.CharField(label='Repeat password', widget=forms.PasswordInput)
name = forms.CharField(label="First name", min_length=1, validators=[check_first_upper_letter_validator])
surname = forms.CharField(label="Last name",validators=[check_first_upper_letter_validator])
email = forms.CharField(validators=[EmailValidator()])
'''
views.py
'''
class AddUserView(View):
def get(self, request):
form = AddUserForm()
return render(request, 'exercises/form.html', {'form': form}) def post(self, request):
form = AddUserForm(request.POST)
if form.is_valid():
user = User.objects.create_user(username=...., email=....., password=....)
user.save()
return HttpResponse("OK")
else:
return render(request, 'exercises/form.html', {'form': form})
'''
How to get data from form for username, email etc.?
After django validates a form (which happens when you call form.is_valid()) a dictionary is added to your form called cleaned_data which allows you to access your form data.
So, after form.is_valid() in your view you can access the name entered by form.cleaned_data['name'], the email by form.cleaned_data['email'] and so on.

Error : Using django email i am sending an email after sending email got an error ? smtplib.SMTPServerDisconnected:[WinError 10054]

I am beginner and use the django documentation for sending an email.
I am facing a problem when submitting the form. I got this error:
SMTPServerDisconnected at /buggy_app/booking/
and in my terminal I got:
smtplib.SMTPServerDisconnected: Connection unexpectedly closed: [WinError 10054]
Views.py
from django.template.loader import get_template
from django.conf import settings
from django.core.mail import EmailMultiAlternatives
class BookingView(FormView):
template_name = 'buggy_app/booking.html'
form_class = BookingForm
models = Booking
def form_valid(self, form):
car_id = self.request.GET.get('car', '')
car = Car.objects.get(id=car_id)
car.is_available_car = False
car.save()
form.save()
form.cleaned_data.get('username')
first_name = form.cleaned_data.get('first_name')
last_name = form.cleaned_data.get('last_name')
to_email = form.cleaned_data.get('email')
send_emails(first_name, last_name, to_email)
return super(BookingView, self).form_valid(form)
def send_emails(first_name, last_name, to_email):
htmly = get_template('buggy_app/welcome.html')
d = {'first_name':first_name, 'last_name':last_name}
subject, from_email, to = 'Subject line', settings.EMAIL_HOST_USER, to_email
html_content = htmly.render(d)
msg = EmailMultiAlternatives(subject, html_content, from_email, [to])
msg.attach_alternative(html_content, "text/html")
msg.send()

How to send an email after User post the form?

i am beginner and used steps for sending email from https://docs.djangoproject.com/en/2.0/topics/email/
but i didn't accomplished to send email.
i want to send an email automatically using django email after a user submit the form . i am having a booking form and having email field in it after user post the form i want to send a email "Thankyou for your booking / your booking is placed ".
for eg
first name : Abubakar
Last name :Afzal
email : any#gmail.com
i want to take any#gmail.com and send email to it . after user post the form .
settings.py
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_HOST_USER = 'my#gmail.com'
EMAIL_HOST_PASSWORD = 'mypassword'
EMAIL_USE_TLS = True
View.py
class BookingView(FormView):
template_name = 'buggy_app/booking.html'
form_class = BookingForm
models = Booking
def form_valid(self, form):
car_id = self.request.GET.get('car', '')
car = Car.objects.get(id=car_id)
car.is_available_car = False
car.save()
form.save()
return super(BookingView, self).form_valid(form)
success_url = reverse_lazy('index')
Forms.py
class BookingForm(ModelForm):
class Meta:
model = Booking
widgets = {
times_pick': TimePickerInput(), }
fields = ('first_name','last_name','email','book_car','contact_number','times_pick',)
You can define a function called send_emails (or any name). and call taht function from within form_valid method. It will look something like this
def form_valid(self, form):
car_id = self.request.GET.get('car', '')
car = Car.objects.get(id=car_id)
car.is_available_car = False
car.save()
form.save()
form.cleaned_data.get('username')
first_name = form.cleaned_data.get('first_name')
last_name = form.cleaned_data.get('last_name')
to_email = form.cleaned_data.get('email')
#your function here
send_emails(first_name, last_name, to_email)
and then define function something like this.
def send_emails(first_name, last_name, to_email):
#get template
htmly = get_template('email_templates/welcome.html')
#create a context
d = {'first_name':first_name, 'last_name':last_name}
subject, from_email, to = 'Subject line', settings.EMAIL_HOST_USER, to_email
#pass the context to html template
html_content = htmly.render(d)
msg = EmailMultiAlternatives(subject, html_content, from_email, [to])
msg.attach_alternative(html_content, "text/html")
msg.send()
class BookingView(FormView):
template_name = 'buggy_app/booking.html'
form_class = BookingForm
models = Booking
def form_valid(self, form):
car_id = self.request.GET.get('car', '')
car = Car.objects.get(id=car_id)
car.is_available_car = False
car.save()
form.save()
subject = 'Thankyou for your booking / your booking is placed'
message = 'Thankyou for your booking / your booking is placed'
email_from = settings.EMAIL_HOST_USER
recipient_list = [any#gmail.com]
send_mail( subject, message, email_from, recipient_list )
return super(BookingView, self).form_valid(form)
success_url = reverse_lazy('index')

"recipient" from form in send mail

I have a very basic email app. The forms class is:
class ContactForm(forms.Form):
name = forms.CharField(max_length=100)
subject = forms.CharField(max_length=100)
sender = forms.EmailField()
recipient_list = forms.EmailField()
message = forms.CharField(widget=forms.Textarea)
cc_myself = forms.BooleanField(initial=True)
The view function looks like this:
def contact_name(request, id):
if request.method == 'POST': # If the form has been submitted...
form = ContactForm(request.POST) # A form bound to the POST data
if form.is_valid():
name = form.cleaned_data['name']
subject = form.cleaned_data['subject']
message = form.cleaned_data['message']
sender = form.cleaned_data['sender']
cc_myself = form.cleaned_data['cc_myself']
recipients = ['dennis#themenace.com']
if cc_myself:
recipients.append(sender)
from django.core.mail import send_mail
send_mail(subject, message, sender, recipients)
return HttpResponseRedirect('/') # Redirect after POST
else:
a=Entry.objects.get(pk=id)
form = ContactForm(instance=a) # An unbound form
return render_to_response('email.html', {
'form': form,
})
As long as I specify the recipient in the view, I have no problem. However, I want the message to be sent to the address(es) specified in the form field "recipient list".
When I structure the view code like this:
recipients = form.cleaned_data['recipient_list']
if cc_myself:
recipients.append(sender)
from django.core.mail import send_mail
send_mail(subject, message, sender, recipients)
return HttpResponseRedirect('/') # Redirect after POST
or:
recipients = request.POST.get('recipient_list', '')
if cc_myself:
recipients.append(sender)
I get error "'unicode' object has no attribute 'append'". In short, it doesn't work. What am I doing wrong?
Since recipient_list is an EmailField it cleans to unicode. But you're trying to treat the result as a list. So obviously, construct a list out of it and everything's dandy:
recipients = [form.cleaned_data['recipient_list']]
if cc_myself:
recipients.append(sender)
... but really you should call the field recipient not recipient list as only 1 can be entered.