Unable to retrive G-mail with python3 - python

I'm unable to find ANY code that will function to retrieve Gmail.
import poplib
from email import parser
SERVER = "pop.gmail.com"
USER = "user#gmail.com"
PASSWORD = "password"
pop_conn = poplib.POP3_SSL(SERVER)
pop_conn.user(USER)
pop_conn.pass_(PASSWORD)
#Get messages from server:
messages = [pop_conn.retr(i) for i in range(1, len(pop_conn.list()[1]) + 1)]
# Concat message pieces:
messages = ["\n".join(mssg[1]) for mssg in messages]
#Parse message intom an email object:
messages = [parser.Parser().parsestr(mssg) for mssg in messages]
for message in messages:
print(message['subject'])
print(message['body'])
This produces only:
TypeError Traceback (most recent call last)
<ipython-input-8-e557fa99ae8d> in ()
12 messages = [pop_conn.retr(i) for i in range(1, len(pop_conn.list()[1]) + 1)]
13 # Concat message pieces:
---> 14 messages = ["\n".join(mssg[1]) for mssg in messages]
15 #Parse message intom an email object:
16 messages = [parser.Parser().parsestr(mssg) for mssg in messages]
<ipython-input-8-e557fa99ae8d> in (.0)
12 messages = [pop_conn.retr(i) for i in range(1, len(pop_conn.list()[1]) + 1)]
13 # Concat message pieces:
---> 14 messages = ["\n".join(mssg[1]) for mssg in messages]
15 #Parse message intom an email object:
16 messages = [parser.Parser().parsestr(mssg) for mssg in messages]
TypeError: sequence item 0: expected str instance, bytes found
I'VE SPENT DAYS trying to do a "simple" e-mail retrieve, and EVERY scrap of code I've found is totally non-functional.
Can anyone actually get Gmail, with subjects, etc?

This code is incomplete but may help you.
source: https://www.code-learner.com/python-use-pop3-to-read-email-example/
import poplib
import smtplib, ssl
# input email address, password and pop3 server domain or ip address
email = 'yourgmail#gmail.com'
password = 'password'
# connect to pop3 server:
server = poplib.POP3_SSL('pop.gmail.com')
# open debug switch to print debug information between client and pop3 server.
server.set_debuglevel(1)
# get pop3 server welcome message.
pop3_server_welcome_msg = server.getwelcome().decode('utf-8')
# print out the pop3 server welcome message.
print(server.getwelcome().decode('utf-8'))
# user account authentication
server.user(email)
server.pass_(password)
# stat() function return email count and occupied disk size
print('Messages: %s. Size: %s' % server.stat())
# list() function return all email list
resp, mails, octets = server.list()
print(mails)
# retrieve the newest email index number
index = len(mails)
# server.retr function can get the contents of the email with index variable value index number.
resp, lines, octets = server.retr(index)
# lines stores each line of the original text of the message
# so that you can get the original text of the entire message use the join function and lines variable.
msg_content = b'\r\n'.join(lines).decode('utf-8')
# now parse out the email object.
from email.parser import Parser
from email.header import decode_header
from email.utils import parseaddr
import poplib
# parse the email content to a message object.
msg = Parser().parsestr(msg_content)
# get email from, to, subject attribute value.
email_from = msg.get('From')
email_to = msg.get('To')
email_subject = msg.get('Subject')
print('From ' + email_from)
print('To ' + email_to)
print('Subject ' + email_subject)
# delete the email from pop3 server directly by email index.
# server.dele(index)
# close pop3 server connection.
server.quit()

Related

How to deal with error when mails are read

The script is first doing it job
find the message with specific subject
send a message to the sender
copy the message to folder 'answered'
delete the message
sleep for 1min and repeat
mail.select()
status, messages = mail.select("INBOX")
n = int(str(messages[0], 'utf-8'))
messages = int(messages[0])
for i in range(messages, messages-n,-1):
res, msg = mail.fetch(str(i), "(RFC822)")
for response in msg:
if isinstance(response, tuple):
# parse a bytes email into a message object
msg = email.message_from_bytes(response[1])
Sub, encoding = decode_header(msg.get("Subject"))[0] # Error is about this line
Sub=Sub.decode((encoding))
if Sub == pat:
fro, encoding = decode_header(msg.get("From"))[0]
if isinstance(fro, bytes):
fro = fro.decode(encoding)
# if s == 0:
# time.sleep(60)
# mai_load(1)
print("From:", fro)
send_mail(fro)
mail.copy(str(i), 'praca')
mail.store(str(i), '+FLAGS', '\\Deleted')
print("=" * 100)
time.sleep(60)
mai_load(0)
And here is the problem, messages are mark as read and when the scripts connects again I'm receiving an error:
line 99, in mai_load
Sub, encoding = decode_header(msg.get("Subject"))[0]
File "/usr/lib/python3.8/email/header.py", line 80, in decode_header
if not ecre.search(header):
TypeError: expected string or bytes-like object
Try my lib: https://github.com/ikvk/imap_tools
from imap_tools import MailBox, AND, MailMessageFlags
with MailBox('imap.mail.com').login('test#mail.com', 'pwd', 'INBOX') as mailbox:
# get list of email senders from INBOX folder
senders = [msg.from_ for msg in mailbox.fetch()]
# FLAG unseen messages in current folder (INBOX) as Flagged
mailbox.flag(mailbox.fetch(AND(seen=False)), [MailMessageFlags.FLAGGED], True)

How to tell program to sleep for 60 seconds after 50 actions have been completed (emails sent) in python

I have this code that sends out emails individually through gmail from a list of emails in an excel file. I just want to know how to make the bot pause for 60 seconds after it's sent 50 emails and then continue with the list after the 60 seconds is up. I'm just trying to be safe with gmails daily limits.
import smtplib
import openpyxl as xl
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
username = str(input('Your Username:' ))
password = str(input('Your Password:' ))
From = username
Subject = 'Free Beats and Samples For You :)'
wb = xl.load_workbook(r'C:\Users\19548\Documents\EMAILS.xlsx')
sheet1 = wb.get_sheet_by_name('EMAIL TEST - Sheet1')
names = []
emails = []
for cell in sheet1['A']:
emails.append(cell.value)
for cell in sheet1['B']:
names.append(cell.value)
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(username, password)
for i in range(len(emails)):
msg = MIMEMultipart()
msg['From'] = username
msg['To'] = emails[i]
msg['Subject'] = Subject
text = '''
{}
'''.format(names[i])
msg.attach(MIMEText(text, 'plain'))
message = msg.as_string()
server.sendmail(username, emails[i], message)
print('Mail sent to', emails[i])
server.quit()
print('All emails sent successfully!')
You can use time.sleep() to wait a given number of seconds, and you can keep track of the number of emails sent using a variable that gets incremented with each iteration of the loop. Since you're already working with both the emails themselves and their indices, you can simplify this counting by using Python's enumerate function, which gives you both the next value and its corresponding index:
for index, email in enumerate(emails, start=1):
msg = <...>
message = msg.as_string()
server.sendmail(username, email, message)
if index % 50 == 0:
time.sleep(60)
if(your_value%50==0):
time.sleep(60)

Checking new mails of Gmail account through python

I'm using this code to check for new mails with a 10 seconds delay.
import poplib
from email import parser
import time
def seeit():
pop_conn = poplib.POP3_SSL('pop.gmail.com')
pop_conn.user('xxx')
pop_conn.pass_('xx')
#Get messages from server:
messages = [pop_conn.retr(i) for i in range(1, len(pop_conn.list()[1]) + 1)]
# Concat message pieces:a
messages = ["\n".join(mssg[1]) for mssg in messages]
#Parse message intom an email object:
messages = [parser.Parser().parsestr(mssg) for mssg in messages]
for message in messages:
print message['subject']
pop_conn.quit()
starttime=time.time()
while True:
k=10.0
print "tick"
seeit()
time.sleep(k - ((time.time() - starttime) % k))
How can i retrieve the email body without headers?
Look at the method get_payload() method from the email package.
Try this after you get the messages from server:
import email
...
messages = [pop_conn.retr(i) for i in range(1, len(pop_conn.list()[1]) + 1)]
...
for i in messages:
mssg = email.message_from_string(i)
print(mssg.get_payload())

Python Poplib Error

This is the code
import poplib
from email import parser
pop_conn = poplib.POP3_SSL('pop.gmail.com')
pop_conn.user('user#gmail.com')
pop_conn.pass_('password')
messages = [pop_conn.retr(i) for i in range(1, len(pop_conn.list()[1]) + 1)]
messages = ["\n".join(mssg[1]) for mssg in messages]
messages = [parser.Parser().parsestr(mssg) for mssg in messages]
for message in messages:
print(message)
When it gets to the 8th line (messages = ["\n".join(mssg[1]) for mssg in messages])
It says this:
TypeError: sequence item 0: expected str instance, bytes found
Does anyone know what i'm doing wrong?
Convert the bytes objects into string using bytes.decode:
messages = ["\n".join(m.decode() for m in mssg[1]) for mssg in messages]

python emailing one line at a time

My email program is emailing each line of the message as a separate email, i would like to know how to send all of the message in one email, when the email is sent the program will return to the beginning.
import smtplib
from email.mime.text import MIMEText
a = 1
while a == 1:
print " "
To = raw_input("To: ")
subject = raw_input("subject: ")
input_list = []
print "message: "
while True:
input_str = raw_input(">")
if input_str == "." and input_list[-1] == "":
break
else:
input_list.append(input_str)
for line in input_list:
# Create a MIME text message and populate its values
msg = MIMEText(line)
msg['Subject'] = subject
msg['From'] = '123#example.com'
msg['To'] = To
server = smtplib.SMTP_SSL('server', 465)
server.ehlo()
server.set_debuglevel(1)
server.ehlo()
server.login('username', 'password')
# Send a properly formatted MIME message, rather than a raw string
server.sendmail('user#example.net', To, msg.as_string())
server.close()
(the part that takes multiple lines was made with the help Paul Griffiths, Multiline user input python)
for line in input_list:
# Create a MIME text message and populate its values
msg = MIMEText(line)
You are calling server.sendmail in this loop.
Build your entire msg first (in a loop), THEN add all of your headers and send your message.

Categories

Resources