mymlyn mymlyn - 24 days ago 9
Python Question

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

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

Whats the reason of following error?

error:

SMTPRecipientsRefused at /contact/
{'test@test.megiteam.pl': (553, '5.7.1 <randomacc@hotmail.com>: Sender address
rejected: not owned by user test@test.megiteam.pl')}


my settings.py:

EMAIL_HOST = 'test.megiteam.pl'
EMAIL_HOST_USER = 'test@test.megiteam.pl'
EMAIL_HOST_PASSWORD = '###'
DEFAULT_FROM_EMAIL = 'test@test.megiteam.pl'
SERVER_EMAIL = 'test@test.megiteam.pl'
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', 'noreply@example.com'), #get rid of 'email'
['siteowner@example.com'],

Answer

The explanation is in the error message. Your email host is rejecting the email because of the sender address randomacc@hotmail.com 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',
    'test@test.megiteam.pl',
    ['to@example.com',],
    reply_to='randomacc@hotmail.com',
)
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 test@test.megiteam.pl, 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
            ['test@test.megiteam.pl'],
        )