Checking if email is valid

Chris Angelico rosuav at gmail.com
Wed Nov 1 15:11:03 EDT 2023


On Thu, 2 Nov 2023 at 06:02, Jon Ribbens via Python-list
<python-list at python.org> wrote:
>
> On 2023-11-01, Chris Angelico <rosuav at gmail.com> wrote:
> > On Thu, 2 Nov 2023 at 05:21, Simon Connah via Python-list
> ><python-list at python.org> wrote:
> >> Could someone push me in the right direction please? I just want to
> >> find out if a string is a valid email address.
> >
> > There is only one way to know that a string is a valid email address,
> > and that's to send an email to it.
> >
> > What is your goal though? For example, if you're trying to autolink
> > email addresses in text, you don't really care whether it's valid,
> > only that it looks like an address.
>
> There's often value in even only partially-effective checks though.
> With an email address you can easily check to see if it has an "@",
> and if the stuff after the "@" is a syntactically valid domain name.
> You can also go a bit further and check to see if the domain has an
> MX record, and if it doesn't then it is extremely unlikely that the
> address is valid.

Yeah, which is why I asked about the goal. (You may also note that I
worded the prior statement very carefully: You cannot know that it IS
valid without sending email to it, but there can be ways to know that
it CANNOT BE valid.)

In the vast majority of contexts, local addresses can be ignored, so
an email address will have to include an at sign. I wouldn't bother
with a syntax check on the domain portion, though; just check for a
couple of possible formats (IP literal), and if it looks like a domain
name, do the MX lookup. That said, though, there are certain contexts
where you can be a LOT more restrictive, such as the autolinking
example I mentioned; it's fine to exclude some unusual email addresses
when all you're doing is offering a small convenience.

ChrisA


More information about the Python-list mailing list