Proper technique for a contact form? - django

I have a contact form at shantiyoga.ca/contact
With the view
def contact(request):
template = 'contact.html'
form = ContactForm(request.POST or None)
if form.is_valid(): # All validation rules pass
subject = form.cleaned_data['subject']
message = "%s\n\n%s" % (form.cleaned_data['message'], form.cleaned_data['sender'])
cc_myself = form.cleaned_data['cc_myself']
recipients = ['contact#shantiyoga.ca']
sender = form.cleaned_data['sender']
if cc_myself:
recipients.append(sender)
headers = {'Reply-To': form.cleaned_data['sender']}
from django.core.mail import send_mail
send_mail(subject,message,sender,recipients,headers)
return redirect('/thanks/')
return render_to_response(template, {'form': form, 'current':'contact'}, context_instance=RequestContext(request))
Which works fairly well. I'm not terribly sophisticated with Django and my Python skills are not quite up to snuff, so please bear with me if I step through this in a basic fashion.
I would like to clarify that there is no way for the form recipient (contact#shantiyoga.ca) to receive the contact form from the value of the email field (user entered). It will always be sent by the authenticated email in my settings.py, which at this point is my personal email?
A user fills out the contact form and hits submit, an email is sent to contact#shantiyoga.ca from my personal email, and if the user decides to cc themself, a copy of the email is sent to them, also from my personal email.
This is not ideal, should I create an email like contactform#shantiyoga.ca for my settings.py to send the email from?
Also, the headers = {'Reply-To': form.cleaned_data['sender']} does not appear to be doing anything and I can't seem to find documentation describing its proper usage, has anyone had success using this technique?
Thank you for your time,
Noah

I would like to clarify that there is no way for the form recipient (contact#shantiyoga.ca) to receive the contact form from the value of the email field (user entered). It will always be sent by the authenticated email in my settings.py, which at this point is my personal email?
You're setting the sender of the email to sender but using EMAIL_HOST, correct? If this is the case, be careful that your SMTP account will let you send email from users other than your domain. Normally, providing you have an authenticated account on that server, you'll be able to set the From: field to whatever you like.
So in short, this email will hit your inbox appearing to be from the sender variable. So when you hit reply, you'll be able to email them back, which is I think what you want. However, it will be sent using the SMTP server whose authentication details you provide. There is a disconnect between being able to send email (SMTP) and being able to receive it, which I think has got you confused.
I've never tried it, but to add extra headers I believe you need to use the EmailMessage object. According to the docs, you would:
e = EmailMessage(headers={'Reply-To':...
e.send()
Be careful doing this; specifically, be careful to strip out newlines in the reply to field. I do not know if the default clean methods would do this.
Finally, there isn't much wrong with your django/python at all. The only thing I'd say, by way of awareness, is not to use this:
return redirect('/thanks/')
but instead:
return HttpResponseRedirect(reverse('myapp.views.method',args=tuple,kwargs=dict))
This gives you the ability to not hardcode urls into your application. The reverse method will look them up from urls.py for you, so you can move your application around/change urls and it will still work.

Here is signature of send_mail from django documentation:
send_mail(subject, message, from_email, recipient_list, fail_silently=False, auth_user=None, auth_password=None, connection=None)
As you can see it does not have headers argument.
You will need to use EmailMessage object directly.
It would also be nice to remove email-formatting from view. I would write everything something more like this:
from django.core.mail.message import EmailMessage
from django.conf import settings
class ContactsEmailMessage(EmailMessage):
def __init__(self, sender, subject, message, cc_myself):
super(ContactEmailMessage, self).__init__(
subject=subject,
body=self._get_message(self, sender, message),
from=settings.DEFAULT_FROM_EMAIL,
to=settings.CONTACT_RECIPIENTS,
headers=self._get_headers(sender),
cc=(sender, ) if cc_myself else None
)
def _format_message(self, sender, message):
return "%s\n\n%s" % (sender, message)
def _get_headers(self, sender):
return {
'reply-to': sender
}
Now you can write clean and easy to read view:
from myproject.mail.message import ContactsEmailMessage, BadHeaderError
from django.core.exceptions import SuspiciousOperation
def contact(request):
...
form = ContactForm(request.POST or None)
if form.is_valid(): # All validation rules pass
try:
message = ContactsEmailMessage(**form.cleaned_data)
message.send()
except BadHeaderError:
# django will raise this error if user will try to pass suspicious new-line
# characters to "sender" or other fields. This is safe-guard from
# header injections
raise SuspiciousOperation()
return redirect('/thanks/')
...

Related

Django: dynamic changing email recepients

I making a feedback form on website. I made model called 'globalapp' with all settings for future admin, it have email,address and phone fields without permissions for add or delete this objects.
In my views i have a simple code:
def index(request):
seos = SEO.objects.get(id__exact=1)
socs = Social_networks.objects.get(id__exact=1)
globs = globalapp.objects.get(id__exact=1)
index = Index.objects.get(id__exact=1)
form = ContactForm(request.POST)
if form.is_valid():
subject = form.cleaned_data['subject']
sender = form.cleaned_data['sender']
message = form.cleaned_data['message']
fille = form.cleaned_data['fille']
recepients = ['test#test.ru']
from_email, to = sender, recepients
html_content = loader.render_to_string('globalapp/chunks/email_tpl.html',
{'subject': subject, 'sender':sender, 'message':message, 'fille':fille})
msg = EmailMultiAlternatives(subject, html_content, from_email, to)
msg.send()
return render(request, 'globalapp/index.html', {'seos': seos,
'socs': socs,
'globs': globs,
'index': index,
'form': form })
Right now mail sending on test#test.ru. I want to take email field from globalapp object, and put it in 'recepients', to give admin ability to change email address when he needs it.
The best thing that i get yet, i get email value by queryset with:
email = globalapp.objects.filter(id=1).values('email')
by in mail ive got only To: {'email': 'test#gmail.com'}
So question is how to get string from queryset object for dynamic email recepients changing? Or maybe i have option how to do it other way?
Also i have another little problem, that i cant deal with yet: after i push submit button, my page reloading, and i dont need it, can i disable it somehow?
Well there are two problems here:
you use .filter(..), and a filter means you do not get a single dictionary, but a QuerySet of dictionaries. This can be empty, contain one, or multiple elements. Since you filter on id=..., it will contan at most one element, but still it will require some extra logic to unwrap it out of the QuerySet, so we better use .get(..) here; and
we obtain a dictionary, we can retrieve the element associated with the key, by performing an element lookup, so the_dict['email'].
We can tus obtain the email address with:
email = globalapp.objects.values('email').get(id=1)['email']
Or perhaps more elegant:
email = globalapp.objects.values_list('email', flat=True).get(id=1)
Also i have another little problem, that i cant deal with yet: after i push submit button, my page reloading, and i dont need it, can i disable it somehow?
Not with a form, since that is exactly the task the browser is supposed to carry out: send a HTTP request, and load the response. But you can use an AJAX call to perform a HTTP request while the webpage still remains the same.

How to send email to settings.MANAGER in django recipient_list

In Django, I wish to have the send_email send the email to settings.MANAGERS and to the ticket issuer as well. So trying to set those in recipient_list porduced no luck. I am using class based view.
# views.py
...
from django.conf import settings
...
class TicketCreate(CreateView):
model = Ticket
fields = ['title', 'question_detail',]
raise_exception = False
success_url = reverse_lazy('ticket_list')
template_name = 'ticket/ticket_form.html'
def form_valid(self, form):
form.instance.owner = self.request.user
send_mail(
subject=form.cleaned_data.get('title').strip(),
message=form.cleaned_data.get('question_detail'),
from_email=form.cleaned_data.get('request.user.email'),
recipient_list=['settings.MANAGERS','request.user.email',],
)
return super(TicketCreate, self).form_valid(form)
# settings.py
...
MANAGERS = [
('Manager', 'email_id#somedomain.com'),
]
What would be the solution to achieve this?
MANAGERS is a tuple, and only the second element in each tuple is relevant. This will work:
sender = form.cleaned_data.get('request.user.email')
recipients = [a[1] for a in settings.MANAGERS]
recipients.append(sender)
send_mail(
subject=form.cleaned_data.get('title').strip(),
message=form.cleaned_data.get('question_detail'),
from_email=sender,
recipient_list=recipients,
)
The mail_managers function does most of this for you - the only difference being that it doesn't let you control the sender email (it uses SERVER_EMAIL).
Note that you should be very careful about sending mail on behalf of other people - it is only recommended if you control the sender's domain. Otherwise your messages have a good chance of being caught as spam, with the associated reputation risk for the sending server.
Thanks solarissmoke, Because I only let logged in users send the ticket and that all users are required to authenticate with valid email address, I assume users do NOT need to enter email addres again. So, get email from the user data and insert that into the ticket.
Therefore, I modified a bit like below and all work just cool now. Thanks again and you are right about spam stuff - all under my control.
sender=self.request.user.email
recipients = [a[1] for a in settings.MANAGERS]
recipients.append(sender)
send_mail(
subject=form.cleaned_data.get('title').strip(),
message=form.cleaned_data.get('question_detail'),
from_email=sender,
recipient_list=recipients,
)

Send mass mail with hidden recipients

I have a functionality in a Django app to send an email to all the registered users, I'm currently doing it with 'EmailMessage' and it works perfectly but everybody gets to see every other recipient's email which is unwanted.
Is there a way to hide recipients using the Django mailing functions?
Thank you.
when you instantiate EmailMessage class you can provide bcc attribute such as the example.
Here is the EmailMessage class
class EmailMessage(object):
"""
A container for email information.
"""
content_subtype = 'plain'
mixed_subtype = 'mixed'
encoding = None # None => use settings default
def __init__(self, subject='', body='', from_email=None, to=None, bcc=None,
connection=None, attachments=None, headers=None, cc=None):
so if you provide bcc recipient with the attribute name. you can set the target email as bcc recipient.
message = EmailMessage('hello', 'body', bcc=['user#email.com',])
message.send()
http://en.wikipedia.org/wiki/Blind_carbon_copy
https://docs.djangoproject.com/en/1.7/topics/email/
Definitely BCC each address, this should hide them for any recipient. By the looks of the docs you will need to create your own EmailMessage rather than using the predefined wrappers.
You can try this code format if you want to send Mass Email using send_mass_mail() function.
from django.core.mail import send_mass_mail
subject = 'test subject'
message = 'test message'
from_email = 'from#from.com'
recipient_list = ['a#a.com', 'b#b.com', 'c#c.com']
messages = [(subject, message, from_email, [recipient]) for recipient in recipient_list]
send_mass_mail(messages)

Control a function (E.g send mail) from a users profile page

I have a profile page like so: http://i.stack.imgur.com/Rx4kg.png . In management I would like a option "Notify by mail" that would control my send_email functions in every application I want. As example I'm using django-messages and it sends private messages aswell as emails when you send a message. I would like for the user to be able to specify if he wants emails aswell when he gets a message.
messages/utils.py
def new_message_email(sender, instance, signal,
subject_prefix=_(u'New Message: %(subject)s'),
template_name="messages/new_message.html",
default_protocol=None,
*args, **kwargs):
"""
This function sends an email and is called via Django's signal framework.
Optional arguments:
``template_name``: the template to use
``subject_prefix``: prefix for the email subject.
``default_protocol``: default protocol in site URL passed to template
"""
if default_protocol is None:
default_protocol = getattr(settings, 'DEFAULT_HTTP_PROTOCOL', 'http')
if 'created' in kwargs and kwargs['created']:
try:
current_domain = Site.objects.get_current().domain
subject = subject_prefix % {'subject': instance.subject}
message = render_to_string(template_name, {
'site_url': '%s://%s' % (default_protocol, current_domain),
'message': instance,
})
if instance.recipient.email != "":
send_mail(subject, message, settings.DEFAULT_FROM_EMAIL,
[instance.recipient.email,])
except Exception, e:
#print e
pass #fail silently
Apparently instance.recipient.email is the email for the recipient user. So my questions are: How do I go about creating an option in my profile management that can be used in my new_message_email to check if the user wants emails or not? My own thoughts are that I need to save a value in the database for the user and then check for that value in new_message_email function. How I do that isn't clear though. Do I create a new function in my userprofile/views.py and class in userprofile/forms.py? And have my userprofile/overview.html template change them? Some specifics and thoughts if this is the right approach would help alot!
You probably want to start off by creating a user profile so that you have a good way to store weather or not the user wants these emails sent to them. This is done using the AUTH_PROFILE_MODULE setting in your settings.py.
Once you have the data stored, you should be able to access it from instance.recipient (assuming that instance.recipient is a User object). So you could change your code to:
if instance.recipient.get_profile().wants_emails and instance.recipient.email != "":
send_mail(subject, message, settings.DEFAULT_FROM_EMAIL,
[instance.recipient.email,])
Done and done.

satchmo password_reset html format mail

Ive been requested by a client that his satchmo store should send an html formatted mail when resetting his password.
Aparently satchmo or django's contrib.auth.views.password_reset sends only raw email.
How do I modify this in order to be able to send html formatted mails?
Thank you!
I haven't used Satchmo, but this should get you started.
First of all, subclass the PasswordResetForm, and override the save method to send an html email instead of a plain text email.
from django.contrib.auth.forms import PasswordResetForm
class HTMLPasswordResetForm(PasswordResetForm):
def save(self, domain_override=None, email_template_name='registration/password_reset_email.html',
use_https=False, token_generator=default_token_generator, from_email=None, request=None):
"""
Generates a one-use only link for resetting password and sends to the user
"""
# Left as an exercise to the reader
You can use the existing PasswordResetForm as a guide. You need replace the send_mail call at the end with code to send html emails. The docs about sending html emails should help.
Once you've written your form, you need to include the form in the url pattern for password_reset. As I said, I don't have any experience of Satchmo, but looking at the source code, I think you want to update satchmo_store.accounts.urls, by changing the password_reset_dict.
# You need to import your form, or define it in this module
from myapp.forms import HTMLPasswordResetForm
#Dictionary for authentication views
password_reset_dict = {
'template_name': 'registration/password_reset_form.html',
# You might want the change the email template to .html
'email_template_name': 'registration/password_reset.txt',
'password_reset_form': HTMLPasswordResetForm,
}
# the "from email" in password reset is problematic... it is hard coded as None
urlpatterns += patterns('django.contrib.auth.views',
(r'^password_reset/$', 'password_reset', password_reset_dict, 'auth_password_reset'),
...