验证电子邮件消息是否正确的收件人电子邮件地址的正确方法是什么?
我正在使用 Django 开发一个应用程序。在存储表单类的 forms.py 中,我编写了一个干净的函数来验证输入到文本框中的所有电子邮件是否都遵循正确的格式([电子邮件受保护])。
在这个干净的函数中,我使用 EmailMessage 对象构建电子邮件消息:
def clean_recipients(self):
rec = self.data['recipients'].split(",")
recList = []
for recipient in rec:
reci = str.strip(str(recipient))
recList.append(reci)
message = (self.data['subject'], self.data['message'], '[email protected]', recList)
mail = EmailMessage(self.data['subject'], self.data['message'], '[email protected]', ['[email protected]'], recList)
try:
mail.send(fail_silently=False)
except Exception:
raise forms.ValidationError('Please check inputted emails for validity.')
return self.data['recipients']
但是,无论我在文本框中输入什么内容,表单上都不会引发异常“请检查输入的电子邮件的有效性。”。如果我在文本框中输入随机字符,则不会发送任何消息。
如果电子邮件未正确发送,捕获的正确方法是什么?
谢谢。
I am developing an application with Django. In forms.py, where the classes for my forms are stored, I have written a clean function to verify that all the emails typed into a textbox adhere to the proper format ([email protected]).
In this clean function, I build the email message with an EmailMessage object:
def clean_recipients(self):
rec = self.data['recipients'].split(",")
recList = []
for recipient in rec:
reci = str.strip(str(recipient))
recList.append(reci)
message = (self.data['subject'], self.data['message'], '[email protected]', recList)
mail = EmailMessage(self.data['subject'], self.data['message'], '[email protected]', ['[email protected]'], recList)
try:
mail.send(fail_silently=False)
except Exception:
raise forms.ValidationError('Please check inputted emails for validity.')
return self.data['recipients']
However, the exception 'Please check inputted emails for validity.' is never raised on the form regardless of what I input into the textbox. If I input random characters into the textbox, simply no message is sent.
What is the proper way to catch if the email was not sent properly?
Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
尝试仅在 clean_recipients 中清理收件人电子邮件格式。有一个如何检查电子邮件的片段。 http://djangosnippets.org/snippets/1093/ 。如果电子邮件格式不匹配,则会引发验证错误。
创建电子邮件并从表单的 clean 方法(如果您需要显示发送错误。您需要在发送之前检查表单错误。)或从视图发送。
附言。以这种方式获取数据 - self.cleaned_data 而不是 self.data。
Try to clean recipients emails format only in the clean_recipients. There is snippet how to check email. http://djangosnippets.org/snippets/1093/ . Raise validation error if email format does not match.
Create email and send it from the form's clean method (if you need show sending errors. You will need check for form errors before send.) or from the view.
PS. get your data this way - self.cleaned_data instead of self.data.