Twilio Unable to send fax - django

Hope you are having a nice day.
I am getting following error on twillion fax api
HTTP Error Your request was:
POST /Faxes
Twilio returned the following information:
Unable to create record: The requested resource /Faxes was not found
Here is the code .
def __init__(self):
self.client = Client(
settings.TWILIO_ACCOUNT_SID,
settings.TWILIO_AUTH_TOKEN,
)
self.sender = settings.FAX_SENDER
self.receiver = settings.FAX_RECEIVER
self.callback_url = settings.TWILIO_CALLBACK_URL
i am sending a fax in function with this code
fax = self.client.fax.faxes.create(
from_=self.sender,
to=self.receiver,
media_url=pdf_url,
status_callback=self.callback_url,
)
Here is the trackback
fax = client.fax.faxes.create(from_= sender,to=receiver,media_url = 'https://mysite.ca/media/7ad4a93f0e7641b58e078da171b3651a.pdf',status_callback = callback_url,)
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/var/www/vhosts/site/httpdocs/venv/lib64/python3.6/site-packages/twilio/rest/fax/v1/fax/__init__.py", line 186, in create
payload = self._version.create(method='POST', uri=self._uri, data=data, )
File "/var/www/vhosts/site/httpdocs/venv/lib64/python3.6/site-packages/twilio/base/version.py", line 209, in create
raise self.exception(method, uri, response, 'Unable to create record')
twilio.base.exceptions.TwilioRestException:
HTTP Error Your request was:
POST /Faxes
Twilio returned the following information:
Unable to create record: The requested resource /Faxes was not found
More information may be available here:
https://www.twilio.com/docs/errors/20404
also, I confirmed that my Twilio account is working and active.

It seems like the Faxes API has been deprecated. If you go to https://www.twilio.com/fax you'll see a message.
We are no longer supporting Programmable Fax as of December 17, 2021.
For new and inactive accounts, access to Programmable Fax is disabled effective immediately. So if your account are new, you basically have no options except switching the provider.

Thank you for the help, Twilio blocked my account, however they enabled it since it was active before the cut off date.

Related

Django easypost buy returns malformed syntax when using test api key but insufficient funds with production

Using the easypost python library I call the buy function passing in the rate like the documentation says but it returns an error.
Can you use your test api key with buy for easypost or not? I didn't see anything in the documentation with it. It might seem to work with production but I am not able to test that yet so I was wondering if I could test it with the test api key?
The code is:
import easypost
def get_shipment(shipment_id):
return easypost.Shipment.retrieve(shipment_id)
......
shipment = get_shipment(shipment_id)
try:
shipment.buy(rate=shipment.lowest_rate())
except Exception as e:
raise ValidationError({'detail': e.message})
The error message I get with test key
Traceback (most recent call last):
File "/app/returns/serializers.py", line 237, in handle_shipment_purchase
shipment.buy(rate=shipment.lowest_rate())
File "/usr/local/lib/python3.6/dist-packages/easypost/__init__.py", line 725, in buy
response, api_key = requestor.request('post', url, params)
File "/usr/local/lib/python3.6/dist-packages/easypost/__init__.py", line 260, in request
response = self.interpret_response(http_body, http_status)
File "/usr/local/lib/python3.6/dist-packages/easypost/__init__.py", line 321, in interpret_response
self.handle_api_error(http_status, http_body, response)
File "/usr/local/lib/python3.6/dist-packages/easypost/__init__.py", line 383, in handle_api_error
raise Error(error.get('message', ''), http_status, http_body)
easypost.Error: The request could not be understood by the server due to malformed syntax.
I got the same issue with Python though my shipment id and API_KEY are correct. with the EasyPost python exception message, it will not show the root cause of the exception. Try to do request with curl or inside exception check e.json_body and raise ValidationError accordingly.
try:
shipment.buy(rate=shipment.lowest_rate())
except Exception as e:
# Put debugger here and Check exception e.json_body
e.json_body
raise ValidationError({'detail': e.http_body})
Yes, you can buy shipments with your TEST API key. From the code you shared, I don't see any obvious problems, but you'll obviously want to double check that your shipment_id is being set correctly and that your API key is as well. Beyond that, write to us as support#easypost.com and we can actually look into our system logs to see what may be coming in "malformed".

Flask-Mail not Authenticating with Gmail and App password

So I am getting an SMTPSenderRefused error when I try to use the flask app I built to send an email. Let me start buy saying this worked previously but now it has stopped. I am at a loss and I have spent many hours testing and tweaking and reading online and NOTHING has given me an answer.
I keep getting the following error.
[2019-01-21 03:07:51,954] ERROR in app: Exception on /register/ [POST]
Traceback (most recent call last):
File "/usr/local/lib/python2.7/site-packages/flask/app.py", line 2292, in wsgi_app
response = self.full_dispatch_request()
File "/usr/local/lib/python2.7/site-packages/flask/app.py", line 1815, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/usr/local/lib/python2.7/site-packages/flask/app.py", line 1718, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/usr/local/lib/python2.7/site-packages/flask/app.py", line 1813, in full_dispatch_request
rv = self.dispatch_request()
File "/usr/local/lib/python2.7/site-packages/flask/app.py", line 1799, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "MyFlaskApp.py", line 131, in register
mail.send(msg)
File "/usr/local/lib/python2.7/site-packages/flask_mail.py", line 492, in send
message.send(connection)
File "/usr/local/lib/python2.7/site-packages/flask_mail.py", line 427, in send
connection.send(self)
File "/usr/local/lib/python2.7/site-packages/flask_mail.py", line 192, in send
message.rcpt_options)
File "/usr/lib64/python2.7/smtplib.py", line 737, in sendmail
raise SMTPSenderRefused(code, resp, from_addr)
SMTPSenderRefused: (530, '5.5.1 Authentication Required. Learn more at\n5.5.1 https://support.google.com/mail/?p=WantAuthError u186sm20332024pfu.51 - gsmtp', u'myemail#gmail.com')
IP.XX.XXX.XXX - - [21/Jan/2019 03:07:51] "POST /register/ HTTP/1.1" 500 -
My gmail account is configured with 2 step verification and then an application password that this Flask App uses. I have tried every combination and it still will not work. This is my code that I am using.
app = Flask(__name__, static_url_path='/static')
app.config.update(
DEBUG = False,
MAIL_SERVER = 'smtp.gmail.com',
MAIL_PORT = 465,
MAIL_USE_SSL = True,
MAIL_USERNAME = 'myemail#gmail.com',
MAIL_DEFAULT_SENDER = 'myemail#gmail.com',
MAIL_PASSWORD = 'GmailApplicationPassword',
)
mail = Mail(app)
The lines to actually send the message (inside the POST):
msg = Message("Welcome",
sender = 'myemail#gmail.com',
recipients = [request.form["email"]])
msg.body = "Welcome! \n\n Congratulations on your successful registration. \n\n Cheers!"
mail.send(msg)
Some additional information that might be helpful. This exact code used to work when I was running my application locally. Then I deployed my code to my AWS EC2 instance and had it working on there. It was working until I did the following.
I associated a Elastic IP address with the site and then pointed my DNS to that IPv4. I have also added AWS Public Certificate.
Can someone please help me understand why I am unable to send emails. I have tried everything I can find as solutions online.
Additional Details:
$ pip freeze
Flask-Mail==0.9.1
Thanks in advance and I will help provide any answers if more clarification is needed so please ask.
This is the solution that I found to work best. (I am not saying this is the best method but it works) It involves the use of a few different key concepts that I would Highly Recommend using. It involves the use of secrets, which you can follow this guide here for more information on this (as it is not the heart of this question I will only leave a link here). It also required the use of Boto3 to be able to read the variables. The AWS documentation will be helpful here so again I am not including it.
My method was to set up AWS Simple Email Service (SES). This makes it such that the application using Flask-Mail accesses AWS SES to send the email which then talks to gmail to actually send out the email. A few important notes here are that the SES is not in every region but presently (June 2019) it is not required that your EC2 instance be hosted in the same region that you are using SES in. Additionally, if you want to be able to send emails to outside addresses you MUST ensure that you have the email inbox configured in accordance with and not violate AWS terms of use. And Finally if you are on the free tier, you must submit a support ticket to get a rate increase and it will also allow you to send emails externally. Now here is the bit of code that I use:
app = Flask(__name__, static_url_path='/static')
app.config.update(
DEBUG = False,
MAIL_SERVER = params.getParameter("SES_SERVER"),
MAIL_PORT = 587,
MAIL_USE_TLS = True,
MAIL_USERNAME = params.getParameter("SES_USERNAME"),
MAIL_PASSWORD = params.getParameter("SES_PASSWORD"),
)
mail = Mail(app)
The sending code remains unchanged.
I did need to add the an import for Boto3 and I created a new file that is called params.py and is where I built my getParameter method to access the variables. If you want you could hard code the values above but I would not recommend it, especially if you are storing your code in a cloud repository.
I am not 100% sure but I suspect that gmail prohibits a IP address or domain from AWS accessing its servers and thus you cannot send emails. This is my suspicion but I could not find a way to prove it.
For gmail accounts for which 2-Step verification is activated, allowing less secure app is disabled. In that case to access App Password need to be generated.
This is app config code written in flask app.
`app = Flask(__name__)
app.config.update(
MAIL_SERVER = "smtp.gmail.com",
MAIL_PORT="465",
MAIL_USE_SSL=True,
MAIL_USERNAME=params['gmail-user'],
MAIL_PASSWORD=params['gmail-pass']
)
mail=Mail(app)`
Created "config.json" to define the parameter, which will be used above. For username and password check "gmail-user" and "gmail-pass"
{"params":
{ "local_server":"True",
"local_uri":"mysql+pymysql://root:#localhost/jbh_datasc_blog",
"prod_uri": "mysql+pymysql://root:#localhost/jbh_datasc_blog",
"fb_url":"https://facebook.com/<give the name of extension>",
"tw_url":"https://twitter.com/<give the name of extension>",
"gh_url":"https://github.com/<give the name of extension>",
"blog_head":"Data Science Digital",
"sub_head":"Innovating Future",
"gmail-user":"xxxxxxxx#gmail.com",
"gmail-pass":"xxxxxxxxxxxxxxxx"
}
}
Go the your gmail account and in the search bar type App Password.
It will ask about the name of app and computer from where r u accessing, provide it.
Google will generate a 16 digit password.
Use this password to fill in the 'gmail-pass'
Save and execute the code.

Error while accessing Google Contacts Groups by API

I want get list of all groups in my contacts. I use that code:
import gdata.gauth
import gdata.contacts.client
token = gdata.gauth.OAuth2Token(client_id = "***.apps.googleusercontent.com",
client_secret = "***",
scope = "https://www.google.com/m8/feeds/",
user_agent = "GC")
gd_client = gdata.contacts.client.ContactsClient(source = 'GCv0.1')
gd_client = token.authorize(gd_client)
gd_client.GetGroups()
But got error:
Traceback (most recent call last):
File "F:/Yandex/Sites/GoogleContacts/cli_contacts.py", line 27, in <module>
gd_client.GetGroups()
File "C:\Users\Ishayahu\27Gdata\lib\site-packages\gdata\contacts\client.py", line 218, in get_groups
return self.get_feed(uri, desired_class=desired_class, auth_token=auth_token, **kwargs)
File "C:\Users\Ishayahu\27Gdata\lib\site-packages\gdata\client.py", line 640, in get_feed
**kwargs)
File "C:\Users\Ishayahu\27Gdata\lib\site-packages\gdata\client.py", line 319, in request
RequestError)
gdata.client.RequestError: Server responded with: 400,
enter code here
I have no idea what a reason and I can't find any clue how to solve it.
UPD: It looks like I should somehow put acess_token or refresh_token into OAuth2Token, but I can't understand how
so it send headers
{'GData-Version': '3', 'Authorization': 'Bearer None', 'User-Agent': 'gdata-py/2.0.17'}
UPD2: by the way, if I test in in OAuth2Playground, it shows me a page with request access to my contacts. That script doesn't ask for it. Maybe that's the problem? How can I change it? I thought, it connect with url_redirect, but I can't uderstand, how to use it
UPD3: I was right: if I add access_token, which I get manualy from Playground, all works. But how should I get it in script?!

linkedin api - python - get_connections()

I am working on a simple python scraping script, I am trying to get connections from LinkedIn using their API without a redirect_uri. I worked once with some APIs, that don't require the redirect url or just https://localhost. I got the consumer_key, consumer_secret, user_secret, consumer_secret. Here's the code i am using from https://github.com/ozgur/python-linkedin:
RETURN_URL = ''
url = 'https://api.linkedin.com/v1/people/~'
# Instantiate the developer authentication class
authentication = linkedin.LinkedInDeveloperAuthentication(CONSUMER_KEY, CONSUMER_SECRET,
USER_TOKEN, USER_SECRET,
RETURN_URL, linkedin.PERMISSIONS.enums.values())
# Pass it in to the app...
application = linkedin.LinkedInApplication(authentication)
print application.get_profile() # works
print application.get_connections()
And here's the error I get:
Traceback (most recent call last):
File "getContacts.py", line 20, in <module>
print application.get_connections()
File "/home/imane/Projects/prjL/env/local/lib/python2.7/site-packages/linkedin/linkedin.py", line 219, in get_connections
raise_for_error(response)
File "/home/imane/Projects/prjL/env/local/lib/python2.7/site-packages/linkedin/utils.py", line 63, in raise_for_error
raise LinkedInError(message)
linkedin.exceptions.LinkedInError: 403 Client Error: Forbidden for url: https://api.linkedin.com/v1/people/~/connections: Unknown Error
This is my first question here, so excuse me if I didn't make it clear enough, and thank you for helping me out.
Here's what i tried with python_oauth2:
import oauth2 as oauth
import requests
url = 'https://api.linkedin.com/v1/people/~'
params = {}
token = oauth.Token(key=USER_TOKEN, secret=USER_SECRET)
consumer = oauth.Consumer(key=CONSUMER_KEY, secret=CONSUMER_SECRET)
# Set our token/key parameters
params['oauth_token'] = token.key
params['oauth_consumer_key'] = consumer.key
oauth_request = oauth.Request(method="GET", url=url, parameters=params)
oauth_request.sign_request(oauth.SignatureMethod_HMAC_SHA1(), consumer, token)
signed_url = oauth_request.to_url()
response = requests.get(signed_url)
Connections API calls are a restricted endpoint as of March, 2015. It's possible you're using sample code/documentation that was written at a time when anyone could access those endpoints. You are receiving a 403 response because your application legitimately does not have the permission required to make that request.

Google Python Admin SDK using Oauth2 for a Service Account (Education Edition)-"oauth2client.client.AccessTokenRefreshError: access_denied" exception

I have been trying to get the Service Account authentication working for the Google Admin SDK for a few days now to no avail. I am using the google-api-python-client-1.2 library freshly installed from Google.
I have been following Google's documentation on the topic. Links are here:
htps://developers.google.com/accounts/docs/OAuth2ServiceAccount
htps://developers.google.com/api-client-library/python/guide/aaa_oauth
htp://google-api-python-client.googlecode.com/hg/docs/epy/oauth2client.client.SignedJwtAssertionCredentials-class.html
And have the tasks.py Service Account example working which you can be found here:
htp://code.google.com/p/google-api-python-client/source/browse/samples/service_account/tasks.py?r=c21573904a2df1334d13b4380f63463c94c8d0e8
And have been closely studying these two Stack Overflow threads on a related topic here:
google admin sdk directory api 403 python
Google Admin API using Oauth2 for a Service Account (Education Edition) - 403 Error
And have studied the relevant code in gam.py (Dito GAM).
Yet I'm still missing something as I am getting an 'oauth2client.client.AccessTokenRefreshError: access_denied' exception in nearly every test case I write.
Here is a concise example of a test authentication:
import httplib2
from apiclient.discovery import build
from oauth2client.client import SignedJwtAssertionCredentials
f = file('myKey.p12', 'rb')
key = f.read()
f.close()
credentials = SignedJwtAssertionCredentials(
'myServiceAdmin#developer.gserviceaccount.com',
key,
sub='myAdminUser#my.googleDomain.edu',
scope = ['https://www.googleapis.com/auth/admin.directory.user',])
http = httplib2.Http()
http = credentials.authorize(http)
service = build('admin', 'directory_v1', http=http)
When I run the above code I get this stack dump and exception:
Traceback (most recent call last):
File "./test.py", line 17, in <module>
service = build('admin', 'directory_v1', http=http)
File "/usr/lib/python2.7/dist-packages/oauth2client/util.py", line 132, in positional_wrapper
return wrapped(*args, **kwargs)
File "/usr/lib/python2.7/dist-packages/apiclient/discovery.py", line 192, in build resp, content = http.request(requested_url)
File "/usr/lib/python2.7/dist-packages/oauth2client/util.py", line 132, in positional_wrapper
return wrapped(*args, **kwargs)
File "/usr/lib/python2.7/dist-packages/oauth2client/client.py", line 475, in new_request
self._refresh(request_orig)
File "/usr/lib/python2.7/dist-packages/oauth2client/client.py", line 653, in _refresh
self._do_refresh_request(http_request)
File "/usr/lib/python2.7/dist-packages/oauth2client/client.py", line 710, in _do_refresh_request
raise AccessTokenRefreshError(error_msg)
oauth2client.client.AccessTokenRefreshError: access_denied
I've tried multiple super user accounts, service accounts, and keys and always end up with the same exception. If I add sub to the tasks.py example I end up with the same error. Replacing sub with prn also generates this exception and adding private_key_password='notasecret' does nothing (it is the default). The Admin SDK is activated in the Google Developers Console and the target accounts have super user privileges. This makes me think something is missing on the Google domain side but I cannot think of anything else to check.
Any one have an idea what I am doing wrong?
Have you granted the third party client access in your Admin Console for your service account?
My to go instruction when it comes to setting up Service Account is the instruction Google has for Drive Api.
https://developers.google.com/drive/web/delegation
Take a look at the "Delegate domain-wide authority to your service account" part and see if you have completed those steps.
Maybe not OP's problem, but I had this same error and my issue was that I was setting the sub field in the credentials object
credentials = SignedJwtAssertionCredentials(SERVICE_ACCOUNT_EMAIL, key,
scope=SCOPES, sub=**<DON'T SET ME>**)
If you're using domain-wide delegation, you need to not set a sub (because your "user" is the domain administrator.) The docs are a bit confusing on this point. I just removed the sub field and it worked for me.