from email.utils import getaddresses, formataddr from django import forms from django.utils.translation import ugettext_lazy as _ class EmailListField(forms.CharField): """ A Django form field which validates a list of email addresses. >>> EmailListField().clean('user1@example.com') [u'user1@example.com'] >>> EmailListField().clean('User 1 , User 2 ') [u'User 1 ', u'User 2 '] >>> EmailListField().clean('invalid email address') Traceback (most recent call last): File "", line 1, in File "/home/sciyoshi/chideit/apps/chide/common/mail/forms.py", line 21, in clean raise forms.ValidationError(self.error_messages['invalid']) ValidationError: [u'Please enter a valid list of e-mail addresses.'] >>> EmailListField().clean('"User 3>" < "Abc\@def"@example.com >, User 2 <$A12345@example.com > , 3rd guy ') [u'"User 3>" <"Abc@def"@example.com>', u'User 2 <$A12345@example.com>', u'3rd guy '] """ default_error_messages = { 'invalid': _('Please enter a valid list of e-mail addresses.') } def clean(self, value): value = super(EmailListField, self).clean(value) field = forms.EmailField() try: return [ formataddr((name, field.clean(addr))) for name, addr in getaddresses([value])] except forms.ValidationError: raise forms.ValidationError(self.error_messages['invalid'])