Send request Odoo doesn't deliver email - python

I am using OdooRPC to send sign request in Odoo.
The process consist in 4 Parts:
Send the document to Sign to Odoo.
Send the fields to sign in the document, can be text field type or sign field.
Prepare the email template with the document and the signers (contacts from Odoo) to sign request.
Send the sign request email.
The code to prepare the request is:
request_fields = {
'template_id': template_id,
'signer_ids': [[0, 'virtual_25', {'role_id': 2, 'partner_id': employee_id1}],
[0, "virtual_37", {'role_id': 3, 'partner_id': employee_id2}]],
'signer_id': False,
'signers_count': 2,
'has_default_template': True,
'is_user_signer': False,
'follower_ids': [[6, False, []]],
'subject': 'Sign Request',
'filename': 'document_to_sign.pdf',
'message_cc': '<p><br></p>',
'attachment_ids': [[6, False, []]],
'message': '<p>Hi.</p><p>Sign this document, no reply</p>'
}
# Prepare email request
sign_email = self.odoo.env['sign.send.request']
email_id = sign_email.create(request_fields)
After create the email template, I can tell Odoo to send the sign request
# Prepare email request
sign_email = self.odoo.env['sign.send.request']
email_id = sign_email.create(request_fields) # int type
request_sign = sign_email.send_request(email_id)
The answer method doesn't show any error:
{'name': 'file_name.pdf', 'type': 'ir.actions.client', 'tag': 'sign.Document', 'context': {'id': 1234, 'token': 'abcd-1234-efgh-5678', 'sign_token': None, 'create_uid': 9, 'state': 'sent', 'request_item_states': {'1234': False, '1235': False}}}
The method 'send_request' create the email in Odoo, but it doesn't deliver the email to the recipents.

have you configured outgoing mail server in odoo which is in settings>technical>outgoing mail server if not please configure it, if yes then check in settings>technical>email if the email is sent from your side then a record will be created in it. please check it and update those information in the question in order to help you better.

I got the email message now.
removed the 'is_user_signer' key from the request_fields dictionary.
request_fields = {
'template_id': template_id,
'signer_ids': [[0, 'virtual_25', {'role_id': 2, 'partner_id': employee_id1}],
[0, "virtual_37", {'role_id': 3, 'partner_id': employee_id2}]],
'signer_id': False,
'signers_count': 2,
'has_default_template': True,
'follower_ids': [[6, False, []]],
'subject': 'Sign Request',
'filename': 'document_to_sign.pdf',
'message_cc': '<p><br></p>',
'attachment_ids': [[6, False, []]],
'message': '<p>Hi.</p><p>Sign this document, no reply</p>'
}
Now, it sends email messages with the sign request.

Related

Stawpoll can't create poll

I am working on a program that includes a strawpoll. As far as I can tell this code should work to create a poll however it is returning an error page instead of a poll. Here is the api
json = json.dumps({"title": "Question", "options": ["option1", "option2", "option3"]})
poll = requests.post("http://strawpoll.me/api/v2/polls", data = json, headers = {"Content-Type": "application/json"})
This is the url it returns
https://www.strawpoll.me/error?aspxerrorpath=/api/v2/polls
Unfortunately, strawpoll.me' api have been broken for quite some time now. You can still retrieve the polls but creating one redirects you to the error landing page.
Try posting your request to https://www.strawpoll.me/api/v2/polls:
data = {"title": "Question", "options": ["option1", "option2", "option3"]}
poll = requests.post("https://www.strawpoll.me/api/v2/polls", json=data,
headers={"Content-Type": "application/json"})
print(poll.url)
# https://www.strawpoll.me/api/v2/polls
print(poll.json())
# {'multi': False, 'title': 'Question', 'votes': [0, 0, 0], 'id': 16578754,
# 'captcha': False, 'dupcheck': 'normal', 'options': ['option1', 'option2', 'option3']}

Unable to update data in pymongo

I have a JSON POST data that a user is going to send me every time to fetch some data from a third party service.I plan to cache the data based on a scope id so that I don't keep inserting the data each time the user requests for something.Futhermore I am keeping a time stamp for each user request.Below is the POST data that user is going to send me everytime.
{
"scope_id": "user1",
"tool_id": "appdynamics",
"api_id": "get metrics",
"input_params": {"user": "myuser", "pwd": "mypwd", "acc_id": "myaccount", "app_id": "TestApp", "metric-path": "ars",
"time-range-type": "BEFORE_NOW", "duration-in-mins": 10},
"output_filters": {}
}
Below is the code snippet to handle the insertion of data
def post(self):
data = ServiceAPI.parser.parse_args()
print("First data", data)
scope_id = data["scope_id"]
tool_id = data["tool_id"]
api_id = data["api_id"]
input_params = data["input_params"]
output_filter = data["output_filter"]
if all([scope_id, tool_id, api_id]) and all(input_params.values()):
check_id = [j for i in users.find({}) for j in i if j == scope_id]
if check_id and check_id[0] == scope_id:
users.update({scope_id: [tool_id, api_id, input_params]},
{scope_id: [tool_id, api_id, input_params],
"timestamp": datetime.now().strftime('%Y-%m-%d %H:%M:%S')}, upsert=True)
else:
users.insert_one(
{scope_id: [tool_id, api_id, input_params],
"timestamp": datetime.now().strftime('%Y-%m-%d %H:%M:%S')})
Here the update statement works great if the user request is exactly the same as last time but makes a new entry if the user demands a new information for example in the POST request api_id = "get logs" when ideally it should have updated the user's data with the latest one.
For the first time when the user makes a POST request, below is the data that gets stored in my database
[{'user1': ['appdynamics', 'get metrics', {'pwd': 'mypwd', 'metric-path': 'ars', 'user': 'myuser', 'time-range-type': 'BEFORE_NOW', 'acc_id': 'myaccount', 'app_id': 'TestApp', 'duration-in-mins': 10}], 'timestamp': '2018-03-24 21:49:28', '_id': ObjectId('5ab67a901899db6d8a266558')}]
Now I make the same request again, it ensures no new entry is made since its made by the same scope id
However now if the user requests some new information for example
{
"scope_id": "user1",
"tool_id": "appdynamics",
"api_id": "get logs",
"input_params": {"user": "myuser", "pwd": "mypwd", "acc_id": "myaccount", "app_id": "TestApp", "metric-path": "ars",
"time-range-type": "BEFORE_NOW", "duration-in-mins": 10},
"output_filters": {}
}
Notice I have changed "api_id": "get logs", it makes a new entry instead of just modifying the existing data in my database.Here is the data now
[{'user1': ['appdynamics', 'get metrics', {'pwd': 'mypwd', 'metric-path': 'ars', 'user': 'myuser', 'time-range-type': 'BEFORE_NOW', 'acc_id': 'myaccount', 'app_id': 'TestApp', 'duration-in-mins': 10}], 'timestamp': '2018-03-24 21:49:28', '_id': ObjectId('5ab67a901899db6d8a266558')}, {'user1': ['appdynamics', 'get logs', {'pwd': 'mypwd', 'metric-path': 'ars', 'user': 'myuser', 'time-range-type': 'BEFORE_NOW', 'acc_id': 'myaccount', 'app_id': 'TestApp', 'duration-in-mins': 10}], 'timestamp': '2018-03-24 21:55:29', '_id': ObjectId('5ab67bf9089b16e9e77037f4')}]
So here the update seems to fail.What could be going wrong?
Note: This is a flask app and I suggest not to get into the details of the implementation.I just need to update the given data based on the scope id each time a user makes a request irrespective of whether it is the same request or a different one.
You are passing upsert=True to update(). Upsert tells MongoDB to update an existing document if one matching the query is found, insert a new document otherwise. The first parameter to update() is a query filter to find documents to apply the update to. The update query filter where api_id == "get logs" isn't matching any existing document, so a new document is being created.

Export Methods for SugarCRM v10 api

I am trying to make a call to the SugarCRM v10 api to get the output of a report without having to log into the web interface and click the export button. I would like to get this report as data that can be written into csv format using python and the requests library.
I can authenticate successfully and get a token but whatever I try all I get as a response from reports is Error Method does not exist, by which they mean that you cannot use /csv at the end of the second url in this code block.
url = "https://mydomain.sugarondemand.com/rest/v10/oauth2/token"
payload = {"grant_type":"password","username":"ursername","password":"password","client_id":"sugar", "platform":"myspecialapp"}
r = requests.post(url, data=json.dumps(payload))
response = json.loads(r.text)
token = response[u'access_token']
print 'Success! OAuth token is ' + token
#What export methods are available? ###################################
#WRONG url = "https://mydomain.sugarondemand.com/rest/v10/Reports/report_id/csv"
#Following paquino's suggestion I used Base64
url = "https://mydomain.sugarondemand.com/rest/v10/Reports/report_id/Base64"
headers = { "Content-Type" : "application/json", "OAuth-Token": token }
r = requests.get(url, headers=headers);
response = r.text.decode('base64')
print response`
My question is this: what Export Methods are available via an api call to v10 of the SugarCRM api.
Edit: Using Base64 in the request url unfortunately returns ab object that I don't know how to parse...
%PDF-1.7
3 0 obj
<</Type /Page
/Parent 1 0 R
/MediaBox [0 0 792.00 612.00]
/Resources 2 0 R
/Contents 4 0 R>>
endobj
4 0 obj
<</Length 37217>>
stream
8.cܬR≈`ä║dàQöWºáW╙µ
The Reports Api accepts "Base64" and "Pdf"
Python Wrapper for SugarCRM REST API v10
https://github.com/Feverup/pysugarcrm
Quickstart
pip install pysugarcrm
from pysugarcrm import SugarCRM
api = SugarCRM('https://yourdomain.sugaropencloud.e', 'youruser', 'yourpassword')
# Return info about current user
api.me
# A more complex query requesting employees
api.get('/Employees', query_params={'max_num': 2, 'offset': 2, 'fields': 'user_name,email'})
{'next_offset': 4,
'records': [{'_acl': {'fields': {}},
'_module': 'Employees',
'date_modified': '2015-09-09T13:40:32+02:00',
'email': [{'email_address': 'John.doe#domain.com',
'invalid_email': False,
'opt_out': False,
'primary_address': True,
'reply_to_address': False}],
'id': '12364218-7d79-80e0-4f6d-35ed99a8419d',
'user_name': 'john.doe'},
{'_acl': {'fields': {}},
'_module': 'Employees',
'date_modified': '2015-09-09T13:39:54+02:00',
'email': [{'email_address': 'alice#domain.com',
'invalid_email': False,
'opt_out': False,
'primary_address': True,
'reply_to_address': False}],
'id': 'a0e117c0-9e46-aebf-f71a-55ed9a2b4731',
'user_name': 'alice'}]}
# Generate a Lead
api.post('/Leads', json={'first_name': 'John', 'last_name': 'Smith', 'business_name_c': 'Test John', 'contact_email_c': 'john#smith.com'})
from pysugarcrm import sugar_api
with sugar_api('http://testserver.com/', "admin", "12345") as api:
data = api.get('/Employees', query_params={'max_num': 2, 'offset': 2, 'fields': 'user_name,email'})
api.post('/Leads', json={'first_name': 'John', 'last_name': 'Smith', 'business_name_c': 'Test John', 'contact_email_c': 'john#smith.com'})
# Once we exit the context manager the sugar connection is closed and the user is logged out

How to find uid of existing python email object

I have been reading through this document. Most of the document is based on finding an email's uid. From the article:
"The way this works is pretty simple: use the uid function, and pass in the string of the command in as the first argument. The rest behaves exactly the same.
result, data = mail.uid('search', None, "ALL") # search and return uids instead
latest_email_uid = data[0].split()[-1]
result, data = mail.uid('fetch', latest_email_uid, '(RFC822)')
raw_email = data[0][1]
I'm working with a django app called django-mailbox (http://django-mailbox.readthedocs.org/en/latest/index.html) the purpose of which is to consume emails.
The app creates a "Message" model that looks like:
u'django_mailbox.message': {
'Meta': {'object_name': 'Message'},
'body': ('django.db.models.fields.TextField', [], {}),
'encoded': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'from_header': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'in_reply_to': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'replies'", 'null': 'True', 'to': u"orm['django_mailbox.Message']"}),
'mailbox': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'messages'", 'to': u"orm['django_mailbox.Mailbox']"}),
'message_id': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'outgoing': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'processed': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'read': ('django.db.models.fields.DateTimeField', [], {'default': 'None', 'null': 'True', 'blank': 'True'}),
'subject': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'to_header': ('django.db.models.fields.TextField', [], {})
using the python "email" library I can select a record from a django queryset and turn it into an email object:
qs = Message.objects.filter("my criteria")
first = qs[0]
one = first.get_email_object() // one is an email object
Does the existing data in the db have a uid, and if so how can I grab it.
The strict answer to your question is "no". The document you quote is about looping through an IMAP folder (in this case, a Gmail account), which will certainly get a unique ID (uid) from the server which tracks the unique message ID for each Email message.
Because you are constructing a mail message object using Django, you won't have such a UID. The "ID" field you do get from django.db.models.fields.AutoField is the sequential auto-increment ID that the Gmail/IMAP web page you quote says is "unacceptable".
You may want to look at the "uuid" library (http://docs.python.org/2/library/uuid.html) to generate unique ID values for your messages, but unless you also store those in your database, you'll be re-generating them over and over.
If you care to share more exact information about what you're trying to build (a web-based Email reader, perhaps?) then we as a community might have some better ideas for you.
you will get the uid of your mail in response
email_user = 'your gmail'
email_pass = 'your app password'
mail = imaplib.IMAP4_SSL('imap.gmail.com')
mail.login(email_user, email_pass)
mail.select('inbox')
status, response = mail.uid('search', None, r'(X-GM-RAW "subject:\"your latest mail subject\"")')
response = response[0].decode('utf-8').split()
response.reverse()
response = response[:min(10, len(response))]
print (response)

Reddit API and voting. Not accepting modhash/cookie. .error.USER_REQUIRED

I'm trying to get the voting API working, but I get the error .error.USER_REQUIRED. Can't figure out why, but I assume I must either be sending the modhash or the session cookie the wrong way, as the login goes trough fine
My code looks something like this:
UP = {'user': username, 'passwd': password, 'api_type': 'json',}
client = requests.session()
r = client.post('http://www.reddit.com/api/login', data=UP)
j = json.loads(r.text)
mymodhash = j['json']['data']['modhash']
url = 'http://www.reddit.com/api/vote/.json'
postdata = {'id': thing, 'dir': newdir, 'uh': mymodhash}
vote = client.post(url, data=json.dumps(newdata))
Error:
{"jquery": [[0, 1, "refresh", []], [0, 2, "attr", "find"], [2, 3, "call", [".error.USER_REQUIRED"]], [3, 4, "attr", "show"], [4, 5, "call", []], [5, 6, "attr", "text"], [6, 7, "call", ["please login to do that"]], [7, 8, "attr", "end"], [8, 9, "call", []]]}
To login you should post to ssl.reddit.com so that you are not posting your credentials in plain-text. Also, you should set a User-Agent.
The below is a working example to vote on your /r/redditdev submission.
import requests
# Login
client = requests.session(headers={'User-Agent': 'Requests test'})
data = {'user': 'USERNAME', 'passwd': 'PASSWORD', 'api_type': 'json'}
r = client.post('https://ssl.reddit.com/api/login', data=data)
modhash = r.json['json']['data']['modhash']
# Vote
data = {'id': 't3_11mr32', 'dir': '1', 'uh': modhash, 'api_type': 'json'}
r = client.post('http://www.reddit.com/api/vote', data=data)
print r.status_code # Should be 200
print r.json # Should be {}
Also, unless you are really interested in how reddit's API works under the covers, I suggest you use PRAW.
You can use session object with with statement.
import requests
UP = {'user': username, 'passwd': password, 'api_type': 'json'}
url_prefix = "http://www.reddit.com"
with requests.session() as client:
client.post(url_prefix + '/login', data=UP)
<...something else what you want...>

Categories

Resources