18
19

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Python3でメールアドレスが到達可能かチェックする

Posted at

SESなどを利用していて、バウンスメールを極力排除したい場合。
メールアドレスの正規表現チェックだけでは、メールアドレスとしての書式チェックはできても実際に使える(到達可能な)メールかのチェックができません。

ライブラリdnspythonを使うとDNSからMXレコードを取得できるため、ドメインとアドレスの存在チェックをかけることができます。


dnspythonのインストール

pip install dnspython==1.15.0

または

pip install git+https://github.com/rthalley/dnspython

実装

mail_address_check.py
import re
import dns.resolver
import socket
import smtplib

mail_address = input("input mail address:")

# メールアドレス構文チェック
match = re.match('[A-Za-z0-9._+]+@[A-Za-z]+.[A-Za-z]', mail_address)
if match == None:
    print('Syntax error')
    exit()

# ドメインチェック
mail_domain = re.search("(.*)(@)(.*)", mail_address).group(3) # ドメイン部分の取り出し
try:
    records  = dns.resolver.query(mail_domain, 'MX')
    mxRecord = records[0].exchange
    mxRecord = str(mxRecord)
    print(mxRecord)
except Exception as e:
    print('None of DNS query names exist')
    exit()

# メールアドレス存在チェック
local_host = socket.gethostname()

server = smtplib.SMTP(timeout=5)
server.set_debuglevel(0)

try:
    server.connect(mxRecord)
    server.helo(local_host)
    server.mail('test@example.com')
    code, message = server.rcpt(str(mail_address))
    server.quit()

    if code == 250:
        print('Address exists') # 250 OK
    else:
        print('Address does not exists')
except Exception as e:
    print(e)

実行結果

>python mail_address_check.py
input mail address:hogehogehoge
Syntax error

>python mail_address_check.py
input mail address:hoge@hogefugapiyo.com
None of DNS query names exist

>python mail_address_check.py
input mail address:**********@gmail.com
Address does not exists

参考サイト

Python Email Verification Script

18
19
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
18
19

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?