This repository has been archived by the owner on May 20, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Email.py
84 lines (68 loc) · 2.67 KB
/
Email.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
import re
import socket
import smtplib
import dns.resolver
class Email:
def __init__(self, address, from_address=f"root@{socket.gethostname()}"):
self.address = address
self.from_address = "leejinhuey@gmail.com" # from_address
self.username = self.get_username()
self.domain = self.get_domain()
self.valid = self.check_deliverability()
def get_username(self):
username = str(self.address.split('@')[0])
return username
def get_domain(self):
domain = str(self.address.split('@')[1])
return domain
def validate_email(self):
EMAIL_REGEX = r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)"
match = re.match(EMAIL_REGEX, self.address)
return {'result': (match is not None)}
def check_dns(self):
try:
dns_records = dns.resolver.query(self.domain, 'MX')
except dns.resolver.NXDOMAIN:
return {'result': False, 'message': 'Invalid domain name'}
except dns.resolver.NoAnswer:
return {'result': False, 'message': 'No MX records found'}
mx_record = str(dns_records[0].exchange)
self.mx = mx_record
return {'result': True, 'mx': mx_record}
def check_smtp(self):
try:
server = smtplib.SMTP()
server.connect(self.mx)
server.helo(server.local_hostname)
server.mail(self.from_address)
code, message = server.rcpt(self.address)
server.quit()
if code == 250:
return {'result': True}
else:
return {'result': False, 'message': str(message)}
except smtplib.SMTPServerDisconnected:
return {'result': False, 'message': "SMTP server unexpectedly disconnected"}
except socket.gaierror as error:
return {'result': False, 'message': str(error)}
except socket.timeout:
return {'result': False, 'message': "SMTP server connection timed out"}
except socket.error as error:
return {'result': False, 'message': f"Socker Error: {str(error)}"}
def check_deliverability(self):
validity = {'overall': False}
syntax_valid = self.validate_email()
validity['syntax'] = syntax_valid
if not syntax_valid:
return validity
dns_valid = self.check_dns()
validity['dns'] = dns_valid
if not dns_valid['result']:
return validity
smtp_valid = self.check_smtp()
validity['smtp'] = smtp_valid
if smtp_valid['result']:
validity['overall'] = True
return validity
def __str__(self):
return str(vars(self))