how to read the pop server response in python - python

I am trying to read the response or exception of pop3 hotmail server. its very simple question but i am beginner in python don't know how to read it? this is my code:
import poplib
import sys
host = 'pop3.live.com'
port = 995
email='123456#hotmail.com'
pwd='123456'
server = poplib.POP3_SSL(host, port)
try:
server.user(email)
server.pass_(pwd)
if('+OK'):
print 'Email: '+email+'password: '+pwd
server.quit()
sys.exit(1)
except poplib.error_proto:
if('POP+disabled'):
print 'Email: '+email+'password: '+pwd
server.quit()
sys.exit(1)
elif('authentication+failed'):
print "wronge user and pass. try again"
continue
continue
in exception "if ('POP+disabled')" used to eliminate that user login and password is correct but the account has not enabled POP3 in options.
when I run the above code then it also display email password whether i put wrong password...
Can any body help me please how to handle this problem?

You can use the server.getwelcome() method to check for the server response before proceeding into parsing messages.
The server object lets you request the list of messages after authentication and then you can call retr to retrieve each message.
welcomeresp = server.getwelcome()
if welcomeresp.find("+OK"):
numMessages = len(server.list()[1])
for i in range(numMessages):
for j in server.retr(i+1):
server_msg, body, octets = j
for line in body:
print line
Take a look at the documentation for the POP library for more information and an example:
https://docs.python.org/2/library/poplib.html

Related

Accessing Gmail SMTP via Python - AUTH issues

I'm writing this currently for an assignment but years back I had the same problem and just gave up. Further searches had me try a variety of things and I cannot get past the login portion.
from socket import *
from ssl import *
msg = "\r\n I love computer networks!"
endmsg = "\r\n.\r\n"
clientSocket = socket(AF_INET, SOCK_STREAM)
mailserver = getaddrinfo('smtp.gmail.com',465, AF_INET, SOCK_STREAM, IPPROTO_TCP)[0][4]
clientSocket = wrap_socket(clientSocket)
clientSocket.connect(mailserver)
recv = clientSocket.recv(1024)
print recv
if recv[:3] != '220':
print '220 reply not received from server.'
clientSocket.send('EHLO Nolan\r\n')
recv = clientSocket.recv(1024)
print recv
if recv1[:3] != '250':
print '250 reply not received from server.'
clientSocket.send('AUTH LOGIN ' + 'my Google email'.encode('base64','strict'))
recv = clientSocket.recv(1024)
print recv
print recv.split()[1].decode('base64')
clientSocket.send("my password".encode('base64','strict'))
recv = clientSocket.recv(1024)
print recv
# And onto other tasks
I'm under the impression I don't need STARTTLS as I start the connection with SSL. If I change AUTH LOGIN to AUTH PLAIN it doesn't know how to decode it. If I use PLAIN but don't encode it my program just hangs. If I terminate it with "\n\r" (not encoded) I get a broken pipe. Using the code above I get the password request.
Then sending the password I get 535-5.7.8 Username and Password not excepted.It's the same password I sign in with?!? I already setup my account to allow less secure devices. 2-step verification... started the process seems to be orientated to mobile phones, not my python app.
I've changed EHLO to use my IP, as I believe RFC 5321 says that's how it should be. Didn't matter.
I've looked through RFC 4954...
I dug into smtplib to uncover "AUTH PLAIN " + encode_base64("\0%s\0%s" % (user,pass),eol='') Just hangs... waiting...
I have no clue.
Update
I changed the smtplib to output every string submitted. This confuses me even more:
ehlo [127.0.1.1]
AUTH PLAIN [almost forgot one can decode this base64]==
mail FROM:<[gmail account]>
rcpt TO:<[hotmail account]>
data
quit
My AUTH string is exactly the same but it hangs. And I am receiving the email at my hotmail account (using smtplib, not my code).
If you want a basic, non-SSL connection to Gmail, you can use this:
import smtplib
gmail = smtplib.SMTP("smtp.gmail.com",587)
gmail.ehlo() #open the connection
gmail.starttls()
gmail.login("gmaillogin","gmailpassword") #login*
gmail.quit() #close the connection
*Note: You will need to generate a gmail application password from your google account.
Edit:
If you want to use SSL encryption, use this (thanks to furas):
import smtplib
gmail = smtp.SMTP_SSL("smtp.gmail.com",465)
gmail.ehlo()
gmail.login("gmaillogin","gmailpassword")
gmail.quit()
As is typically my fashion, it's the simple things. I just spent hours looking over one program and Googling only to have one error pop out at me: the parameter order in my definition was not how I used it in my code.
Here... I changed my code to use AUTH PLAIN and the issue... I had been putting in '\n\r' not '\r\n' (if I had ended the command with anything, only omitted because '\n\r' produced errors on some commands and went through okay on others). Thank you for classical music to study by on your favorite streaming video site. It raised my intelligence briefly. :)
clientSocket.send('AUTH PLAIN ' + encode_base64("\0%s\0%s" % ([email],[password]), eol="") + '\r\n')

Sending reports from my python script using gmail smtp

I'm trying to send email to myself with all reports collect each day from my scripts and below is the code I'm using to send the email.
# Import smtplib for the actual sending function
import smtplib
# Import the email modules we'll need
from email.mime.text import MIMEText
def send_email(message="", subject="EReport of Twitter Bot"):
msg = MIMEText(message)
# me == the sender's email address
# you == the recipient's email address
msg['Subject'] = subject
msg['From'] = 'r****#gmail.com'
msg['To'] = 'r****#gmail.com'
# Send the message via our own SMTP server, but don't include the
# envelope header.
try:
s = smtplib.SMTP('smtp.gmail.com',465)
s.ehlo()
s.starttls()
s.ehlo()
s.login('r****#gmail.com', 'mypassword')
s.sendmail('r****#gmail.com', 'r****#gmail.com', msg.as_string())
s.quit()
return True
except Exception as e:
print e
return False
if __name__ == "__main__":
if send_email(message="Hello Ravi!"):
print "Successfully sent the mail"
else:
print "Sorry"
However, I get Connection unexpectedly closed when using the port 465. And If I use port 587 I get the following
(534, '5.7.14 <https://accounts.google.com/ContinueSignIn?sarp=1&scc=1&plt=AKgnsbvkf\n5.7.14 g4kEFJrti_fMva0wSRWGl4KfuNsFhQumLhgzMCUlPCQn2dvYdPCDr03l9luBP2XTwcnf_N\n5.7.14 BNsPV2jZhLOPjFOSYtGM16Wb6A1BlmLvMP1_mMHoeo4plSVNGio8EDCx_RMW7HcJdYcpx9\n5.7.14 T5SHwceKzRdpUXHxdL2icc0KAMDtb1dDLDr389N_s-tnSkylcN0bwctBA0tKF2k0AC6OsX\n5.7.14 jIcP7iV3ArV6PEB2ZXPCOI2gRPg0> Please log in via your web browser and\n5.7.14 then try again.\n5.7.14 Learn more at\n5.7.14 https://support.google.com/mail/answer/78754 lq10sm97657764pab.36 - smtp')
Which basically means my server is not trust worthy, although reverse-dns on my server's ip returns valid rent-history.com
Does anyone know what I can do/try to fix this?
Port 465 is used for SSL, port 587 not.
You should use SMTP_SSL when you intend to use secure connection (port 465), and SMTP with port 587.
Also, I'd like to point out yagmail; I developed it.
You can just use:
import yagmail
yag = yagmail.SMTP('r****#gmail.com', 'pw') # or yagmail.SMTP_SSL for port 465
yag.send('r****#gmail.com', "EReport of Twitter Bot", message)
Furthermore, it makes it easy to:
write the script in a passwordless manner
adding files by filenames (and it will automatically attach it using the correct mimetype)
it automatically sends HTML emails and uses plain text fallback
Install using pip (works for both python 2 and 3):
pip install yagmail
You may need to log into whatever gmail account you are using and go to the less secure apps secion to enable access via a less secure app, such as your program. Obviously, this decreases the account's security, so I don't recommend you do this with a personal account.

Python SMTP.login not working

Hi guys I'm writing a program to send and email from one email to another from the command line. Below is my program so far but I can't seem to get session.login(sender, password) to work. When I get rid of the "Try, except" function I get an error saying "SMTP AUTH extension not available on this server". I'm stuck and need help.
import smtplib
sender = raw_input("Please put in your e-mail")
password = raw_input("Email password please")
recipient = raw_input("Please put person e-mail")
message = raw_input("Insert message")
try:
session = smtplib.SMTP("smtp.gmail.com:587")
session.ehlo()
session.starttls
session.ehlo()
#having issues with this specific command
session.login(sender, password)
session.sendmail(sender, recipient, message)
session.quit
print("message sent :)")
except smtplib.SMTPException:
print("message not sent :(")
You never actually call the function starttls:
session.starttls -> session.starttls() # add parens to call
Less relevant but you also don't call quit session.quit -> session.quit()
Please, try yagmail. Disclaimer: I'm the maintainer, but I feel like it can help everyone out!
It really provides a lot of defaults: I'm quite sure you'll be able to send an email directly with:
import yagmail
yag = yagmail.SMTP(username, password)
yag.send(to_addrs, contents = msg)
You'll have to install yagmail first with either:
pip install yagmail # python 2
pip3 install yagmail # python 3
Once you will want to also embed html/images or add attachments, you'll really love the package!
It will also make it a lot safer by preventing you from having to have your password in the code.
'recipient' must be in list form for this to work.
Try changing
session.sendmail(sender, recipient, message)
to
session.sendmail(sender, [recepient], message)

How to Verify an Email Address in Python Using smtplib

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.

How can I send email using Gmail's SMTP without using smtplib?

This is my code:
import socket
import base64
s=socket.socket()
s.connect(('smtp.gmx.com',25))
message=s.recv(1024)
print message
s.send("EHLO gmx\r\n")
message=s.recv(1024)
print message
Username=raw_input("Inesrt Username: ")
Password=raw_input("Insert Password: ")
UP=("\x00"+Username+"\x00"+Password).encode("base64")
UP=UP.strip("\n")
print "AUTH PLAIN "+UP
s.send("AUTH PLAIN "+UP+"\r\n")
message=s.recv(10000000)
print message
s.send("MAIL FROM:"+Username+"\r\n")
message=s.recv(10000)
print message
To=raw_input("TO:")
s.send("RCPT TO:"+To+"\r\n")
message=s.recv(10000)
print message
s.send("DATA\r\n")
message=s.recv(100000)
print message
Subject=raw_input("Subject: ")
Text=raw_input("Message:")
s.send("Subject: "+Subject+"\r\n\r\n"+Text+"\r\n.\r\n")
message=s.recv(10000)
print message
s.send("QUIT\r\n")
message=s.recv(100000)
print message
s.close()
It works for regular email, but it does not work for Gmail or Yahoo. How can I send email using Gmail's SMTP using similar code?
Gmail SMTP server does not support plain SMTP protocol. You have to use TLS/SSL and connect to port 465. See this question for more pointers how to do that.

Categories