5

I have an application whereby a user can contact me by filling out a form and in the form the user just has to fill in his details and his email and subject.

The code throws no error but I could not receive the mail after setting up everything, but the contact details gets stored in the database as I want it to be stored.

Below is my code.

Models.py

class Contact(models.Model):
    name = models.CharField(max_length=100)
    message = models.TextField()
    sender = models.EmailField()
    phone = models.CharField(max_length=10)
    cc_myself = models.BooleanField(blank=True)
    time = models.DateTimeField(auto_now_add=True, db_index=True)

    def __str__(self):
        return 'Message for {}'.format(self.sender)

Forms.py

class ContactForm(forms.ModelForm):

    class Meta:
        model = Contact
        fields = ['name', 'sender', 'phone', 'message', 'cc_myself']

Views.py

def contact(request):
    if request.method == 'POST':
        contact_form = ContactForm(request.POST)

        if contact_form.is_valid():
            name = contact_form.cleaned_data['name']
            message = contact_form.cleaned_data['message']
            sender = contact_form.cleaned_data['sender']
            phone = contact_form.cleaned_data['phone']
            cc_myself = contact_form.cleaned_data['cc_myself']

            recipients = ['xxxx@gmail.com']
            if cc_myself:
                recipients.append(sender)

            send_mail(name, message, sender, recipients)
            contact_form.save()
            messages.success(request, 'Message sent successfully')
            return redirect('contact:contact')
        else:
            messages.error(request, 'Error sending your Message')

    else:
        contact_form = ContactForm(request.POST)

    context = {
        "contact_form": contact_form,
    }
    template = 'contact.html'
    return render(request, template, context)

gmail server

EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = 'xxx@gmail.com'
EMAIL_HOST_PASSWORD = 'xxxx'
EMAIL_PORT = '587'
EMAIL_USE_TLS = True

terminal output

MIME-Version: 1.0
Content-Type: text/plain; charset="utf-8"
Content-Transfer-Encoding: 7bit
Subject: adie Ugbe
From: abcd@gmail.com
To: xxxx@gmail.com
Date: Sun, 07 Jan 2018 11:11:10 -0000
Message-ID: <20180107111110.29855.10393@1.0.0.127.in-addr.arpa>

oh oh no ooo dddddddd se skan
-------------------------------------------------------------------------------
Successful
King
  • 1,885
  • 3
  • 27
  • 84
  • 2
    Test with fail_silently=False, on your send_mail function, send_mail(name, message, sender, recipients, fail_silently=False) , will raise an smtplib.SMTPException. Maybe is an exception from smtp server. – Maykel Llanes Garcia Dec 29 '17 at 16:00
  • Have you checked "spam" folder in your mail box? – alecxe Jan 04 '18 at 19:18
  • Yes. It’s not there. Not even in sent mail of the sending email – King Jan 04 '18 at 19:22
  • Did you allow the access to your Google account via https://accounts.google.com/DisplayUnlockCaptcha ? – taoufik A Jan 05 '18 at 02:27
  • @King Did you try it with a simple backend like the [console backend](https://docs.djangoproject.com/en/2.0/topics/email/#console-backend)? Knowing whether another backend works as expected would help narrow where the issue is. – Louis Jan 05 '18 at 11:26
  • 1
    Please, search other answers: https://stackoverflow.com/questions/31324005/django-1-8-sending-mail-using-gmail-smtp Be sure that in settings: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' – Nadav Jan 05 '18 at 19:46
  • You could try to see if the porblem is with smtp / gmail or with your way to handle it, by setting EMAIL_BACKEND to `django.core.mail.backends.console.EmailBackend`, and checking the console – Info-Screen Jan 06 '18 at 12:06
  • @Info-Screen, I know. He wrote: " it shows in terminal that the message is being sent"...Maybe he is seeing it because of the console setting as EMAIL_BACKEND... – Nadav Jan 06 '18 at 20:06
  • It prints message sent when I inserted a print statement – King Jan 06 '18 at 23:04
  • I have updated my question to include the terminal output – King Jan 07 '18 at 11:16
  • 1
    found the problem. I realized that I had `EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'` in my settings file. removing it fixed the problem. it was conflicting the smtp – King Jan 07 '18 at 20:35
  • Possible duplicate of [Django 1.8 sending mail using gmail SMTP](https://stackoverflow.com/questions/31324005/django-1-8-sending-mail-using-gmail-smtp) – Louis Jan 17 '18 at 17:04

4 Answers4

2

First off, you're missing your EMAIL_BACKEND

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
addohm
  • 2,248
  • 3
  • 14
  • 40
1

When I am configured it. It sends me email successfully. I have done the code please see it. Visit the link for code: https://www.dropbox.com/s/1ouq5mklq5t51su/mail.zip?dl=0

settings.py:

INSTALLED_APPS = [
    'user',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

STATIC_URL = '/static/'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = 'xxxxx@gmail.com'
EMAIL_HOST_PASSWORD = 'xxxxxxx'
EMAIL_PORT = '587'
EMAIL_USE_TLS = True

views.py:

from django.shortcuts import render,redirect
from user.models import *
from django.core.mail import send_mail
from user.forms import *

def contact(request):
    if request.method == 'POST':
        contact_form = ContactForm(request.POST)

        if contact_form.is_valid():
            name = contact_form.cleaned_data['name']
            message = contact_form.cleaned_data['message']
            sender = contact_form.cleaned_data['sender']
            phone = contact_form.cleaned_data['phone']
            cc_myself = contact_form.cleaned_data['cc_myself']

             recipients = ['xxxxx@gmail.com']
             if cc_myself:
             recipients.append(sender)

             send_mail(name, message, sender, recipients)
             contact_form.save()
             print('Successful')
             return redirect('contact')
        else:
            print('Fails')

    else:
        contact_form = ContactForm(request.POST)

    context = {
        "contact_form": contact_form,
    }
    template = 'contact.html'
    return render(request, template, context)

models.py:

from django.db import models

class Contact(models.Model):
    name = models.CharField(max_length=100)
    message = models.TextField()
    sender = models.EmailField()
    phone = models.CharField(max_length=10)
    cc_myself = models.BooleanField(blank=True)
    time = models.DateTimeField(auto_now_add=True, db_index=True)

    def __str__(self):
        return 'Message for {}'.format(self.sender)

contact.html:

<form method="post">
  {% csrf_token %}
  {{contact_form.as_p}}
  <input type="submit" name="" value="submit">
  </form>
1

From your output,it clearly shows that the email is being logged to the console which means the sending process is being simulated on your console. This technically constitute sending the email.

Anyway, I suspect this is happening because you have your email backend set to

EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'

What you need to do is change the email backend to :

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'

Fadil Olamyy Wahab
  • 626
  • 2
  • 6
  • 15
-1

Django Setting is the trick!

Django sends the emails in background job, and you have to set this ENV VARs correctly if you want to use and external job manager.

maguri
  • 386
  • 2
  • 10