2014-03-06 321 views
5

我一直在嘗試驗證用戶在我的程序中輸入的電子郵件地址。我公司目前擁有的代碼是:如何驗證Python中的電子郵件地址使用smtplib

server = smtplib.SMTP() 
server.connect() 
server.set_debuglevel(True) 
try: 
    server.verify(email) 
except Exception: 
    return False 
finally: 
    server.quit() 

然而,當我運行它,我得到:

ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it 

那麼,我問的是如何驗證使用SMTP模塊的電子郵件地址?我想檢查電子郵件地址是否真的存在。

+3

您需要詳細說明「驗證」是什麼意思。你想檢查地址是否格式正確,或者它是否存在? – goncalopp

+0

https://gist.github.com/blinks/47987 –

回答

5

以下是驗證電子郵件的簡單方法。這是從this link最小修改的代碼。第一部分將檢查電子郵件地址是否格式正確,第二部分將使用該地址ping SMTP服務器並查看它是否獲得成功代碼(250)。話雖如此,這不是安全的 - 取決於如何設置,有時每封電子郵件都會被視爲有效。所以你仍然應該發送驗證郵件。

email_address = '[email protected]' 

#Step 1: Check email 
#Check using Regex that an email meets minimum requirements, throw an error if not 
addressToVerify = email_address 
match = re.match('^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$', addressToVerify) 

if match == None: 
    print('Bad Syntax in ' + addressToVerify) 
    raise ValueError('Bad Syntax') 

#Step 2: Getting MX record 
#Pull domain name from email address 
domain_name = email_address.split('@')[1] 

#get the MX record for the domain 
records = dns.resolver.query(domain_name, 'MX') 
mxRecord = records[0].exchange 
mxRecord = str(mxRecord) 

#Step 3: ping email server 
#check if the email address exists 

# Get local server hostname 
host = socket.gethostname() 

# SMTP lib setup (use debug level for full output) 
server = smtplib.SMTP() 
server.set_debuglevel(0) 

# SMTP Conversation 
server.connect(mxRecord) 
server.helo(host) 
server.mail('[email protected]') 
code, message = server.rcpt(str(addressToVerify)) 
server.quit() 

# Assume 250 as Success 
if code == 250: 
    print('Y') 
else: 
    print('N') 
+0

太棒了!謝謝@verybadatthis。還可以添加導入語句並調整解析器(無法使用** dns.resolver **)? '進口; 來自dns import resolver; 導入套接字; import smtplib;' – propjk007

+0

這不適用於Gmail Id以外的其他電子郵件。如何檢查其他電子郵件域名,如hotmail yahoo等 –

0

服務器名稱未與端口一起正確定義。根據您的SMTP服務器的不同,您可能需要使用登錄功能。

server = smtplib.SMTP(str(SERVER), int(SMTP_PORT)) 
server.connect() 
server.set_debuglevel(True) 
try: 
    server.verify(email) 
except Exception: 
    return False 
finally: 
    server.quit()