0

I am new to Django development. I have a contact message form which sends the data collected from the form to the recipient and saves the form in the database as well (sqlite).

The code for views.py:

def contact(request):
    if request.method == 'POST':
        from django.core.mail import send_mail
        form = MessageForm(request.POST or None)
        if form.is_valid():
            name = form.cleaned_data['name']
            sender = form.cleaned_data['email']
            telephone = form.cleaned_data['telephone']
            subject = "Contact Us Form - Message"

            message = "From: " + name + " ( " + sender + " ) " + "Phone: " + telephone + "\n\n"
            message += form.cleaned_data['message']

            recipients = ['somdip@steanne.co.uk']
            save_it = form.save(commit=False)
            save_it.save()
            result = "Your message has been delivered. Thank you for contacting us! We will get in touch very soon.."
            try:
                send_mail(subject, message, sender, recipients)
            except smtplib.SMTPException:
                result = smtplib.SMTPException.message
            return render(request, "contactus.html", {"result": result, "style": "display: block", 'form': form})
        else:
            return render(request, "contactus.html", {"result": "Failed to send the message. Please validate your data. ",
                                                    "style": "display: block", 'form': form})
    else:
        form = MessageForm()
    return render_to_response('contactus.html', {'form': form},  context_instance=RequestContext(request))

the code in the forms.py:

class MessageForm(forms.ModelForm):
    class Meta:
        model = Message
        name = forms.CharField(label='Name *', max_length=120)
        email = forms.EmailField(label='Email *', max_length=120)
        telephone = forms.CharField(label='Telephone *', max_length=120)
        message = forms.CharField(label='Message *', max_length=2000, widget=forms.Textarea)

the code in the models.py:

class Message(models.Model):
    name = models.CharField(max_length=120, null=False, blank=False)
    email = models.EmailField(null=False,  blank=False)
    telephone = models.CharField(max_length=120, null=True, blank=True)
    message = models.TextField(max_length=2000, null=False, blank=False)
    timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)

    def __unicode__(self):
        return smart_unicode(self.email)

in the settings.py I have also added:

#Email Sending for ContactForm
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 465
EMAIL_HOST_USER = 'SECRET'
EMAIL_HOST_PASSWORD = 'SECRET'
EMAIL_USE_SSL = True

When I am pressing submit, it is giving me an exception error:

attribute 'message' of 'exceptions.BaseException' objects

halfer
  • 19,824
  • 17
  • 99
  • 186
Somdip Dey
  • 3,346
  • 6
  • 28
  • 60

1 Answers1

0

You are not seeing an exception, you are simply seeing the output of this:

>>> smtplib.SMTPException.message
<attribute 'message' of 'exceptions.BaseException' objects>

In this line:

    result = smtplib.SMTPException.message

you are referring to the message attribute of the type smtplib.SMTPException, but you actually need to access message of an instance of the exception. Your code should read:

try:
    send_mail(subject, message, sender, recipients)
except smtplib.SMTPException as e:
    result = e.message
#    result = str(e)    # preferred!!! (see below)

In the above, the exception instance is bound to variable e from which you can access its message attribute.

Note, however, that the message attribute has been deprecated as of Python 2.6. This should issue a warning (unless Python is run with -W error which will generate an error). In Python 3 the attribute is no longer present and an exception will be raised.

Try this instead:

try:
    send_mail(subject, message, sender, recipients)
except smtplib.SMTPException as e:
    result = str(e)
mhawke
  • 84,695
  • 9
  • 117
  • 138