[Django]-Sending email from webserver โ€“ django python

7๐Ÿ‘

โœ…

 Make sure first you have properly install django-sendmail

 $ sudo apt-get install sendmail

 in the settings.py :

 from django.core.mail import send_mail

  DEFAULT_FROM_EMAIL='webmaster@localhost' 
  SERVER_EMAIL='root@localhost' 
  EMAIL_HOST = 'localhost' 
  EMAIL_HOST_USER='' 
  EMAIL_BACKEND ='django.core.mail.backends.smtp.EmailBackend' 
  EMAIL_PORT = 25 #587 
  EMAIL_USE_TLS = False

  in views.py:

  from project.apps.contact import ContactForm
  def contactnote(request):
if request.method=='POST':
    form =ContactForm(request.POST)
    if form.is_valid():
        topic=form.cleaned_data['topic']
        message=form.cleaned_data['message']
        sender=form.cleaned_data.get('sender','email_address')
        send_mail(
            topic,
            message,
            sender, 
            ['myaddress@gmail.com'],fail_silently=False
        )
        #return HttpResponseRedirect(reverse('games.views.thanks',  {},RequestContext(request)))
        return render_to_response('contact/thanks.html', {},RequestContext(request)) #good for the reverse method
else:
    form=ContactForm()
return render_to_response('contact.html',{'form':form},RequestContext(request))


contact.py:

from django import forms as forms
from django.forms import Form

TOPIC_CHOICES=(
        ('general', 'General enquiry'),
        ('Gamebling problem','Gamebling problem'),
        ('suggestion','Suggestion'),
)


class ContactForm(forms.Form):
topic=forms.ChoiceField(choices=TOPIC_CHOICES)
sender=forms.EmailField(required=False)
message=forms.CharField(widget=forms.Textarea)
#the widget here would specify a form with a comment that uses a larger Textarea   widget, rather than the default TextInput widget.

def clean_message(self):
    message=self.cleaned_data.get('message','')
    num_words=len(message.split())
    if num_words <4:
        raise forms.ValidationError("Not enough words!")
    return message

  Try it , this is a whole working example apps, modify it
  to be send to to mailserver like a reply when it got an mail, very simple to modify it
๐Ÿ‘คuser2699980

Leave a comment