I have the following script, which is trying to get attachments from Outlook.
outlook = win32com.client.Dispatch("Outlook.Application")
inbox = outlook.GetDefaultFolder(0)
messages = inbox.Items
message = messages.GetLast() #open last message
attachments = message.Attachments #assign attachments to attachment variable
attachment = attachments.Item(1)
attachment.SaveASFile(os.path.join('c:', 'temp'))
When I run it however I am getting the following:
Traceback (most recent call last):
File "C:/Users/e003048/QA/trunk/automation/selenium/src/global_functions/util_get_email_attachments.py", line 11, in <module>
inbox = outlook.GetDefaultFolder(0)
File "C:\Python27\Lib\site-packages\win32com\client\dynamic.py", line 522, in __getattr__
raise AttributeError("%s.%s" % (self._username_, attr))
AttributeError: Outlook.Application.GetDefaultFolder
I am unsure where I would put the username to get this to work.
I tried the suggestion in the answer below and am getting the following error:
Traceback (most recent call last):
File "C:/Users/e003048/QA/trunk/automation/selenium/src/global_functions/util_get_email_attachments.py", line 10, in <module>
inbox = mapi.GetDefaultFolder(0)
File "<COMObject <unknown>>", line 2, in GetDefaultFolder
pywintypes.com_error: (-2147024809, 'The parameter is incorrect.', None, None)
I wanted to include my completed working code in-case anyone else will find it useful:
def get_email_attachments(self):
outlook = win32com.client.Dispatch("Outlook.Application").GetNameSpace('MAPI')
# change the Folders parameter to the directory you are having the attachment go to
inbox = outlook.GetDefaultFolder(6).Folders('ForAttachments')
messages = inbox.Items
message = messages.GetLast() # opens the last message
attachments = message.Attachments
attachment = attachments.Item(1)
attachment.SaveAsFile('C:\\temp\\' + attachment.FileName)
The GetDefaultFolder is not defined on the application object (see application docs), it is defined on the NameSpace object which you get via
mapi = outlook.GetNameSpace("MAPI")
Then
inbox = mapi.GetDefaultFolder(0)
I think you can also use
mapi = outlook.Session
instead of GetNameSpace.
Related
am novice in python.Extracted below code to login to website from an online post, but getting error.
Please help to fix it and an explanation will help me
import requests
with requests.Session() as c:
EMAIL = 'noob.python#gmail.com'
PASSWORD = 'Dabc#123'
URL = 'https://www.linkedin.com/'
c.get(URL)
token = c.cookies['CsrfParam']
# This is the form data that the page sends when logging in
login_data = {loginCsrfParam:token, session_key:EMAIL, session_password:PASSWORD}
# Authenticate
r = c.post(URL, data=login_data)
# Try accessing a page that requires you to be logged in
r = c.get('https://www.linkedin.com/feed/')
print r.content
Am stuck with below Error:
C:\Python27>python website.py
Traceback (most recent call last):
File "website.py", line 8, in <module>
token = c.cookies['CsrfParam']
File "C:\Python27\lib\site-packages\requests\cookies.py", line 329, in __getitem__
return self._find_no_duplicates(name)
File "C:\Python27\lib\site-packages\requests\cookies.py", line 400, in _find_no_duplicates
raise KeyError('name=%r, domain=%r, path=%r' % (name, domain, path))
KeyError: "name='CsrfParam', domain=None, path=None"
The reason you're getting the error is that you're calling a value from a list which is empty. To call the first item in the list you say list[0]. In this case the list you're calling is empty so the first value doesn't exist hence the error.
I've ran your code and there is no #id value of 'recaptcha-token' which is why the code is returning an empty list. The only place a recaptcha token is needed is for signing up so I would suggest trying to log in without creating the authenticity_token.
I am using tweepy twitter api for python, while using it i got some error,
I am not able to use send_direct_message(user/screen_name/user_id, text) this method
Here is my code:-
import tweepy
consumer_key='XXXXXXXXXXXXXXXXX'
consumer_secret='XXXXXXXXXXXXXXXXX'
access_token='XXXXXXXXXXXXXXXXX'
access_token_secret='XXXXXXXXXXXXXXXXX'
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
API = tweepy.API(auth)
user = API.get_user('SSPendse')
screen_name="CJ0495"
id = 773436067231956992
text="Message Which we have to send must have maximum 140 characters, If it is Greater then the message will be truncated upto 140 characters...."
# re = API.send_direct_message(screen_name, text)
re = API.send_direct_message(id, text)
print re
got following error:-
Traceback (most recent call last):
File "tweetApi.py", line 36, in <module>
re = API.send_direct_message(id, text)
File "/usr/local/lib/python2.7/dist-packages/tweepy/binder.py", line 245, in _call
return method.execute()
File "/usr/local/lib/python2.7/dist-packages/tweepy/binder.py", line 229, in execute
raise TweepError(error_msg, resp, api_code=api_error_code)
tweepy.error.TweepError: [{u'message': u'Text parameter is missing.', u'code': 38}]
What will be mistake done by me...???
I also have another problem related to tweepy, How can I moved to page two or got more followers in following code
i=1
user = API.get_user('Apple')
followers = API.followers(user.id,-1)
for follower in followers:
print follower,'\t',i
i=i+1
if I run the code I got only 5000 followers however if I use user.followers_count it gives 362705 followers (This no. may be changes while You check it) How can I see remaining followers
Thank You... :)
To solve your first error, replace re = API.send_direct_message(id, text) with re = API.send_direct_message(id, text=text). This function only works if you give it the message as a named parameter. The parameter name you need here is "text", so you might want to change your variable name to avoid confusion. Also, I just tried it, since you are sending a direct message, not a tweet, it will not be truncated to only the first 140 characters.
For your second question, this should do the trick, as explained here:
followers = []
for page in tweepy.Cursor(API.followers, screen_name='Apple').pages():
followers.extend(page)
time.sleep(60) #this is here to slow down your requests and prevent you from hitting the rate limit and encountering a new error
print(followers)
On my Raspberry Pi running raspbian jessie I tried to go through the OAuth2 flow to connect a program to my dropbox using the dropbox SDK for Python which I installed via pip.
For a test, I copied the code from the documentation (and defined the app-key and secret, of course):
from dropbox import DropboxOAuth2FlowNoRedirect
auth_flow = DropboxOAuth2FlowNoRedirect(APP_KEY, APP_SECRET)
authorize_url = auth_flow.start()
print "1. Go to: " + authorize_url
print "2. Click \"Allow\" (you might have to log in first)."
print "3. Copy the authorization code."
auth_code = raw_input("Enter the authorization code here: ").strip()
try:
access_token, user_id = auth_flow.finish(auth_code)
except Exception, e:
print('Error: %s' % (e,))
return
dbx = Dropbox(access_token)
I was able to get the URL and to click allow. When I then entered the authorization code however, it printed the following error:
Error: 'str' object has no attribute 'copy'
Using format_exc from the traceback-module, I got the following information:
Traceback (most recent call last):
File "test.py", line 18, in <module>
access_token, user_id = auth_flow.finish(auth_code)
File "/usr/local/lib/python2.7/dist-packages/dropbox/oauth.py", line 180, in finish
return self._finish(code, None)
File "/usr/local/lib/python2.7/dist-packages/dropbox/oauth.py", line 50, in _finish
url = self.build_url(Dropbox.HOST_API, '/oauth2/token')
File "/usr/local/lib/python2.7/dist-packages/dropbox/oauth.py", line 111, in build_url
return "https://%s%s" % (self._host, self.build_path(target, params))
File "/usr/local/lib/python2.7/dist-packages/dropbox/oauth.py", line 89, in build_path
params = params.copy()
AttributeError: 'str' object has no attribute 'copy'
It seems the build_path method expects a dict 'params' and receives a string instead. Any ideas?
Thanks to smarx for his comment. The error is a known issue and will be fixed in version 3.42 of the SDK. source
I'm working on an app that will stream events into BQ. Since Streamed Inserts require the table to pre-exist, I'm running the following code to check if the table exists, and then to create it if it doesn't:
TABLE_ID = "data" + single_date.strftime("%Y%m%d")
exists = False;
request = bigquery.tables().list(projectId=PROJECT_ID,
datasetId=DATASET_ID)
response = request.execute()
while response is not None:
for t in response.get('tables', []):
if t['tableReference']['tableId'] == TABLE_ID:
exists = True
break
request = bigquery.tables().list_next(request, response)
if request is None:
break
if not exists:
print("Creating Table " + TABLE_ID)
dataset_ref = {'datasetId': DATASET_ID,
'projectId': PROJECT_ID}
table_ref = {'tableId': TABLE_ID,
'datasetId': DATASET_ID,
'projectId': PROJECT_ID}
schema_ref = SCHEMA
table = {'tableReference': table_ref,
'schema': schema_ref}
table = bigquery.tables().insert(body=table, **dataset_ref).execute(http)
I'm running python 2.7, and have installed the google client API through PIP.
When I try to run the script, I get the following error:
No handlers could be found for logger "oauth2client.util"
Traceback (most recent call last):
File "do_hourly.py", line 158, in <module>
main()
File "do_hourly.py", line 101, in main
body=table, **dataset_ref).execute(http)
File "build/bdist.linux-x86_64/egg/oauth2client/util.py", line 142, in positional_wrapper
File "/usr/lib/python2.7/site-packages/googleapiclient/http.py", line 721, in execute
resp, content = http.request(str(self.uri), method=str(self.method),
AttributeError: 'module' object has no attribute 'request'
I tried researching the issue, but all I could find was info about confusing between urllib, urllib2 and Python 2.7 / 3.
I'm not quite sure how to continue with this, and will appreciate all help.
Thanks!
Figured out that the issue was in the following line, which I took from another SO thread:
table = bigquery.tables().insert(body=table, **dataset_ref).execute(http)
Once I removed the "http" variable, which doesn't exist in my scope, the exception dissappeared
i am attaching a file from a particular path c:\important\log.txt
sender = 'poojagupta4112#gmail.com'
receiver = ['shubh4112#gmail.com']
message = """From: From Pooja Gupta <poojagupta4112#gmail.com>
To: To Shubha Goel <shubh4112#gmail.com>
Subject: SMTP e-mail test
This is a test e-mail message.
"""
file_name = 'C:\important\log.txt'
msg=MIMEMultipart()
msg['From'] = sender
msg['To'] = receiver
msg['Subject'] = message
msg['Date'] = email.Utils.formatdate(localtime=True)
# build the attachment
att = MIMEBase('application', 'base64')
att.set_payload(open(file_name, 'rb').read())
email.Encoders.encode_base64(att)
att.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(file_name))
msg.attach(att)
print 'successfully built attachment'
try:
session = smtplib.SMTP('smtp.gmail.com',587)
print 'Starting..'
session.ehlo()
print 'ehlo executed..'
session.starttls()
print 'starttls done'
session.login(sender,'snxzoumwhpybzvmo')
print 'logged in'
session.sendmail(sender,receiver,msg.as_string())
print 'sendmail executed..now quitting'
session.close()
except smtplib.SMTPRecipientsRefused:
print 'Recipient refused'
except smtplib.SMTPAuthenticationError:
print 'Auth error'
except smtplib.SMTPSenderRefused:
print 'Sender refused'
except smtplib.SMTPException:
print('Error')
It keeps on giving me the same error of Attribute error list object has no attribute lstrip
the following is the error, stack trace :
Traceback (most recent call last):
File "<pyshell#8>", line 1, in <module>
execfile('C:\important\secret_file.pyw')
File "C:\important\secret_file.pyw", line 45, in <module>
session.sendmail(sender,receiver,msg.as_string())
File "C:\Python27\lib\email\message.py", line 137, in as_string
g.flatten(self, unixfrom=unixfrom)
File "C:\Python27\lib\email\generator.py", line 83, in flatten
self._write(msg)
File "C:\Python27\lib\email\generator.py", line 115, in _write
self._write_headers(msg)
File "C:\Python27\lib\email\generator.py", line 164, in _write_headers
v, maxlinelen=self._maxheaderlen, header_name=h).encode()
File "C:\Python27\lib\email\header.py", line 410, in encode
value = self._encode_chunks(newchunks, maxlinelen)
File "C:\Python27\lib\email\header.py", line 370, in _encode_chunks
_max_append(chunks, s, maxlinelen, extra)
File "C:\Python27\lib\email\quoprimime.py", line 97, in _max_append
L.append(s.lstrip())
AttributeError: 'list' object has no attribute 'lstrip'
Please Help.
it was a small error. receiver parameter was list type. either it should be list converted to string using join method or if it is a single recipient, then pass it as a string only
receiver = ['shubh4112#gmail.com']
This is a list but msg['To'] is expecting a string and hence the error.
You can use ','.join(receiver) and that should solve your problem.
This appears to be a issue from smtplib. The documentation clearly says that it accepts a list
The arguments are:
- from_addr : The address sending this mail.
- **to_addrs : A list of addresses to send this mail to. A bare
string will be treated as a list with 1 address.**
- msg : The message to send.
Usage from documentation:
"Example:
>>> import smtplib
>>> s=smtplib.SMTP("localhost")
**>>> tolist=
["one#one.org","two#two.org","three#three.org","four#four.org"]**
>>> msg = '''\\
... From: Me#my.org
... Subject: testin'...
...
... This is a test '''
>>> s.sendmail("me#my.org",tolist,msg)"
Also as said in the documentation if recipients are passed as string, mail is being sent to first mailid only.
So actually the problem is that SMTP.sendmail and email.MIMEText need two different things.
email.MIMEText sets up the "To:" header for the body of the e-mail. It is
ONLY used for displaying a result to the human being at the other end, and
like all e-mail headers, must be a single string. (Note that it does not
actually have to have anything to do with the people who actually receive
the message.)
SMTP.sendmail, on the other hand, sets up the "envelope" of the message for
the SMTP protocol. It needs a Python list of strings, each of which has a
single address.
So, what you need to do is COMBINE the two replies you received. Set
msg['To'] to a single string, but pass the raw list to sendmail:
emails = ['a.com','b.com', 'c.com']**
**msg['To'] = ', '.join( emails )
....
s.sendmail( msg['From'], emails, msg.as_string() )****
I have the same problem, my solution:
msg['To'] = receiver
receive must be string like 'aa#bb.com,bb#cc.com', not list