Im having trouble verifying a mass list of email addresses. The issue is with the error code "connection refused" Every email verification returns Connection refused. Why would this be? Can you give me a solution? No issues with verifying the email syntax
The below code is only for the correct area of the programme, i.e mxrecord check. Im using intellij Idea, python 3.4.3 and tkinter for the GUI.
def handle_accuracy(self):
for email in self.emails:
# See if email string contains ampersand and period.
if (email.find('#') < 0) or (email.find('.') < 0):
print("Email not syntactically correct.")
self.inaccurate_emails.append(email)
else:
email_exists = self.check_existence(email)
if email_exists:
print("Email is accurate and exists.")
self.accurate_emails.append(email)
else:
print("Email is syntactically correct but couldn\'t be found")
self.inaccurate_emails.append(email)
def check_existence(self, email):
at_pos = email.find('#')
mx_name = email[(at_pos + 1):]
# Connect to email server and get name of SMTP server
records = dns.resolver.query(mx_name, 'MX')
for record in records:
print(record.exchange)
mxRecord = records[0].exchange
mxRecord = str(mxRecord)
host = socket.gethostname()
# Setup an exception block to handle issues with connection.
try:
server = smtplib.SMTP(mxRecord)
except TimeoutError:
print("Timeout")
# Indicate to calling function that email cannot be found.
return False
except ConnectionRefusedError:
print("Connection Refused")
return False
server.set_debuglevel(0)
# Setup another exception block to handle further issues with connection.
try:
server.connect()
server.helo(host) #needs to have a helo rather than hello
server.mail(email)
code, message = server.rcpt()
except TimeoutError:
print("Timeout")
server.quit()
return False
except ConnectionRefusedError:
print("Connection Refused")
server.quit()
return False
server.quit()
if code == 250:
return True
else:
return False
Thanks in advance.
Related
I wrote the code about the gateway running on VS with python. The problem now is that I have configured the username and password of mqtt and the IP and port of the server, but the return value is rc=4 (bad username or password) , I use wireshark to capture packets, the CONNECT packet I sent is correct, but the return value shows bad username or password
def __doPost(self):
self.__connectMqtt(host = host, port = port, mqttUsername = id, mqttPassword = token)
def __connectMqtt(self,host,port,mqttUsername,mqttPassword):
# Username = mqttUsername.encode("utf-8")
self.mqttc.username_pw_set(username=mqttUsername, password=mqttPassword)
# self.mqttc.subscribe(self.setTopic,1)
self.mqttc.on_connect=self.__on_connect
self.mqttc.on_message=self.__on_message
self.mqttc.on_publish=self.__on_publish
self.mqttc.on_disconnect=self.__on_disconnect
# self.mqttc.tls_set(ca_certs = r"C:\Users\chris\Desktop\MobiusPi-Project-Templates-1.0.5\helloworld-template\src\root.crt")
self.mqttc.connect(host, port, keepalive=200)
# self.publish(message = "SUPCON Test")
self.mqttc.publish_to_mqtt = self.publish_to_mqtt()
# self.mqttc.subscribe_gateway = self.subscribe_gateway()
self.mqttc.loop_forever()
def __on_connect(self,client, userdata, flags, rc):
"""
The value of rc indicates success or not:
0: Connection successful
1: Connection refused - incorrect protocol version
2: Connection refused - invalid client identifier
3: Connection refused - server unavailable
4: Connection refused - bad username or password
5: Connection refused - not authorised
6-255: Currently unused.
"""
if rc==0:
print("Connect successful")
elif rc==1:
print("incorrect protocol version")
elif rc==2:
print("invalid client identifier")
elif rc==3:
print("server unavailable")
elif rc==4:
print("bad username or password")
# print (client,flags)
elif rc==5:
print("not authorised")
elif 6<rc<255:
print("Currently unused")
else:
print("Connect failed")
def __on_message(self,client, userdata, message):
message=message.payload.decode('utf8')
print('receive message:%s'%(message))
def __on_publish(self,client, userdata, mid):
print('publish message success mid:%s'%(mid))
def __on_disconnect(self,client,userdata,rc):
if rc==0:
print('disconnect success')
else:
print('disconnect fail')
oh,i have been solved this problem.because every gateway have clientID, The server I need to connect to needs to specify the client ID, and it is not possible to connect to anything. I need to define the clientID to connect.
if your gateway don't connet the server,and return error is bad username or password, maybe is clientID is error.
this question is somehow similar to python: sending a mail, fails when inside a "with" block .
I'm using Python (3.6) to send emails to mailtrap smtp. Mailtrap actually provides you with the integration code for smtplib which is the one below:
import smtplib
sender = "Private Person <from#smtp.mailtrap.io>"
receiver = "A Test User <to#smtp.mailtrap.io>"
message = f"""\
Subject: Hi Mailtrap
To: {receiver}
From: {sender}
This is a test e-mail message."""
with smtplib.SMTP("smtp.mailtrap.io", 2525) as server:
server.login("<MYUSER>", "<MYPASSWORD>")
server.sendmail(sender, receiver, message)
The code above works just fine if I place it in a module and run it.I go to mailtrap inbox and verify that the email is there. However I want to encapsulate this in a function like this:
import smtplib
from socket import gaierror
def test():
sender = "Test Dev <from#smtp.mailtrap.io>"
receiver = "Test User <to#smtp.mailtrap.io>"
message = f"""\
Subject: Hi there
To: {receiver}
From: {sender}
TESTING"""
try:
with smtplib.SMTP("smtp.mailtrap.io", 2525) as server:
server.login("<MYUSER>", "<MYPASSWORD")
print("Sending email")
server.sendmail(sender, receiver, message)
print('Sent')
except (gaierror, ConnectionRefusedError):
print('Failed to connect to the server. Bad connection settings?')
except smtplib.SMTPServerDisconnected:
print('Failed to connect to the server. Wrong user/password?')
except smtplib.SMTPException as e:
print('SMTP error occurred: ' + str(e))
if __name__ == "__main__":
test()
This doesn't work. WHY? Here is the output:
output image
There's no connection error or any other exception. However I go to mailtrap and don't find the email there.
Is this a mailtrap issue or is it related to smtplib ? I'm cracking my head around this one
I was having this same issue and couldn't wrap my head around it. I did notice that when I made my message an empty string, it worked.
After an embarrassingly long time of searching; I found this post which pointed me to the solution.
You must set the MIME type of the email message. So rather than just passing a string you pass a message object:
message = MIMEText("TEST!")
message["Subject"] = "Alert!"
message["From"] = sender
message["To"] = receiver
... then eventually
server.sendmail(sender, receiver, message.as_string())
my full send email function looks like this:
def send_mail(self):
message = MIMEText("TEST!")
message["Subject"] = "Alert!"
message["From"] = sender
message["To"] = receiver
try:
context = ssl.create_default_context()
with smtplib.SMTP(smtp_server, port) as server:
server.set_debuglevel(1)
server.ehlo() # Can be omitted
server.starttls(context=context)
server.ehlo() # Can be omitted
server.login(login, password)
server.sendmail(sender, receiver, message.as_string())
print('Sent')
except (gaierror, ConnectionRefusedError):
print('Failed to connect to the server. Bad connection settings?')
except smtplib.SMTPServerDisconnected:
print('Failed to connect to the server. Wrong user/password?')
except smtplib.SMTPException as e:
print('SMTP error occurred: ' + str(e))
except Exception as e:
print('everything else')
It's unfortunate that you must specify the sender and receiver in both the message object and sendemail fuction.
I would like to check if an email address exists or not in python 2.7.I used the SMTP server but it does not return any result.
Does anyone have an idea to check if an email address exists or not?
try:
email_address = 'me#exemple.com'
domain_name = email_address.split('#')[1]
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('me#domain.com')
code, message = server.rcpt(str(addressToVerify))
server.quit()
print(code)
# Assume 250 as Success
if code == 250:
print('Y')
else:
print('N')
except Exception as error:
print('Erreur:'+repr(error))
Should I not put the return from this method below in finally ? Pylint gives error for this saying:
3: return statement in finally block may swallow exception (lost-exception)
def sendMessage(self, subject, msgContent, files, mailto):
""" Send the email message
Args:
subject(string): subject for the email
msgContent(string): email message Content
files(List): list of files to be attached
mailto(string): email address to be sent to
"""
msg = self.prepareMail(subject, msgContent, files, mailto)
# connect to server and send email
server=smtplib.SMTP(self.smtpserver, port=self.EMAIL_PORT)
server.ehlo()
# use encrypted SSL mode
server.starttls()
# to make starttls work
server.ehlo()
server.login(self.usrname, self.password)
server.set_debuglevel(self.debug)
try:
failed = server.sendmail(self.mailFrom, mailto, msg.as_string())
except Exception as er:
print er
finally:
server.quit()
if failed:
return False
return True
alright, I fixed the problem, #Nabla pointed the right!!
def sendMessage(self, subject, msgContent, files, mailto):
""" Send the email message
Args:
subject(string): subject for the email
msgContent(string): email message Content
files(List): list of files to be attached
mailto(string): email address to be sent to
"""
msg = self.prepareMail(subject, msgContent, files, mailto)
# connect to server and send email
server = smtplib.SMTP(self.smtpserver, port=self.EMAIL_PORT)
server.ehlo()
# use encrypted SSL mode
server.starttls()
# to make starttls work
server.ehlo()
server.login(self.usrname, self.password)
server.set_debuglevel(self.debug)
try:
server.sendmail(self.mailFrom, mailto, msg.as_string())
except Exception as er:
print er
return False
finally:
server.quit()
return True
This is not a direct answer to your question, but if I may suggest a slightly-different implementation.
Put the connect-to-server and disconnect-from-server in two different methods:
class MyClass():
serverDict = {
"gmail" :"smtp.gmail.com",
"hotmail":"smtp.live.com",
"yahoo" :"smtp.mail.yahoo.com"
}
def __init__(self,username,password):
self.username = username
self.password = password
self.serverName = MyClass.serverDict[username[username.index("#")+1:username.index(".")]]
def sendMessage(self,subject,msgContent,files,mailto):
server = Connect()
if not server:
return False
failed = True
try:
server.login(self.username,self.password)
if not server.sendmail(self.mailFrom,mailto,msg.as_string()):
failed = False
except Exception,error:
print error
Disconnect(server)
return failed
def Connect():
try:
server = smtplib.SMTP(self.serverName)
except smtplib.SMTPException,error:
print error
return None
try:
server.ehlo()
if server.has_extn("starttls"):
server.starttls()
server.ehlo()
except (smtplib.SMTPException,ssl.SSLError),error:
print error
Disconnect(server)
return None
return server
def Disconnect(server):
try:
server.quit()
except smtplib.SMTPException,error:
print error
I have the following code that is part of my email class that I use in my programs. Currently I am running the quit function whether or not a connection to the SMTP server was made in the connect function. I know I could put the quit function inside of the try statement after the email is sent, but I would like to figure out how to write the code to say the equivalent of "if a connection to the server is open, close it." What is the best way to write that in Python?
Thanks!
def connect(self, headers, msg):
try:
self.server.starttls()
try:
self.server.login(self.usrname,self.pswd)
try:
self.server.sendmail(self.sendfrom, self.sendto, headers + "\r\n\r\n" + msg)
except Exception as sendmailfail:
print(sendmailfail)
except Exception as emailfail:
print (emailfail)
except Exception as error:
print(error)
def quit(self):
self.server.quit()
print("The SMTP connection is closed")
first = GmailSmpt('x','y','z','zz')
x , y = first.message()
first.connect(x,y)
first.quit()
You need to finish the "Errors and Exceptions" section of the tutorial.
try:
possibly_fail()
except ...:
handle_exception()
else:
no_exceptions()
finally:
always_run_this()