"recipient" from form in send mail - django

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.

Related

How to sent password reset mail from another view?

I have a view to create a restaurant.
In the same view a user is also being created.
After the user creation, I have to sent a mail to the user with the link to reset the password.
My view looks like:
def create_restaurant(request):
form = RestaurantForm()
user_form = RestaurantUserForm()
if request.method == 'POST':
form = RestaurantForm(request.POST, request.FILES)
user_form = RestaurantUserForm(request.POST)
if form.is_valid() and user_form.is_valid():
#----user is saved here------
user_obj = user_form.save()
#----have to sent the mail here------
#-----restaurant is saved here-----
restaurant_obj = form.save()
restaurant_obj.user = User.objects.get(id=user_obj.id)
restaurant_obj.save()
messages.success(request, 'Restaurant Added Successfully.')
return redirect('create_restaurant')
context = {
"title": "Add restaurant",
"form": form,
"user_form": user_form
}
return render(request, "restaurant/restaurant.html", context)
I have implemented the password reset procedure using
urlpatterns = [
path('reset_password/',
auth_views.PasswordResetView.as_view(template_name="password_reset.html"),
name='password_reset'
),
path('reset_password_sent/',
auth_views.PasswordResetDoneView.as_view(template_name="password_reset_sent.html"),
name='password_reset_done'
),
path('reset/<uidb64>/<token>/',
auth_views.PasswordResetConfirmView.as_view(template_name="password_reset_form.html"),
name='password_reset_confirm'
),
path('reset_password_complete/',
auth_views.PasswordResetCompleteView.as_view(template_name="password_reset_done.html"),
name='password_reset_complete'
)]
How can I sent the email as mentioned above?
You can add a function to handle email sending like this
if request.method == 'POST':
form = RestaurantForm(request.POST, request.FILES)
user_form = RestaurantUserForm(request.POST)
if form.is_valid() and user_form.is_valid():
#----user is saved here------
user_obj = user_form.save()
#----have to sent the mail here------
ctx = {add all your data which you want to add in your email template}
send_user_email(ctx)
#-----restaurant is saved here-----
restaurant_obj = form.save()
restaurant_obj.user = User.objects.get(id=user_obj.id)
restaurant_obj.save()
messages.success(request, 'Restaurant Added Successfully.')
return redirect('create_restaurant')
and this is your function which is responsible to send emails
def send_user_email(ctx):
mail_subject = ctx['subject']
message = get_template('email_temp/user_notification.html').render(ctx)
to_email = ctx['user']
email = EmailMessage(
mail_subject,
message,
DEFAULT_FROM_EMAIL,
to=[to_email]
)
email.content_subtype = "html"
email.send(fail_silently=False)
return JsonResponse({'success':'success'})
you need to import some required things
from django.template.loader import get_template
from django.core.mail import EmailMessage

Adding more fields to send_mail

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

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')

Email in django/python Not Sending [duplicate]

This question already has answers here:
Email sending in django code is not working
(3 answers)
Closed 10 years ago.
I am trying to send a direct email message using django.
It doesn't produce any error, but the message are not sending to the recipient email.
Is there any problem with my codes?
VIEWS.PY
def contact(request):
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():
subject = form.cleaned_data['subject']
message = form.cleaned_data['message']
sender = form.cleaned_data['sender']
cc_myself = form.cleaned_data['cc_myself']
recipients = ['canonizadocharm#ymail.com']
if cc_myself:
recipients.append(sender)
from django.core.mail import send_mail
send_mail(subject, message, sender, recipients)
return HttpResponseRedirect('/thanks/') # Redirect after POST
else:
form = ContactForm() # An unbound form
return render(request, 'contact.html', {
'form': form,
})
MODELS.PY
class ContactForm(forms.Form):
subject = forms.CharField(max_length=100)
message = forms.CharField()
sender = forms.EmailField()
cc_myself = forms.BooleanField(required=False)
SETTINGS.PY
EMAIL_BACKEND = 'django.core.mail.backends.filebased.EmailBackend'
EMAIL_FILE_PATH = '/tmp/app-messages' # change this to a proper location
# Sending mail
EMAIL_USE_TLS = False
EMAIL_HOST='localhost'
EMAIL_PORT= 25
EMAIL_HOST_USER=''
EMAIL_HOST_PASSWORD=''
recipients = ['canonizadocharm#ymail.com',]
EMAIL_USE_TLS = True
EMAIL_HOST='smtp.gmail.com'
EMAIL_PORT=587
EMAIL_HOST_USER='your gmail account'
EMAIL_HOST_PASSWORD='your gmail password'