How to get messages via imap_tools excluding some UID? - python

Test code:
fetch_criteria = AND(seen=False), AND(NOT(uid=['61','88']))
for message in mailbox.fetch(fetch_criteria, mark_seen=False, charset='utf8', limit=10):
print(message.uid)
Server response:
SEARCH command error: BAD [b'Could not parse command']
Please help me correctly create the conditions to exclude emails with UID 66 and 88

from imap_tools import AND, NOT
mailbox.fetch(AND(NOT(uid=['39', '40'])))
mailbox.fetch(NOT(AND(uid=['39', '40'])))
Both works for me at [yandex, google, outlook, zimbra].
May be your server can not do this.
Error example at mail.ru: imap_tools.errors.MailboxSearchError: Response status "OK" expected, but "NO" received. Data: [b'[CANNOT] Unsupported search criterion: (UID 5,6)']
Lib author.

Related

How to Send a URL Link within the Text Body with the Twilio API using Python

I am trying to send a text message that contains both text and a hypeprlink but am encountering the following message from the Twilio API:
"Error - 12300 Invalid Content-Type: Attempt to retrieve MediaUrl returned an unsupported Content-Type."
Here is the code I am attempting to leverage:
import os
from twilio.rest import Client
# Find your Account SID and Auth Token at twilio.com/console
# and set the environment variables. See http://twil.io/secure
account_sid = os.environ['TWILIO_ACCOUNT_SID']
auth_token = os.environ['TWILIO_AUTH_TOKEN']
client = Client(account_sid, auth_token)
message = client.messages \
.create(
body='Article: https://4r7s.short.gy/GPaoh7',
from_='123-345-5667',
to='123-345-5668',
)
When I send a message without a hyperlink it works fine (e.g. body = 'Here is the article for you to read') but when it contains a link I receive the aforementioned error. I've also tried using a shortened url of the above but that causes the same issue.
I was just able to send messages containing that exact link using my own Twilio account.
There might be an issue in that you are using phone numbers in local format, when they should be provided in e.164 format.
It's possible that your message is being blocked. Certain carriers don't like when you use link shorteners to obscure a link.
The error you are getting definitely seems weird, since you are not sending media. If you continue to have issues with this, I would contact Twilio support.

Search creteria for query in mailbox imap_tools library

im trying to query in mailbox with python3 imap_tools, cant uderstand how to extract emails with sender email and unseen flag. Trying like this
for msg in [msg for msg in mailbox.fetch(Q(from_=sender, seen=False))]
And always get same error
imap_tools.utils.UnexpectedCommandStatusError: Response status for command "box.search" == "NO", "OK" expected, data: [b'[CANNOT] Unsupported search criterion: FROM "ZOYA1608#YANDEX.RU" UNSEEN']
Can somebody explain where my mistake,
full code below
with open("..\\conf\\conf.yaml", mode="r") as stream:
for conf in yaml.safe_load_all(stream):
with MailBox(conf['host']).login(conf['mailbox'], conf['password']) as mailbox:
for sender in conf['senders']['from']:
for msg in [msg for msg in mailbox.fetch(Q(from_=sender, seen=False))]:
for att in msg.attachments:
with open(get_path(file_name=att.filename, store_paths=conf['store_paths']), 'w+b') as f:
f.write(att.payload)
yandex server support From queries
A(from_="ZOYA1608#YANDEX.RU", seen=False) works, I checked
Do not forget update lib sometimes
Most likely: your server doesn't fully support the IMAP search specification.
Regards, imap_tools author.

Python imaplib uid fetch command error

I tried to fetch a message content in the following way
result, data = m.uid('fetch', num, "( FLAGS BODY.PEEK[HEADER.FIELDS (SUBJECT FROM DATE)] BODYSTRUCTURE)")
It worked well when I was connecting to a private mail server "mail.example.com"
But it returns exception when I used "imap.gmail.com"
error: UID command error: BAD ['Could not parse command']
I think gmail doesnot support detailed search like HEADER.FIELDS....
So I tried the following option for gmail server and it worked really well
result, data = m.uid('fetch', num, "(FLAGS BODY.PEEK[HEADER] BODYSTRUCTURE)")

rpython and imaplib sending a search query to imap

I'm trying to import an email with a particular search string from the server. I'm using the following code.
library(rPython)
python.exec("import imaplib
import email")
python.exec('
m=imaplib.IMAP4("imap.myserver.com","143")
m.login(r"myid","mypass")
m.select()')
python.exec('r,data=m.search(None,\'HEADER From "*cds*"\')')
a = python.get("data")
but it seems to not like the escaped apostrophes. I get the message
Error in python.exec("r,data=m.search(None,'HEADER From \"*cds*\"')") :
SEARCH command error: BAD ['unable to handle request: Invalid search parameters: "HEADER FROM \\"*CDS*\\""']
Can anyone help me figure out how to get this right? Thanks

why doesn't this imaplib request work all the time?

I'm using imaplib and attempting to parse messages from a gmail acct. My code has worked for months, and now all of the sudden it's failing miserably. I have no idea what to attribute this to.
The following works around 1/3 of the time. By 'works', I mean succeeds in printing something other than 'no new messages' when I receive an email. Would anyone have any suggestions of more robust ways to attempt this? Or maybe suggestions of now to configure gmail accounts to get this to work more reliably?
I'm also generally interested if the way I've coded this seems like good practice.
Thanks for any and all help...
def check_email(interval):
while True:
server.select('INBOX')
status, ids = server.search(None, 'UnSeen')
if not ids or ids[0] is '':
print 'no new messages'
else:
print 'found a message; attempting to parse...'
latest_id = ids[0]
status, msg_data = server.fetch(latest_id, '(UID BODY[TEXT])')
raw_data = msg_data[0][1]
char_array = list(raw_data)
print 'message result: ', char_array
time.sleep(interval)
EDIT1: I am now getting the following error:
"imaplib.error: FETCH command error: BAD ['Could not parse command']"
Does anyone know what I can attribute this to? It's apparently a result of the line
status, msg_data = server.fetch(latest_id, '(UID BODY[TEXT])')
EDIT2: I found out that I can log into the gmail account, click on the 'more' tab, then click on 'mark all as read' and all of the sudden the code works as expected. Is there a way to mark all messages as read remotely with imaplib??

Categories