python也提供了套簡單的方法來進行。
sys.stdout.write("Enter username: ")
username = sys.stdin.readline().strip()
password = getpass("Enter password: ")
try:
s = smtplib.SMTP(server)
try:
s.login(username, password)
except smtplib.SMTPException, e:
print "Authentication failed:", e
sys.exit(1)
s.sendmail(frmaddr, toaddrs, message)
在取得username & password以後,就可以直接呼叫SMTPObject.login(name, pass)
來進行驗證,如果拋出了SMTPException就是驗證失敗囉!
當然也可以先進行SMTPObject.ehlo()後,看有沒有SMTPObject.has_extn('auth'),
來先確認server是否支援身份驗證的。
附件:完整script
沒有留言:
張貼留言