read mails from custom label in gmail using python(google api) - python-3.x

I want to read mail from customed label USING PYTHON and google API.However i m getting error of change the label from inbox to customed label
label_id_one = 'AW'
label_id_two = 'UNREAD'
unread_msgs = GMAIL.users().messages().list(userId='me',labelIds=[label_id_one, label_id_two]).execute()
GETTING THIS ERROR:
File "C:\Users\AppData\Local\Programs\Python\Python36-32\lib\site-packages\googleapiclient\discovery.py", line 272, in _retrieve_discovery_doc
raise HttpError(resp, content, uri=actual_url)
googleapiclient.errors.HttpError: <HttpError 403 when requesting https://gmail.googleapis.com/$discovery/rest?version=v2 returned "The request cannot be identified with a project. Please pass a valid API key with the request.">

I have removed labelIDs and added q parameter as shown below. Here the "test" is the folder created by me in Gmail.
unread_msgs = GMAIL.users().messages().list(userId='me',q='in:test is:unread').execute()

Related

Apache Airflow did not recognize error in xml and report success

Hello Community I have a question for you, regarding a Python function. in Diser Function I read a large XML into a JSON format. In doing so I want to check if there is an tag within the XML at the first or last position, if so then raise error etc.
Unfortunately I have the problem that sometimes the function doesn't seem to recognize this tag and Apache Airflow then reports a success back.
For this I have then built a second function in advance, which checks the xml in advance via a Beautifulsoup.
But now I always get a failed reported.
Can you explain to me why the "old" checked a success reports, but soup cancels ?
Should I combine the two or is there a more elegant solution in general ?
def parse_large_xml(xml_file_name, json_file_name, extra_fields=None, clean_keys=True):
"""
Converts SAP xml response to json.
- processes the xml file iteratively (one tag at a time)
- capable to deal with large files
Args:
xml_file_name: input filename
json_file_name: output filename
extra_fields: extra fields to add to the json
clean_keys: flag, if set remove prefixes from the response keys
"""
######### Extra check #####
# This is the new extra check
with open(xml_file_name, 'r') as xMl_File:
data = xMl_File.read()
if "error" in set(tag.name for tag in BeautifulSoup(data, 'xml').find_all()):
logging.info(tag.name)
errorMsg= f"error in response file \"{xml_file_name} (XML contains error tag)"
logging.error(msg=errString, exc_info=True, stack_info=True);
raise RuntimeError(errString)
########################################################################################
# This is the old Check
if extra_fields is None:
extra_fields = {}
with open(json_file_name, 'w') as json_file:
for event, elem in progressbar.progressbar(ET.iterparse(xml_file_name, events=('start', 'end'))):
if 'content' in elem.tag and event == 'end':
elem_dict = xmltodict.parse(tostring(elem))
if clean_keys:
elem_dict = clean_response_keys(elem_dict)
response_dict = {'raw_json_response': json.dumps(elem_dict)}
response_dict = {**extra_fields, **response_dict}
response_dict['hash'] = hashlib.sha256(
response_dict['raw_json_response'].encode()).hexdigest()
response_dict['date'] = get_scheduled_date()
json.dump(response_dict, json_file)
json_file.write('\n')
elem.clear()
elif 'error' in elem.tag and event == 'end':
errString = f"error in response file \"{xml_file_name}\":\n{tostring(elem)}"
logging.error(msg=errString, exc_info=True, stack_info=True);
raise RuntimeError(errString)
I´m using Apache Airflow 1.10.15 and composer: 1.16.10 as well as Python 3.
Here is an example error xml as it is returned but not recognized
<error xmlns="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata">
<code>
DBSQL_CONNECTION_NO_METADATA
</code>
<message>
Runtime Error: 'DBSQL_CONNECTION_NO_METADATA'. The OData request processing has been abnormal terminated. If "Runtime Error" is not initial, launch transaction ST22 for details and analysis. Otherwise, launch transaction SM21 for system log analysis.
</message>
<timestamp>
20220210031242
</timestamp>
</error>

Sending Mail in Python - Error code - SMTPDataError: 451, b 4.3.0 Mail server temporarily rejected message

I am able to send mail without issue when I implement the same code very plain without using any functions. But when I try to send mail using a function I am getting mail as my senders account is disabled and it is blocking my mail and account.
Have to implement a code for sending mails after certain filters are met in a function so that it can be used to send mail whenever wanted.
My code snippet:
import smtplib
def setup_mail():
global smtpObj,sender,receivers,message
sender = 'sample#gmail.com'
receivers = ['sample1#gmail.com','sample2#gmail.com']
message = """From: From Person <from#fromdomain.com>
To: To Person <to#todomain.com>
Subject: 1 MIN candle 15 points alert
TIME: watch out next 2 minutes
"""
smtpObj = smtplib.SMTP_SSL('smtp.gmail.com', 465)
smtpObj.login("sample#gmail.com","samplepassword")
setup_mail()
def sending_mails(smtpObj):
smtpObj.sendmail(sender, receivers, message)
for i in range(3):
sending_mails(smtpObj);
print("Successfully sent email")
The error i got,
Traceback (most recent call last): File "C:/Users/Arun/PycharmProjects/Astro/venv/Scripts/ZERODHA_DEV/sendmail.py", line 22, in sending_mails(smtpObj); File "C:/Users/Arun/PycharmProjects/Astro/venv/Scripts/ZERODHA_DEV/sendmail.py", line 20, in sending_mails smtpObj.sendmail(sender, receivers, message) File "C:\Python\lib\smtplib.py", line 888, in sendmail raise SMTPDataError(code, resp) smtplib.SMTPDataError: (451, b'4.3.0 Mail server temporarily rejected message. s77sm14888153pfc.164 - gsmtp')
However it works with a simple code like,
import smtplib
global smtpObj,sender,receivers,message
sender = 'sample#gmail.com'
receivers = ['sample1#gmail.com','sample2#gmail.com']
message = """From: From Person <from#fromdomain.com>
To: To Person <to#todomain.com>
Subject: 1 MIN candle 15 points alert
TIME: watch out next 2 minutes
"""
smtpObj = smtplib.SMTP_SSL('smtp.gmail.com', 465)
smtpObj.login("sample#gmail.com","samplepassword")
for i in range(3):
smtpObj.sendmail(sender, receivers, message)
print("Successfully sent email")
The immediate problem is that your message is indented; a valid SMTP message contains two literal adjacent newlines to demarcate the headers from the body.
While you can assemble simple email messages from ASCII strings, this is not tenable for real-world modern email messages. You really want to use the email library (or a higher level third-party wrapper or replacement) to handle all the corner cases of email message encapsulation, especially if you are not an expert on email and MIME yourself.

Azure AD Python - Unexpected polling state invalid_client error

store_token = context.acquire_token_with_device_code(resource_uri, code, client_id)
File "/Users/jyao/Desktop/azureblobtest/lib/python3.7/site-packages/adal/authentication_context.py", line 273, in acquire_token_with_device_code
return self._acquire_token(token_func)
File "/Users/jyao/Desktop/azureblobtest/lib/python3.7/site-packages/adal/authentication_context.py", line 109, in _acquire_token
return token_func(self)
File "/Users/jyao/Desktop/azureblobtest/lib/python3.7/site-packages/adal/authentication_context.py", line 266, in token_func
token = token_request.get_token_with_device_code(user_code_info)
File "/Users/jyao/Desktop/azureblobtest/lib/python3.7/site-packages/adal/token_request.py", line 398, in get_token_with_device_code
token = client.get_token_with_polling(oauth_parameters, interval, expires_in)
File "/Users/jyao/Desktop/azureblobtest/lib/python3.7/site-packages/adal/oauth2_client.py", line 345, in get_token_with_polling
wire_response)
adal.adal_error.AdalError: Unexpected polling state invalid_client
How could I get rid of this error after input the device code and sign-in successfully.
steps:
From a python interactive prompt, run this code [1] (All modules are already loaded). Where:
authority_url = 'https://login.microsoftonline.com/my_tenant_id'
resource_uri = "https://storage.azure.com/"
context = adal.AuthenticationContext(authority_uri)
code = context.acquire_user_code(resource_uri, client_id)
print(code['message'])
store_token = context.acquire_token_with_device_code(resource_uri, code, client_id)
credentials = AADTokenCredentials(store_token, client_id)
2.Open the URL https://microsoft.com/devicelogin in a browser.
3.Enter the code E8B2DVT67
4.Confirm the application's name, it is correct.
5.Authenticate using the user's credentials.
6.Get a message in browser saying "You have signed in to the TEST-APP application on your device. You may now close this window."
7.Get the error shown in my previous message in the python interactive prompt.
I use a native app and update manifest and set "allowPublicClient": true permission.
Your code works fine.
If we set allowPublicClient:false, we will encounter this error.
After updating allowPublicClient to true, it will work. Note: There will be some delay for the configuration to take effect.

Is there any way by which I can name the attached pdf file in flask mail?

I am using flask-mail to send a mail that would include a pdf document as an attachment,
The problem is when I receive it in my email the document's name turns out to be "noname" (without any extension), Even though this document is downloadable and readable there are some exceptional cases (probably 1 out of 10) where the document cannot be opened(probably because the extension is not set).
def send_mail_flask_to_user(self, doc_name, document_id, email,approve):
app.config.update(self.mail_settings)
mail = Mail(app)
with app.app_context():
msg = Message(sender=app.config.get(
"MAIL_USERNAME"), recipients=[email])
msg.subject = '{} Coriolis Tech'.format(doc_name)
msg.body=""" Dear {},
your request for {} has be approved and generated,please find the attachment for the same""".format(email.split('.')[0],doc_name)
working_dir=os.getcwd()
link = "https://docs.google.com/document/d/{}/".format(document_id)
if (approve==True):
with open(working_dir+"/generated_docs/"+document_id+".pdf",'rb') as fh:
msg.attach(working_dir+"/"+document_id+".pdf","application/pdf",fh.read())
elif(approve==False):
msg.body=""" Your {} is rejected ,contact Division of Human Resource Coriolis Technologies to know more""".format(doc_name)
mail.send(msg)
This problem only persists on Ubuntu 14.04 ,where as it works fine on a Windows machine
The filename parameter has to be a string.extension(eg: "something.pdf") to name the attachment that would be received
eg: your 'abcdcdhhcbdhbcvh.pdf' file that you want to attach would be named as "something.pdf" in the attachment
Hence replace the msg.attach(working_dir+"/"+document_id+".pdf","application/pdf",fh.read()) line with msg.attach(filename="something.pdf",disposition="attachment",content_type="application/pdf",data=fh.read())

Netsuite CSV import(An unexpected error has occurred)

Below is the sample code, i am using in CSV Import process.
var createJob = nlapiCreateCSVImport();
createJob.setMapping("CUSTIMPORTcust_pay");
createJob.setPrimaryFile("Data_string");
createJob.setOption("jobName", "Test imports");
var JobId = nlapiSubmitCSVImport(createJob);
nlapiSubmitCSVImport function is returning JobId without any error, but in job status page[UI] it showing status is failed and in Message field it showing "An unexpected error has occurred", CSV Response field also empty. when i try this by running the above code with same data again, some time it is successfully imported and some time it got failed, with showing message "An unexpected error has occurred"
Please see setPrimaryFile(file).
Where file is either:
The internal ID, as shown in the file cabinet, of the CSV file containing data to be imported, referenced by nlapiLoadFile. For example:
.setPrimaryFile(nlapiLoadFile(73))
Raw string of the data to be imported.
You are passing in a raw string of "Data_string".

Resources