错误:SMTPRecipientsRefused 553,'5.7.1 #在Django中处理联系表单时
我正在尝试在Django 1.3和Python 2.6中制作一个联系表单。
请问以下错误是怎么回事?
错误信息:
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')}
我的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
补充:如果其他人也在跟着Django书籍,这部分是导致错误的原因:
send_mail(
request.POST['subject'],
request.POST['message'],
request.POST.get('email', 'noreply@example.com'), #get rid of 'email'
['siteowner@example.com'],
1 个回答
14
错误信息里已经说明了问题。你的邮箱服务商拒绝了这封邮件,因为发件人地址是 randomacc@hotmail.com
,这个地址是你从联系表单中拿来的。
你应该用你自己的邮箱地址作为发件人。你可以使用 reply_to
选项,这样回复就会发到你的用户那里。
email = EmailMessage(
'Subject',
'Body goes here',
'test@test.megiteam.pl',
['to@example.com',],
reply_to='randomacc@hotmail.com',
)
email.send()
在 Django 1.7 及更早版本中,没有 reply_to
参数,但你可以手动设置一个 Reply-To
头部信息:
email = EmailMessage(
'Subject',
'Body goes here',
'test@test.megiteam.pl',
['to@example.com',],
headers = {'Reply-To': 'randomacc@hotmail.com'},
)
email.send()
补充:
在评论中你问如何把发件人的地址放在邮件内容里。其实 message
和 from_email
只是字符串,所以你可以在发送邮件之前随意组合它们。
注意,不要从你的 cleaned_data 中获取 from_email
参数。你知道 from_address
应该是 test@test.megiteam.pl
,所以就用这个,或者从你的设置中导入 DEFAULT_FROM_EMAIL
。
如果你像我上面的例子那样使用 EmailMessage
创建邮件,并设置了回复头部,那么当你点击回复按钮时,你的邮件客户端应该会正常处理。下面的例子使用 send_mail
,这样和你提供的 代码 更相似。
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'],
)