Personalizing 'to' field with EmailMultiAlternatives - django

I'm using EmailMultiAlternatives to serve a lot of our emails to customers. We'd ideally like to change the 'to' field so that it reflects their name rather than the email address itself, as apparently that makes spam filters less likely to block your email.
I know how to change the from field from this:
msg = EmailMultiAlternatives("subject", text_content, "from#bla", ["to#bla"])
to this:
msg = EmailMultiAlternatives("subject", text_content, "from, bla <from#bla>", ["to#bla"])
but this doesn't seem to work for the 'to' field.
Any suggestions for how I could fix the 'to' field too?
Thanks!

This will work for a to field:
msg = EmailMultiAlternatives("subject", text_content,
"from#example.com",
["Some Name <to#example.com>"])
What will fail is the presence of a comma (,) anywhere in the recipient string, because Django will split the recipient into two at that point. This is pretty hard baked into the underlying EmailMessage class and you would have to override it non-trivially if you wanted to change that behaviour.
That said, I am not sure it is worth the effort. I don't know many email clients that show you the name that was in the To: field (given that, well, it's you), and in the absence of evidence to the contrary I would say that it can't be a key factor in spam scoring because most bulk senders out there just use a plain email address in the To: field.

Related

Default regex django uses to validate email

recently, I started playing with Django and created a custom form for user registration. In that form to create the field for email I use something like
email = forms.EmailField()
I observed that address such as a#a.a is considered invalid by the form. Of course this is a nonsense email address. Nonetheless, I wonder how does Django checks for validity.
I found some topics on the net discussing how to check for validity of an email address but all of them were providing some custom ways. Couldn't find something talking about the django default validator.
In their docs on the email filed they specify
Uses EmailValidator to validate that the given value is a valid email address, using a moderately complex regular expression.
However that's not very specific so I decided to ask here.
For anyone also interested in this, I would suggest looking up the implementation (django.core.validators) as was kindly suggested by iklinac in the comments.
In it, there is not just the source but also mentions about standards that were used to derive regexes that check if domain and literal have valid format.
us should check docs here https://www.geeksforgeeks.org/emailfield-django-forms/#:~:text=EmailField%20in%20Django%20Forms%20is,max_length%20and%20min_length%20are%20provided.
if u wanna check validation use clean function like this :
from django.forms.fields import EmailField
email = EmailField()
my_email = "a#a.a"
print(email.clean(my_email))
if your email is valid then this func return value else return validation error

Way to pass information from a GET parameter to a POST form in django?

I have a mailing list system in which a user can click a link to unsubscribe. This link contains the user's email in a GET parameter and the page it points to contains a short form to ask for feedback. This feedback needs to point to the email of the user who submitted it.
The way I tried to achieve this is:
take the email from the GET parameter
put it as initial value in a hidden field on the feedback form
retrieve it from form data when the form is sent
The problem is that if this hidden field is not disabled, the user can meddle with its value and dissimulate his own identity or even claim that the feedback came from another user. But if I set the field as disabled, the request.POST dictionary does not contain the field at all.
I also tried keeping the field enabled and checking for its presence in form.changed_data, but it seems to always be present there even if its value does not change.
This is the form class:
class UnsubscribeForm(forms.Form):
reason = forms.ChoiceField(choices=UnsubscribeFeedback.Reasons.choices)
comment = forms.CharField(widget=forms.Textarea, required=False)
user_email = forms.CharField(widget=forms.HiddenInput, required=False, disabled=False)
This is how I populate user_email in the view when the method is GET:
email = request.GET.get("email", "")
# ...
context["form"] = UnsubscribeForm(initial={"user_email": email})
Note that I also tried disabling the field manually after this line, as well as in the form's init method. The result is the same: if the field is disabled, the value does not get passed.
After setting the initial value, I print()ed it to make sure it was being set correctly, and it is. I also checked the page's source code, which showed the value correctly.
And this is how I check for the value in the POST part of the view, when the data-bound form is being received:
form = UnsubscribeForm(request.POST)
if form.is_valid(): # This passes whether I change the value or not.
if "user_email" in form.changed_data: # This too passes whether I change the value or not.
print("Changed!")
email = form.cleaned_data["user_email"] # This is "" if user_email is disabled, else the correct value.
I have no idea why the initial value I set is being ignored when the field is disabled. As far as I know, a disabled field passes the initial value over regardless of any changes, but here the initial value isn't being passed at all. And as I outlined above, I can't afford to keep this field editable by the user, even if it's hidden.
Django is version 3.0.3, if that matters.
Any solution? Is this a bug?
I found a solution to my problem, though it doesn't quite answer the question of why disabled fields ignore runtime initial values, so in a sense, the question is still open to answers.
In the original question, I crucially neglected to specify (in an effort to make the code minimal and reproducible) that the GET request that includes the user's email address also contains a token I generate with unpredictable data to verify that the email is authentic and corresponds to a subscribed user. In order to successfully meddle with the email, a user would also have to forge a valid token, which is unlikely (and not worth the effort) unless they have access to both my database and codebase (in which case I have worse problems than a feedback form).
I will simply keep the hidden field not disabled and also pass the token along, to verify that the address is indeed valid.

Django forms EmailValidation not working

I have been researching on this issue but it seems there's not a lot of explanation around there covering this.
...
class RangerRegistrationForm(RegistrationFormUniqueEmail):
email = forms.EmailField(label=_("Email Address"), validators=[EmailValidator(whitelist=['gmail.com'])])
...
Here's the part of my script where I check if the user supplies a gmail account. Unfortunately, as long as it's a valid email it will always pass the check.
What am I doing wrong here?
This is NOT a bug in Django (re-read the source code link posted in #catavaran's answer).
A whitelist in this case is not a "block everything except for this domain part" solution. Rather, the whitelist is a domain part that would otherwise be flagged as invalid by Django's EmailValidator.
For example, the default whitelist is set to domain_whitelist = ['localhost']...an otherwise invalid domain_part that is being flagged as being OK for this use case.
To validate the domain part of an email field, you are going to need to write your own clean function. Something like:
class RangerRegistrationForm(forms.Form):
email = forms.EmailField(label=_("Email Address"))
def clean_email(self):
submitted_data = self.cleaned_data['email']
if '#gmail.com' not in submitted_data:
raise forms.ValidationError('You must register using a Gmail address')
return submitted_data
Congratulations! You had found a bug in Django.
Look at this code from the EmailValidator:
if (domain_part not in self.domain_whitelist and
not self.validate_domain_part(domain_part)):
...
If the domain part of the e-mail is valid then checking against the self.domain_whitelist just ignored.

Laravel 4 regex email validation

I am trying to add validation, inside my User model to validation emails using regex.
However, it's spits a dummy out at the first apostrophe.
'email' => 'required|regex:/^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+#[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/',
Have you tried the 'email' validation rule?
'email' => 'required|email|unique:users,email'
http://laravel.com/docs/4.2/validation#rule-email
As the answer to this question on SO states, there is no simple regular expression to validate an email-address. Using your RegEx could maybe catch valid addresses (although that's just speculation of mine). Using the email-validation-rule would be my first choice.
But you are right, this is just the server side in the first place, if you ignore redirecting users back with input and error messages..
On the client-side, you would have some options. The first one would be to simply rely on the build in browser-validation, by declaring the corresponding input-field as an email-address which you should do anyway:
{{ Form::email($name, $value = null, $attributes = array()) }}
Another, more advanced way would be to create some kind of helper to check the typed input via Ajax using the same validation rule and returning the error messages or sth. similar. This could be an additional route to your Model-Resource for example. This way, you would be stable and consistent.

Django ModelForm Validate custom Autocomplete for M2M, instead of ugly Multi-Select

Given the following models (cut down for understanding):
class Venue(models.Model):
name = models.CharField(unique=True)
class Band(models.Model):
name = models.CharField(unique=True)
class Event(models.Model):
name = models.CharField(max_length=50, unique=True)
bands = models.ManyToManyField(Band)
venue = models.ForeignKey(Venue)
start = models.DateField()
end = models.DateField()
The admin area works great for what I'm doing, but I'd like to open the site up a bit so that certain users can add new Events. For the public portions, I have several "administrative" fields on these models that I don't want the public to see (which is easy enough to fix).
My specific problem, though, is changing the display of the ManyToMany selections when creating a new Event. Because the number of Bands possible to list for an event should not be sent along as a multiselect box, I'd like to use an AutoComplete that handles multiples (like the Tags box, here on StackOverflow!).
I have this part working, and it correctly fills in a hidden input with the Band.id's separated by commas for a value. However, I can't understand how to put together letting Django do the validation using the ModelForms, and somehow also validating the 'Bands' selection.
Ideally, I want to auto-complete like the tags here on StackOverflow, and send along the selected Bands ID's in some kind of Delimited string - all while letting Django validate that the bands passed exist, etc, as if I left the annoying multi-select list in place.
Do I have to create my own Auto-Complete Field type for a form or model, and use that? Is there something else I'm overlooking?
I have seen some existing AutoComplete widgets, but I'd really-really-really like to use my own Autocomplete code, since it's already set up, and some of them look a bit convoluted.
There was a lot more text/explanation here, but I cut back because I'm avoiding Wall Of Text. If I left important stuff out, let me know.
It's a little hard to say without knowing exactly what your autocomplete code is doing, but as long as it is sending the ids of the bands like they would be sent with the <select>, the ModelForm should validate them as usual.
Basically, your POST string should look like:
name=FooBar2009&bands=1&bands=3&bands=4&venue=7&start=...
The easiest way to do this might be to use Javascript to add (and remove) a hidden input field for each band entered with the name band and the id of the band as the value. Then, when the user submits the form, the browser will take care of posting the right stuff, and the ModelForm will validate it.
Using the annointed jquery autocomplete plugin,
On the client-side I have something like this:
jQuery("#id_tags").autocomplete('/tagging_utils/autocomplete/tasks/task/', {
max: 10,
highlight: false,
multiple: true,
multipleSeparator: " ",
scroll: true,
scrollHeight: 300,
matchContains: true,
autoFill: true,
});
So, I have a view that returns when I type in a:
http://skyl.org/tagging_utils/autocomplete/tasks/task/?q=a&limit=10&timestamp=1259652876009
You can see the view that serves that here:
http://github.com/skyl/skyl.org/blob/master/apps/tagging_utils/views.py
Now, it's going to be a little tricky .. you might except the POST, then in the clean method of the field try to .get() based on the strings and raise a form validation error if you can't get it ... right, name = ... unique=True .. so something like (off the top of my head) ... :
def clean_bands(self):
return Band.objects.filter( name__in = self.cleaned_data['bands'].split(' ') )
You could also check each string and raise a form error if there are no bands by that name .. not sure that the clean method should return a qs. Let me know if this helps and you want me to keep going/clarify.