Error: SMTPRecipientsRefused 553, '5.7.1 #while working on contact form in django

mmln picture mmln · Feb 14, 2012 · Viewed 13.1k times · Source

im trying to make a contact form in django 1.3, python 2.6.

Whats the reason of following error?

error:

SMTPRecipientsRefused at /contact/
{'[email protected]': (553, '5.7.1 <[email protected]>: Sender address
rejected: not owned by user [email protected]')}

my settings.py:

EMAIL_HOST = 'test.megiteam.pl'
EMAIL_HOST_USER = '[email protected]'
EMAIL_HOST_PASSWORD = '###' 
DEFAULT_FROM_EMAIL = '[email protected]'
SERVER_EMAIL = '[email protected]'
EMAIL_USE_TLS = True

edit: If any1 else was following djangobook, this is the part causing it:

        send_mail(
            request.POST['subject'],
            request.POST['message'],
            request.POST.get('email', '[email protected]'), #get rid of 'email'
            ['[email protected]'],

Answer

Alasdair picture Alasdair · Feb 14, 2012

The explanation is in the error message. Your email host is rejecting the email because of the sender address [email protected] that you have taken from the contact form.

Instead, you should use your own email address as the sender address. You can use the reply_to option so that replies go to your user.

email = EmailMessage(
    'Subject',
    'Body goes here',
    '[email protected]',
    ['[email protected]',],
    reply_to='[email protected]',
)
email.send()

On Django 1.7 and earlier, there isn't a reply_to argument, but you can manually set a Reply-To header:

email = EmailMessage(
    'Subject',
    'Body goes here',
    '[email protected]',
    ['[email protected]',],
    headers = {'Reply-To': '[email protected]'},
)
email.send()

Edit:

In the comments you asked how to include the sender's address in the message body. The message and from_email are just strings, so you can combine them however you want before you send the email.

Note that you shouldn't get the from_email argument from your cleaned_data. You know that the from_address should be [email protected], so use that, or maybe import DEFAULT_FROM_EMAIL from your settings.

Note that if you create a message using EmailMessage as in my example above, and set the reply to header, then your email client should do the right thing when you hit the reply button. The example below uses send_mail to keep it similar to the code you linked to.

from django.conf import settings

...
    if form.is_valid():
        cd = form.cleaned_data
        message = cd['message']
        # construct the message body from the form's cleaned data
        body = """\
from: %s
message: %s""" % (cd['email'], cd['message'])
        send_mail(
            cd['subject'],
            body,
            settings.DEFAULT_FROM_EMAIL, # use your email address, not the one from the form
            ['[email protected]'],
        )