I have a scanning script that currently works by connecting to an SMTP server, printing the results and moving to the next server in the list. This is the first connect code:
def sendchk(listindex, host, user, password): # seperated function for checking
try:
smtp = smtplib.SMTP(host)
smtp.login(user, password)
code = smtp.ehlo()[0]
After the fail "except":
smtp.quit()
except(socket.gaierror, socket.error, socket.herror, smtplib.SMTPException), msg:
print "[-] Login Failed:", host, user, password
pass
I'm trying to get it to repeat the same code with the same host, adding a subdomain. "mail." I thought this would work:
smtp.quit()
except(socket.gaierror, socket.error, socket.herror, smtplib.SMTPException), msg:
print "[-] Login Failed:", host, user, password
sub1 = 'mail.'
host2 = '{0}#{1}'.format(sub1, host)
smtp = smtplib.SMTP(host2)
But it jams, saying there's an issue in server list.
What would be the better way to inject the prefix to the host here?
Without having tested it: if sub1 is "mail." and host is "myhost.com" then '{0}#{1}'.format(sub1, host) will result in mail.#myhost.com. Is that really your subdomain name? I suppose it should be mail.myhost.com. If so then drop the "#" in your formatting string.
Related
I have tested the below code with gmail credentials and it works perfectly, however, when I try to use an email created within a cPanel it does not work. I am certain that the credentials are correct and that I am not being blocked by the server as my email client is working and I can telnet to it.
Is there a way to somehow produce logs to see why exactly it's failing? Using print statements I found that it fails when it gets to the server variable.
import config
import smtplib
class EmailAlert(object):
"""Class for sending email alert from slave account"""
def __init__(self, subject, msg):
self.subject = subject
self.msg = msg
def send_email(self):
try:
server = smtplib.SMTP(config.OUTGOING_SERVER) #It fails here and goes to except
server.ehlo()
server.starttls()
server.login(config.FROM_EMAIL_ADDRESS, config.PASSWORD)
message = 'Subject: {}\n\n{}'.format(self.subject, self.msg)
server.sendmail(config.FROM_EMAIL_ADDRESS,
config.TO_EMAIL_ADDRESS,
message)
server.quit()
print("Success: Email sent!")
except:
print("Email failed to send.")
email = EmailAlert("Test", "test")
email.send_email()
I found that using port 587 works even though the port shown in cPanel's is usually 465.
Any one have idea then please suggest, This is how I'm doing now. bt not working.
Here I'm trying to copy my newtext.wav file to server location.
def copyToServer():
success = os.system("scp D:/AMRITESH/ContractMonitoring/newtext.wav
root#xxx.xxx.x.xxx:/usr/share/asterisk/sounds")
if (success != True):
print(success)
print "Connection Error"
else:
print "Connection Established"
def createSSHClient(server, port, user, password):
client = paramiko.SSHClient()
client.load_system_host_keys()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(server, port, user, password)
print "Connection Established Here"
return client
ssh = createSSHClient('xxx.xxx.x.xxx', 'xx', 'username', 'password')
scp = SCPClient(ssh.get_transport())
print "Sending file to server"
scp.put('D:/AMRITESH/ContractMonitoring/'+fileName, '/usr/share/asterisk/sounds')
I am trying to use Python's smtplib module to send an email but I keep receiving a TimeoutError.
import smtplib
def send():
try:
server = smtplib.SMTP('smtp.gmail.com', 587)
server.ehlo()
server.starttls()
server.login(email, password) # Email and password are already defined
print('Enter recipient: ')
recipient = input()
print('Enter subject:')
subject = input() + '\n'
print('Enter body:')
body = input()
server.sendmail(email, recipient, body)
server.quit()
except TimeoutError as e:
print (str(e))
This code recieves a:
[WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond
It looks like you have not enabled "Allow Less Secure Apps" option in your GMail account.
Here's more officially from Google,
https://support.google.com/accounts/answer/6010255?hl=en
If you are using a VPN connection, disable it first. It worked for me.
Use port 587. I was getting the same error but when I entered 587 as port it worked
smtplib.SMTP("smtp.gmail.com", 587)
I am trying to send an email using SMTP via python.
This is my code:
import smtplib
from email.mime.text import MIMEText
textfile='msg.txt'
you='ashwin#gmail.com'
me='ashwin#gmail.com'
fp = open(textfile, 'rb')
msg = MIMEText(fp.read())
fp.close()
# me == the sender's email address
# you == the recipient's email address
msg['Subject'] = 'The contents of %s' % textfile
msg['From'] = me
msg['To'] = you
print "reached before s"
s = smtplib.SMTP('127.0.0.1',8000)
print "reached after s"
s.sendmail(me, [you], msg.as_string())
s.quit()
when I try and execute this code, "reached before s" is printed and then goes into an infinite loop or so, i.e. "reached after s" is not printed and the program is still running.
This is code for the server:
import sys
import BaseHTTPServer
from SimpleHTTPServer import SimpleHTTPRequestHandler
HandlerClass = SimpleHTTPRequestHandler
ServerClass = BaseHTTPServer.HTTPServer
Protocol = "HTTP/1.0"
if sys.argv[1:]:
port = int(sys.argv[1])
else:
port = 8000
server_address = ('127.0.0.1', port)
HandlerClass.protocol_version = Protocol
httpd = ServerClass(server_address, HandlerClass)
sa = httpd.socket.getsockname()
print "Serving HTTP on", sa[0], "port", sa[1], "..."
httpd.serve_forever()
can someone figure out what is wrong?
I believe yagmail (disclaimer: I'm the maintainer) can be of great help to you.
Its goal is to make it easy to send emails with attachments.
import yagmail
yag = yagmail.SMTP('ashwin#gmail.com', 'yourpassword')
yag.send(to = 'ashwin#gmail.com', subject ='The contents of msg.txt', contents = 'msg.txt')
That's only three lines indeed.
Note that yagmail contents will try to load the string passed. If it cannot, it will send as text, if it can load it, it will attach it.
If you pass a list of strings, it will try to load each string as a file (or, again, just display the text).
Install with pip install yagmail or pip3 install yagmail for Python 3.
More info at github.
Here is a different approach that creates an email sender class with all the error handling taken care of:
import getpass
import smtplib
class EmailBot(object):
# Gets the username and password and sets up the Gmail connection
def __init__(self):
self.username = \
raw_input('Please enter your Gmail address and hit Enter: ')
self.password = \
getpass.getpass('Please enter the password for this email account and hit Enter: ')
self.server = 'smtp.gmail.com'
self.port = 587
print 'Connecting to the server. Please wait a moment...'
try:
self.session = smtplib.SMTP(self.server, self.port)
self.session.ehlo() # Identifying ourself to the server
self.session.starttls() # Puts the SMTP connection in TLS mode. All SMTP commands that follow will be encrypted
self.session.ehlo()
except smtplib.socket.gaierror:
print 'Error connecting. Please try running the program again later.'
sys.exit() # The program will cleanly exit in such an error
try:
self.session.login(self.username, self.password)
del self.password
except smtplib.SMTPAuthenticationError:
print 'Invalid username (%s) and/or password. Please try running the program again later.'\
% self.username
sys.exit() # program will cleanly exit in such an error
def send_message(self, subject, body):
try:
headers = ['From: ' + self.username, 'Subject: ' + subject,
'To: ' + self.username, 'MIME-Version: 1.0',
'Content-Type: text/html']
headers = '\r\n'.join(headers)
self.session.sendmail(self.username, self.username, headers + '''\r\r''' + body)
except smtplib.socket.timeout:
print 'Socket error while sending message. Please try running the program again later.'
sys.exit() # Program cleanly exits
except:
print "Couldn't send message. Please try running the program again later."
sys.exit() # Program cleanly exits
All you need to do is create an EmailBot instance and call the send_message method on it, with the appropriate details as inputs.
I have been trying to verify an email address entered by the user in my program. The code I currently have is:
server = smtplib.SMTP()
server.connect()
server.set_debuglevel(True)
try:
server.verify(email)
except Exception:
return False
finally:
server.quit()
However when I run it I get:
ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it
So what I am asking is how do i verify an email address using the smtp module? I want to check whether the email address actually exists.
Here's a simple way to verify emails. This is minimally modified code from this link. The first part will check if the email address is well-formed, the second part will ping the SMTP server with that address and see if it gets a success code (250) back or not. That being said, this isn't failsafe -- depending how this is set up sometimes every email will be returned as valid. So you should still send a verification email.
email_address = 'example#example.com'
#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('me#domain.com')
code, message = server.rcpt(str(addressToVerify))
server.quit()
# Assume 250 as Success
if code == 250:
print('Y')
else:
print('N')
The server name isn't defined properly along with the port. Depending on how you have your SMTP server you might need to use the login function.
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()
you need to specify the smtp host (server) in the SMTP construct. This depends on the email domain. eg for a gmail address you would need something like gmail-smtp-in.l.google.com.
The server.verify which is a SMTP VRFY probably isnt what you want though. Most servers disable it.
You might want to look at a service like Real Email which has guide for python. How to Validate Email Address in python.