Key Error when extracting the body from email - python

For some messages, I believe that there is no 'parts' component. I thought the code below covers most messages, but it is still throwing a keyerror: 'data' when trying to get some messages. I have looked through the json result for those messages and they all contain 'data', not sure what's going on. Traceback shows that the keyerror is coming from messages that do contain 'parts'
Traceback
Traceback (most recent call last):
File "gmail.py", line 168, in <module>
final_message_list.append(GetMessage(gmail_service, 'me', message_id))
File "gmail.py", line 150, in GetMessage
message_raw = message['payload']['parts'][0]['body']['data']
(within GetMessage)
# Pull Raw Message Body from Response, some emails may not contain 'parts'
if 'parts' in message['payload']:
message_raw = message['payload']['parts'][0]['body']['data']
else:
message_raw = message['payload']['body']['data']

After some investigation, this is the best I've been able to do for now, if anyone has a better solution please post.
It looks like the message in question that caused the failure has an attachment, and perhaps the attachment is what messes up the structure of the message a bit. I've been able to see that the mimeType within 'Parts' is different (multipart/alternative) for attachment messages than it is for non-attachment messages (text/plain). Thus, I've been able to cover this case by just putting an 'if' statement before I try to parse out the message body, as shown below.
if 'parts' in message['payload']:
if message['payload']['parts'][0]['mimeType'] == 'multipart/alternative':
message_raw = message['payload']['parts'][0]['parts'][0]['body']['data']
else:
message_raw = message['payload']['parts'][0]['body']['data']
else:
message_raw = message['payload']['body']['data']

Related

getting error on updating assignee and comment field in JIRA using python

I am using python to automate JIRA process, while doing I am unable to update Assignee and Comment fields.
While updating Assignee field, not getting any error, but the value is not updated properly, I am trying to assign from one user to other user, but it is getting updated as Unassigned
For comment field, getting an error.
Below is my code:
from atlassian import Jira
jira_instance = Jira(
url = "https://****.atlassian.net/",
username = "****#gmail.com",
password = "*******",
)
data = jira_instance.jql("project = PROJECTNAME AND status = 'IN PROGRESS' ORDER BY created ASC", fields=['description','assignee','reporter','comment'])
for i in range(len(data["issues"])):
test_data = data["issues"][i]
jira_instance.issue_update(test_data['key'], fields={'assignee':{'emailAddress': '#####gmail.com' }})
jira_instance.issue_update(test_data['key'], fields={'comment':{'comments': [{'body':'This is the comment'}]}})
Also tried using displayName instead of using emailAddress, but still same thing happens.
For comment field, got the below error:
Traceback (most recent call last):
File "c:/Users/path/jiratest.py", line 13, in <module>
jira_instance.issue_update(test_data['key'], fields={'comment':{'comments': [{'body':'This is the comment'}]}})
File "C:\Users\path\AppData\Local\Programs\Python\Python37\lib\site-packages\atlassian\jira.py", line 891, in issue_update
return self.put(url, data={"fields": fields})
File "C:\Users\path\AppData\Local\Programs\Python\Python37\lib\site-packages\atlassian\rest_client.py", line 341, in put
absolute=absolute,
File "C:\Users\path\AppData\Local\Programs\Python\Python37\lib\site-packages\atlassian\rest_client.py", line 236, in request
self.raise_for_status(response)
File "C:\Users\path\AppData\Local\Programs\Python\Python37\lib\site-packages\atlassian\jira.py", line 3705, in raise_for_status
raise HTTPError(error_msg, response=response)
requests.exceptions.HTTPError
Please anyone help me out on this
You haven't said if you're using Jira Cloud or Server.
For Jira Cloud, you must set the assignee for an issue using that person's account ID, not their username or email address, so the request would look something like:
jira_instance.issue.update(assignee={'accountId': '5b10ac8d82e05b22cc7d4ef5'})
For adding a comment field, try something like this:
jira_instance.issue_add_comment(test_data['key'], 'This is the comment')
For updating the assignee, try this:
jira_instance.update_issue_field(test_data['key'], fields={"assignee": "####"})

Nonetype error in Sending an email to a teacher in python with SMTP

I used the code below to try to send an email to my teacher with my email and password:
import cs50
import smtplib
from email.message import EmailMessage
def main():
message = EmailMessage()
message.set_content("This email verifies run-check of ASSIGNMENT")
message['Subject'] = 'Assignment from ME'
message['From:'] = 'MY EMAIL'
message['To:'] = 'TEACHER'S EMAIL'
with smtplib.SMTP_SSL('smtp.gmail.com') as smtp:
smtp.login("MY EMAIL", "MY PASSWORD")
smtp.send_message(message)
sys.exit(0)
if(__name__ == "__main__"):
main()
However, I got an error message saying "TypeError: sequence item 0: expected str instance, NoneType found". Any idea what went wrong? It just took me 30 minutes of trying to get the login to work with Less Secure Apps...
Edit: No, the problem is not the third apostrophe in 'TEACHER'S EMAIL'. in the actual teacher's email there is not apostrophe yet I still get the TypeError problem.
Edit 2: Whole error code here:
Traceback (most recent call last):
File "/home/ubuntu/some folder idk/SMF29.py", line 48, in <module>
main()
File "/home/ubuntu/some folder idk/SMF29.py", line 42, in main
smtp.send_message(message)
File "/usr/local/lib/python3.9/smtplib.py", line 940, in send_message
from_addr = email.utils.getaddresses([from_addr])[0][1]
File "/usr/local/lib/python3.9/email/utils.py", line 112, in getaddresses
all = COMMASPACE.join(fieldvalues)
TypeError: sequence item 0: expected str instance, NoneType found
Edit 3: seeing that some people surrounded their emails with <>, I tried that, and got a different error:
smtplib.SMTPAuthenticationError: (535, b'5.7.8 Username and Password not accepted. Learn more at\n5.7.8 https://support.google.com/mail/?p=BadCredentials l11sm1375218qkk.101 - gsmtp')
Which is confusing, because not only have I taken all the google steps including the enable less secure apps and verify device things, but I am only logged into that one account. Any idea what the problem could be?
Edit 4: turns out that was a stupid idea and after getting rid of the <>s around the emails and the colons in front of From and To it worked. I had previously accidentally forgotten to remove one pair of <> around my email after removing the colons.
As can be seen from the error traceback, specifically this line:
from_addr = email.utils.getaddresses([from_addr])[0][1]
You are missing the from_addr. The key for the From address is From, not From: (with a colon). Change the following line
message['From:'] = 'MY EMAIL'
to
message['From'] = 'MY EMAIL'
While you are at it, do the same for the To address as well.
See the docs for an example.

Continue On Error Smartsheet SDK on python

I'm Trying to list the users of my domain smartsheet to backup their data one by one.
For that i need to list them then for every id i retrieve user Home with ss.Home.list_all_content()
the first one is ok, but the second give me this error when i try to retrieve his home or just make a ss.Users.get_User(his id) see below error:
Traceback (most recent call last):
File "<pyshell#84>", line 1, in <module>
ss.Users.list_users(include_all=True)
File "D:\Users\maxime.champain\AppData\Local\Programs\Python\Python35-32\lib\site-packages\smartsheet\users.py", line 277, in list_users
response = self._base.request(prepped_request, expected, _op)
File "D:\Users\maxime.champain\AppData\Local\Programs\Python\Python35-32\lib\site-packages\smartsheet\smartsheet.py", line 218, in request
raise the_ex(native, str(native.result.code) + ': ' + native.result.message)
smartsheet.exceptions.ApiError: {"result": {"shouldRetry": false, "refId": null, "code": 5349, "recommendation": "Do not retry without fixing the problem. ", "statusCode": 400, "message": "You must agree to the Smartsheet User Agreement before using Smartsheet. These terms can be viewed the next time you log in to https://app.smartsheet.com from a desktop browser.", "name": "ApiError"}, "requestResponse": null}
Question
How can I simply bypass this error to continue the program.
The exception of this error is handled by the smartsheet api sdk but i don't know how to call it.
regards,
If you want to catch this exception and continue, you'll need to use the try and except keywords.
There are many tutorials on the web, here's one: https://docs.python.org/3/tutorial/errors.html#handling-exceptions

Difficulties with sending mail from GAE

I'm trying to send an email from within Google App Engine.
Whenever I try to send, I get a "Missing subject error".
When I run the code on the development server, it seems to work fine - the console output looks right and I'm taken to the page that I was expecting. But when I upload it and run it, I get:
Traceback (most recent call last):
File "/base/python_runtime/python_lib/versions/1/google/appengine/ext/webapp/__init__.py", line 636, in __call__
handler.post(*groups)
File "/base/data/home/apps/spam-tool/1.349401522260793315/spam-tool.py", line 34, in post
body=cgi.escape(self.request.get('content')))
File "/base/python_runtime/python_lib/versions/1/google/appengine/api/mail.py", line 297, in send_mail
message.send(make_sync_call)
File "/base/python_runtime/python_lib/versions/1/google/appengine/api/mail.py", line 799, in send
raise ERROR_MAP[e.application_error](e.error_detail)
BadRequestError: Missing subject
But there's definitely a subject.
The code I'm using is:
> message = mail.EmailMessage(sender="admin_address#gmail.com>",
subject="test")
message.subject=self.request.get('content')
message.to = addr_to_send_to
message.body = self.request.get('content')
message.send()
(Yes, the subject is set twice... I've tried only setting it in one place or the other, and neither worked.)
Thanks in advance.
Try this:
def email_member(request):
to_addr = request.POST.get('email_to')
if not mail.is_email_valid(to_addr):
# Return an error message...
pass
else:
# note we can also send html email, e.g. html='<html><head></head><body>Hello world</body><html>'
mail.send_mail(
sender='admin#yourdomain.com',
to=to_addr,
subject=request.POST.get('email_title'),
body=request.POST.get('email_body'))
I suggest you also send your email within the taskqueue, so you could setup something like this, you could pass over a unique parameter so that you are less likely to be hacked.
def mail_member_information(email_to, email_title, email_body):
taskqueue.add(
url = 'email_message',
params =
{
'email_to': email_to,
'email_title': email_title,
'email_body': email_body,
'valid_guid': 'ae9e34ca-a2c5-476e-b8be-72d807e3dc6b'
}
)
If you just want to send to the administrators then use this:
mail.send_mail_to_admins(sender='admin#yourdomain.com',
subject=request.POST.get('email_title'),
body=request.POST.get('email_body'),
html=request.POST.get('email_body'))
I don't know if it is what is throwing you off... but sender should be like this:
sender = '<admin_address#gmail.com>',
you are missing the '<' for the sender. Sometimes it throws an error downstream of where the actual error is.
Also, make sure the admin_address#gmail.com is a Google Account that has been added as a developer for that app.
I think you can send like this, make sure that sender is a admin of the app
from google.appengine.api import mail
mail.send_mail(sender="something#gmail.com",
to=email_valid.email,
subject="Please validate your email",
body=body_text,
html=htmlbody_text)

ValidationError while running Google adwords client library examples

I get the following error when I try to run sample example of Google adwords
[root#some v200909]# python get_related_keywords.py Traceback (most recent call last): File "get_related_keywords.py", line 53, in
page = targeting_idea_service.Get(selector)[0] File "../../aw_api/TargetingIdeaService.py", line 105, in Get
'TargetingIdea', self.__loc, request) File "../../aw_api/WebService.py", line 350, in CallMethod
raise ValidationError(error['data']) aw_api.Errors.ValidationError: Invalid headers for 'https://adwords-sandbox.google.com', see http://code.google.com/apis/adwords/docs/developer/adwords_api_sandbox.html#requestheaders. [root#some v200909]#
This sounds like an issue with the headers you're providing. The headers must be especially formatted for the sandbox, so make sure that:
a) You're formatting the headers as specified in http://code.google.com/apis/adwords/docs/developer/adwords_api_sandbox.html#requestheaders , as Goose Bumper mentioned. This applies to both v2009 and v13, as you still need to format the developer token and client email according to the instructions (the application token is now obsolete).
b) You're choosing the right endpoint, namely adwords-sandbox.google.com for v2009 and sandbox.google.com for v13
If this still doesn't work for you, the SOAP logs for your request might be useful.

Categories