I want to retrive content from sent messages folder by the code below:
conn = imaplib.IMAP4_SSL('imap.exmail.qq.com',993)
conn.login(user,pwd)
conn.select("Sent Messages")
mails = conn.search(None, 'ALL')
for num in mails[1][0].split():
t, d = conn.fetch(num, 'RFC822')
if t == 'OK':
print 'Message %s\n' % (num)
msg = email.message_from_string(d[0][1])
subject = email.Header.decode_header(msg['subject'])[0][0]
if re.search(month, subject):
print subject
else:
print 'fetch error'
The num is between 1~36, when the num is 8. There comes an error:
Traceback (most recent call last):
File "monthlySummary.py", line 30, in
t, d = conn.fetch(num, 'RFC822')
File "/usr/lib/python2.7/imaplib.py", line 455, in fetch
typ, dat = self._simple_command(name, message_set, message_parts)
File "/usr/lib/python2.7/imaplib.py", line 1087, in _simple_command
return self._command_complete(name, self._command(name, *args))
File "/usr/lib/python2.7/imaplib.py", line 911, in _command_complete
raise self.abort('command: %s => %s' % (name, val))
imaplib.abort: command: FETCH => socket error: unterminated line
I try to relogin, but still come the same error. what does this socket error mean? how can i solve this problem?
Thanks.
From the imaplib source code (here), the relevant function is:
def _get_line(self):
line = self.readline()
if not line:
raise self.abort('socket error: EOF')
# Protocol mandates all lines terminated by CRLF
if not line.endswith(b'\r\n'):
raise self.abort('socket error: unterminated line')
line = line[:-2]
if __debug__:
if self.debug >= 4:
self._mesg('< %r' % line)
else:
self._log('< %r' % line)
return line
The comment in the function says that all lines must be terminated by CRLF, so it is obviously hitting a line that is not and so it aborts.
You need to make sure each line ends with '\r\n', so to do that you could simply add this string to each line if it is not already there, before processing it. This will make sure that this error upon which the program is aborted is not raised.
Related
when i try to run this python :
import subprocess, smtplib
def send_mail(email,password,message):
server = smtplib.SMTP("smtp.gmail.com", 587)
server.starttls()
server.login(email,password)
server.sendmail(email, email, message)
server.quit()
a = subprocess.check_output(['netsh','wlan','show','profiles']).decode('utf-8').split('\n')
a = [i.split(":")[1][1:-1] for i in a if "All User Profile" in i]
for i in a:
results = subprocess.check_output(['netsh','wlan','show','profile',i,'key=clear']).decode('utf-8').split('\n')
results = [b.split(":")[1][1:-1] for b in results if "Key Content" in b]
try:
print ("{:<30}| {:<}".format(i, results[0]))
except IndexError:
print ("{:<30}| {:<}".format(i,""))
send_mail("example#gmail.com","Example123",results)
i get this error
Traceback (most recent call last):
File "wifi.py", line 18, in <module>
send_mail("Example#gmail.com","Example123",results)
File "wifi.py", line 6, in send_mail
server.sendmail(email, email, message)
File "C:\Users\TARUN\AppData\Local\Programs\Python\Python38-32\lib\smtplib.py", line 886, in sendmail
(code, resp) = self.data(msg)
File "C:\Users\TARUN\AppData\Local\Programs\Python\Python38-32\lib\smtplib.py", line 568, in data
q = _quote_periods(msg)
File "C:\Users\TARUN\AppData\Local\Programs\Python\Python38-32\lib\smtplib.py", line 176, in _quote_periods
return re.sub(br'(?m)^\.', b'..', bindata)
File "C:\Users\TARUN\AppData\Local\Programs\Python\Python38-32\lib\re.py", line 210, in sub
return _compile(pattern, flags).sub(repl, string, count)
TypeError: expected string or bytes-like object
i understand that i need to put 'str' somewhere but i don't know which part(i'm kinda new to python)
you have results as list just convert it into string This will send both username and pwd
import subprocess, smtplib
def send_mail(email,password,message):
server = smtplib.SMTP("smtp.gmail.com", 587)
server.starttls()
server.login(email,password)
server.sendmail(email, email, message)
server.quit()
a = subprocess.check_output(['netsh','wlan','show','profiles']).decode('utf-8').split('\n')
a = [i.split(":")[1][1:-1] for i in a if "All User Profile" in i]
to_send = []
for i in a:
results = subprocess.check_output(['netsh','wlan','show','profile',i,'key=clear']).decode('utf-8').split('\n')
results = [b.split(":")[1][1:-1] for b in results if "Key Content" in b]
# in order to send everything store it in another list and then join them with new line.
to_send.append(i+":"+"".join(results))
try:
print ("{:<30}| {:<}".format(i, results[0]))
except IndexError:
print ("{:<30}| {:<}".format(i,""))
# convert list to string
send_mail("example#gmail.com","Example123","\n".join(to_send))
I am trying to run the first example:Get Campaigns,through the python sdk(ads api,not adwords).
I got an error that did not describe how to solve the problem: google.api_core.exceptions.DeadlineExceeded: 504 Deadline Exceeded
"""This example illustrates how to get all campaigns.
To add campaigns, run add_campaigns.py.
"""
from __future__ import absolute_import
import argparse
import six
import sys
import google.ads.google_ads.client
_DEFAULT_PAGE_SIZE = 10
def main(client, customer_id, page_size):
ga_service = client.get_service('GoogleAdsService', version='v1')
query = ('SELECT campaign.id, campaign.name FROM campaign '
'ORDER BY campaign.id')
results = ga_service.search(customer_id, query=query, page_size=page_size)
try:
for row in results:
print('Campaign with ID %d and name "%s" was found.'
% (row.campaign.id.value, row.campaign.name.value))
except google.ads.google_ads.errors.GoogleAdsException as ex:
print('Request with ID "%s" failed with status "%s" and includes the '
'following errors:' % (ex.request_id, ex.error.code().name))
for error in ex.failure.errors:
print('\tError with message "%s".' % error.message)
if error.location:
for field_path_element in error.location.field_path_elements:
print('\t\tOn field: %s' % field_path_element.field_name)
sys.exit(1)
if __name__ == '__main__':
google_ads_client = (google.ads.google_ads.client.GoogleAdsClient
.load_from_storage("google-ads.yaml"))
main(google_ads_client, "customer_id", _DEFAULT_PAGE_SIZE)
and got the error:
Traceback (most recent call last):
File "c:/PythonProjects/google_ads_api_test/google-ads-python-master/google-ads-python-master/examples/basic_operations/get_campaigns.py", line 68, in <module>
main(google_ads_client, "customer_id", _DEFAULT_PAGE_SIZE)
File "c:/PythonProjects/google_ads_api_test/google-ads-python-master/google-ads-python-master/examples/basic_operations/get_campaigns.py", line 40, in main
for row in results:
File "C:\Anaconda3\lib\site-packages\google\api_core\page_iterator.py", line 204, in _items_iter
for page in self._page_iter(increment=False):
File "C:\Anaconda3\lib\site-packages\google\api_core\page_iterator.py", line 235, in _page_iter
page = self._next_page()
File "C:\Anaconda3\lib\site-packages\google\api_core\page_iterator.py", line 526, in _next_page
response = self._method(self._request)
File "C:\Anaconda3\lib\site-packages\google\api_core\gapic_v1\method.py", line 143, in __call__
return wrapped_func(*args, **kwargs)
File "C:\Anaconda3\lib\site-packages\google\api_core\retry.py", line 270, in retry_wrapped_func
on_error=on_error,
File "C:\Anaconda3\lib\site-packages\google\api_core\retry.py", line 179, in retry_target
return target()
File "C:\Anaconda3\lib\site-packages\google\api_core\timeout.py", line 214, in func_with_timeout
return func(*args, **kwargs)
File "C:\Anaconda3\lib\site-packages\google\api_core\grpc_helpers.py", line 59, in error_remapped_callable
six.raise_from(exceptions.from_grpc_error(exc), exc)
File "<string>", line 3, in raise_from
google.api_core.exceptions.DeadlineExceeded: 504 Deadline Exceeded
Is something wrong with the call?
I believe you simply need to increase your timeout value in your configuration.
I have pretty straightforward Python code which queries data from memcached:
import memcache
client = memcache.Client([('127.0.0.1', 11211)])
res = client.get("data_e")
data_e key exists, is not null and I am able to get results via telnet connection to memcached.
However when Python script is executed I keep receiving following error:
Traceback (most recent call last):
File "./position_expiration.py", line 5, in <module>
res = client.get("data_e")
File "/usr/lib/python2.7/site-packages/memcache.py", line 1129, in get
return self._get('get', key)
File "/usr/lib/python2.7/site-packages/memcache.py", line 1113, in _get
return _unsafe_get()
File "/usr/lib/python2.7/site-packages/memcache.py", line 1101, in _unsafe_get
value = self._recv_value(server, flags, rlen)
File "/usr/lib/python2.7/site-packages/memcache.py", line 1294, in _recv_value
raise ValueError('Unknown flags on get: %x' % flags)
ValueError: Unknown flags on get: 20
Data in memcached is stored by third party service, so I can't change a way how it is written there. What can I do from client side with Python to read it?
I have solved this problem.
This is the solution in Chinese: https://www.cnblogs.com/LanTianYou/p/9204431.html
The solution is to modify the final else-block content in the method "_recv_value" in the python file "memcache.py".
The _recv_value method should be like this:
def _recv_value(self, server, flags, rlen):
rlen += 2 # include \r\n
buf = server.recv(rlen)
if len(buf) != rlen:
raise _Error("received %d bytes when expecting %d"
% (len(buf), rlen))
if len(buf) == rlen:
buf = buf[:-2] # strip \r\n
if flags & Client._FLAG_COMPRESSED:
buf = self.decompressor(buf)
flags &= ~Client._FLAG_COMPRESSED
if flags == 0:
# Bare bytes
val = buf
elif flags & Client._FLAG_TEXT:
val = buf.decode('utf-8')
elif flags & Client._FLAG_INTEGER:
val = int(buf)
elif flags & Client._FLAG_LONG:
if six.PY3:
val = int(buf)
else:
val = long(buf) # noqa: F821
elif flags & Client._FLAG_PICKLE:
try:
file = BytesIO(buf)
unpickler = self.unpickler(file)
if self.persistent_load:
unpickler.persistent_load = self.persistent_load
val = unpickler.load()
except Exception as e:
self.debuglog('Pickle error: %s\n' % e)
return None
else:
self.debuglog("unknown flags on get: %x\n" % flags)
# 注释掉这行
# raise ValueError('Unknown flags on get: %x' % flags)
# 设定返回值
val = buf
return val
I have the following code which returns the public IP's
def gather_public_ip():
ACCESS_KEY = config.get('aws','access_key')
SECRET_KEY = config.get('aws','secret_key')
regions = regions = ['us-west-2','eu-central-1','ap-southeast-1']
# regions = config.get('aws','region').split(',')
all_EIP = []
for region in regions:
client = boto3.client('ec2',aws_access_key_id=ACCESS_KEY,aws_secret_access_key=SECRET_KEY,region_name=region,)
addresses_dict = client.describe_addresses()
for eip_dict in addresses_dict['Addresses']:
if 'PrivateIpAddress' in eip_dict:
print eip_dict['PublicIp']
# return str(eip_dict['PublicIp'])
all_EIP.append(eip_dict['PublicIp'])
print all_EIP
# print str(all_EIP)
return str(all_EIP)
This is called and returned as :
net_range = gather_public_ip()
for ip in net_range:
r = s.run(ip)
run looks like :
def run(self, targets="" ,options="-Pn"):
#start a new nmap scan on localhost with some specific options
syslog.syslog("Scan started")
parsed = None
nmproc = NmapProcess(targets,options)
rc = nmproc.run()
if rc != 0:
syslog.syslog("nmap scan failed: {0}".format(nmproc.stderr))
try:
parsed = NmapParser.parse(nmproc.stdout)
self.report = parsed
except NmapParserException as e:
syslog.syslog("Exception raised while parsing scan: {0}".format(e.msg))
syslog.syslog("Scan complete")
syslog.syslog("Scan duration: "+ str(parsed.elapsed))
self.report = parsed
return parsed
after printing the list , this throws me :
Traceback (most recent call last):
File "portwatch.py", line 300, in <module>
r = s.run(ip)
File "portwatch.py", line 239, in run
rc = nmproc.run()
File "/usr/local/lib/python2.7/dist-packages/libnmap/process.py", line 257, in run
else shlex.split(self.__nmap_command_line)
File "/usr/lib/python2.7/shlex.py", line 279, in split
return list(lex)
File "/usr/lib/python2.7/shlex.py", line 269, in next
token = self.get_token()
File "/usr/lib/python2.7/shlex.py", line 96, in get_token
raw = self.read_token()
File "/usr/lib/python2.7/shlex.py", line 172, in read_token
raise ValueError, "No closing quotation"
ValueError: No closing quotation
Make sure your ip is not "" or shlex will fail, cf Which exception to raise if a given string does not match some format?
I'm following a tutorial to be able to read email metadata. I'm getting this following error: imaplib.error: UID command error: BAD [b'Could not parse command']
the full trace is:
Traceback (most recent call last):
File "email_metadata.py", line 28, in <module>
result, data = conn.uid('fetch', ','.join(str(u) for u in uids), '(BODY[HEADER.FIELDS (MESSAGE-ID FROM TO CC DATE)])')
File "/usr/lib/python3.4/imaplib.py", line 817, in uid
typ, dat = self._simple_command(name, command, *args)
File "/usr/lib/python3.4/imaplib.py", line 1134, in _simple_command
return self._command_complete(name, self._command(name, *args))
File "/usr/lib/python3.4/imaplib.py", line 965, in _command_complete
raise self.error('%s command error: %s %s' % (name, typ, data))
imaplib.error: UID command error: BAD [b'Could not parse command']
This is my code:
The full code is in my gist
import imaplib, email, getpass
from email.utils import getaddresses
imaplib._MAXLINE = 40000
#connection
conn = imaplib.IMAP4_SSL('imap.gmail.com')
(retcode, capabilities) = conn.login('my_true_email_addr#gmail.com', getpass.getpass())
print(conn.list())
#print con.list()
conn.select("INBOX", readonly=True)
result, data = conn.uid('search', None, '(SINCE "01-Jan-2014" BEFORE "01-Jan-2015")')
uids = data[0].split()
print(uids)#in bytes
# Download headers
result, data = conn.uid('fetch', ','.join(str(u) for u in uids), '(BODY[HEADER.FIELDS (MESSAGE-ID FROM TO CC DATE)])')
# Where data will be stored
raw_file = open('raw-email-rec.tsv', 'w')
# Header for TSV file
raw_file.write("Message-ID\tDate\tFrom\tTo\tCc\n")
Previously this line .join(str(u) for u in uids) was written like this .join(uids) like in the tutorial but I had an error saying TypeError: sequence item 0: expected str instance, bytes found So I converted it in string.
gist
I think you converted the wrong thing. It looks like the library is working with bytes rather than str. Try:
b','.join(uids)
I converted a list of bytes into a string
result, data = conn.uid('search', None, '(SINCE "01-Jan-2014" BEFORE "05-Jan-2015")')
print(data)
#[b'2627 2628 2630 2639 2643 2649 2650 2651 2652']
uids = data[0].split()
#[b'2627', b'2628', b'2630', b'2639', b'2643', b'2649', b'2650', b'2651', b'2652']
uids = [i.decode('utf-8') for i in uids]
#['2627', '2628', '2630', '2639', '2643', '2649', '2650', '2651', '2652']
# Download headers
result, data = conn.uid('fetch', ','.join(uids), '(BODY[HEADER.FIELDS (MESSAGE-ID FROM TO CC DATE)])')
print(','.join(uids))
#'2627,2628,2630,2639,2643,2649,2650,2651,2652'