I create a custom module that should receive mail incoming mail. After configuring the Incoming Mail Servers I tested it with the creating ticket in helpdesk but when I use my module nothing happens not receiving log am don't something wrong
Thank you for the help
from odoo import api, fields, models, tools, _
import logging
_logger = logging.getLogger(__name__)
class TestMailer(models.Model):
_name = 'test.mailer'
_inherit = ['mail.alias.mixin','mail.thread', 'mail.activity.mixin']
_description = 'Sort Email'
name = fields.Char(string='Name')
email_from = fields.Char(string='email from')
email_cc = fields.Char(string='email cc')
mail_body = fields.Text(string='mail body')
partner_id = fields.Many2one('res.partner', 'Partner',required=True,select=True)
#api.model
def message_new(msg_dict, custom_values=None):
# def message_new(self, msg, custom_values=None):
_logger.warning('hi i am message_new')
I get this when I fetch now in Incoming Mail Servers.
odoo.addons.mail.models.mail_thread: Routing mail from "name" <name#email.com> to test_sort#email.net,"test_sort#email.net" <test_sort#email.net> with Message-Id <DBBPR08MB49043139E291E368A928E963EA0F9#DBBPR08MB4904.eurprd08.prod.outlook.com>: fallback to model:test.mailer, thread_id:None, custom_values:None, uid:2
what is read
Create a new record on Incoming Mails odoo
customize the auto lead creation through incoming emails
solution
#api.model
def message_new(self, msg, custom_values=None):
_logger.warning('hi i am message_new')
return super(TestMailer, self).message_new(msg_dict, custom_values=defaults)
i think you forgot super call in this method...
Related
I want to make a "Auto-Reply" on Facebook Messenger using python but I don't know how to do it
If it's possible, can you share the code?
If you use the fbchat library, you can do something like below (the example is from the docs, and just replies back with the same message)
from fbchat import log, Client
# Subclass fbchat.Client and override required methods
class EchoBot(Client):
def onMessage(self, author_id, message_object, thread_id, thread_type, **kwargs):
self.markAsDelivered(thread_id, message_object.uid)
self.markAsRead(thread_id)
log.info("{} from {} in {}".format(message_object, thread_id, thread_type.name))
# If you're not the author, echo
if author_id != self.uid:
self.send(message_object, thread_id=thread_id, thread_type=thread_type)
client = EchoBot("<email>", "<password>")
client.listen()
I have a task to create a REST API that will be responsible for handling messages. As a part of the functionality, I should be able to write a message. This message should contain the following fields:
id
sender
receiver
message itself
subject
creation date
So, as I expected to do this is to have a route that should handle the object that I will send as an argument. But I am not sure I can do so. What would you recommend in this case?
For now, I can handle it somehow like this:
#app.route('/new_message/<string:sender>/<string:receiver>/<string:message>/', methods=['POST'])
def get_message(sender, receiver, message):
sender = sender
receiver = receiver
message = message
# Code that will add the data or to the database or to the json file
# if I decide not to implement DB for this task
return 'Sent successfully'
Thanks for your advice!
I am suggesting you to use JSON request body instead of the path parameters for the POST method.
Here is the example,
from flask import request, Flask
app = Flask(__name__)
#app.route('/new_message', methods=['POST'])
def get_message():
payload = request.json()
sender = payload['sender']
receiver = payload['receiver']
message = payload['message']
return 'Sent successfully'
if __name__ == "__main__":
app.run()
Now, If you want to add message as object then you can add it in JSON body. Not only message object you can add any number of fields if required.
This is my sender view from where i create envelope as draft and open it in edit sender view and send it but recipients are not getting emails
#app.route('/sender', methods = ['POST'])
def sender1():
if request.method == 'POST':
name = request.form['name']
email = request.form['email']
filename1 = pdf2.save(request.files['file'])
subject = request.form['subject']
body = request.form['body']
path1 = pdf2.path(filename1)
url1 = pdf2.url(filename1)
remoteFile1 = urllib.request.urlopen(url1).read()
login_information = client.login_information()
signers = [
models.Signer(
email=email,
name=name,
recipientId=1,
clientUserId=str(uuid.uuid4()), # Something unique in your database.
emailSubject=subject,
emailBody=body,
supportedLanguage='en')]
session['email']=email
session['name']=name
session['subject']=subject
session['body']=body
with open(path1, 'rb') as pdf:
envelope = models.Envelope(
documents=[
models.Document(
name='document.pdf',
documentId=1,
data=pdf,
)
],
emailSubject=subject,
emailBlurb='request for signing',
status=models.Envelope.STATUS_CREATED,
recipients=signers,
)
client.create_envelope_from_documents(envelope)
url = client.sender_edit_view(envelope.envelopeId)
models.Envelope(status=models.Envelope.STATUS_SENT)
data=url['url']
#data = data.replace('send=1','send=0')
#print(data)
return redirect(data)
This is the sender edit view to call api
def sender_edit_view(self,envelopeId=''):
"""POST to {account}/envelopes/{envelopeId}/views/recipient.
This is the method to start embedded signing for recipient.
Return JSON from DocuSign response.
"""
authenticationMethod=None
returnUrl='http://127.0.0.1:5000/callback'
if not self.account_url:
self.login_information()
url = '/accounts/{accountId}/envelopes/{envelopeId}/views/correct' \
.format(accountId=self.account_id,envelopeId=envelopeId,
)
if authenticationMethod is None:
authenticationMethod = 'email'
data = {
'authenticationMethod': authenticationMethod,
'returnUrl': returnUrl,
}
return self.post(url, data=data, expected_status_code=201)
How can i send email to recipients using the api. i have tried using the create correct api also and tried to update recipients but emails are still not being sent.
The problem isn't the sender view, the problem is that the signer is being marked as an embedded signer (no email invite to the signing ceremony is sent).
Your recipients aren't receiving email invitations because you are setting the clientUserId attribute for them.
Setting clientUserId causes a number of effects:
The signer becomes an embedded signer.
An email invitation to a signing ceremony is not sent.
The signer will sign via an embedded signing ceremony after you create one for them.
The metadata of the value of the clientUserId setting is maintained with the signer for your app's purposes.
To solve the problem:
Don't set the clientUserId attribute
If you want to maintain metadata between the receipient record in DocuSign and your own app, use the recipient's customFields attribute.
(This doesn't apply in your use case since you're using a uuid. But it may apply to other readers of this answer.)
I am developing a Gmail extracting app and using Gmail API to fetch mail from server. the problem lies in the fact that fetch time for mails is too large even though I used threading in back end framework. now I am going to implement one feature which will suggest user opting for bulk download that "once your download is ready, we will mail you" but for that i want to run download.py mentioned below in app tree in background and once the fetch is over it will get terminated.
And in the very bottom of the code i want to mail user that their download is ready but its not working though i have defined the mail server in settings.py .
download.py
import httplib2, base64
from stripogram import html2text
from oauth2client.django_orm import Storage
from apiclient.discovery import build
from oauth2client import client
from django.contrib.auth.models import User
from .models import CredentialsModel
from django.conf import settings
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import authentication, permissions
from gextracto import models
from gextracto.models import UserData
from django.core.mail import EmailMessage
from django.core import mail
connection = mail.get_connection()
class ListMails(APIView):
"""
Gets a list of a specified number mail ids for a particular label
Extracts the email in the form of plain/text
The API returns all the extracted mails
"""
authentication_classes = (authentication.SessionAuthentication,)
permission_classes = (permissions.IsAuthenticated,)
def extract_headers(self, message):
"""
Extract the headers for a single mail and returns it
{To, From, Subject}
"""
needed_fields = ('From', 'To', 'Subject')
return {i['name']:i['value'] for i in message['payload']['headers'] if i['name'] in needed_fields}
def get_message_body(self, message):
"""
Get the body of an email
Recursively look for the body for different mimetypes
Returns the body as text/plain
"""
if 'payload' in message:
return self.get_message_body(message['payload'])
elif 'parts' in message:
return self.get_message_body(message['parts'][0])
else:
data = base64.urlsafe_b64decode(message['body']['data'].encode('ASCII'))
markdown_data = html2text(data)#.decode('utf-8', "replace")
data = data.replace("\n", "<br/>")
# return {markdown, html}
return {'markdown':unicode( markdown_data,"ISO-8859-1"), 'html':unicode(data,"ISO-8859-1")} if markdown_data else {'html':unicode(data,"ISO-8859-1")}
def message_content_html(self, userId, message_id, service):
"""
Make queries to get the content for a mail given its message id
Returns all the content
"""
content = {'id':message_id}
# try
message = service.users().messages().get(userId=userId, id=message_id).execute()
mimetype = message['payload']['mimeType']
if mimetype == 'text/html':
return {}
#
else:
body = self.get_message_body(message)
if body == "":
body = "<empty message>"
headers = self.extract_headers(message)
content['body'] = body
content.update(headers)
return content
def collect_mails(self, user, messages, service):
"""
Collect the content for all the mails currently downloaded
"""
all_messages = []
try:
for message in messages:
content = self.message_content_html(user.username, message['id'], service)
if content:
all_messages.append(content)
return all_messages
# return empty list if no messages were downloaded
except KeyError:
return []
def get(self, request, format=None):
"""
Handles the GET request to get all the mails for a label
Paginages through the GAPI content if required
API returns all the messages
{To, From, Subject, body}
"""
user = request.user
storage = Storage(CredentialsModel, 'id', user, 'credential')
credentials = storage.get()
http_auth = credentials.authorize(httplib2.Http())
service = build('gmail', 'v1', http=http_auth)
user_Id = user.username
label_id = request.GET['label']
# try
# call Google API with a request to get a list of all the labels
response = service.users().messages().list(userId=user_Id, labelIds=label_id, maxResults=100).execute()
all_messages = self.collect_mails(user, response['messages'], service)
if not all_messages:
return Response([])
else:
if 'nextPageToken' in response:
page_token_flag = True
# request more more mails if the download limit has not yet been satisfied
while(page_token_flag):
response = service.users().messages().list(userId=user_Id, pageToken=response['nextPageToken'], maxResults=100).execute()
all_messages.append(self.collect_mails(user, response['messages'], service))
print(all_messages)
#for x in range(0,len(all_messages)):
#b=all_messages[10]
#instance= UserData(user_id=user ,label=label_id, sender = b['From'] , subject=b['Subject'] , body=b['body'])
#instance.save()
page_token_flag = 'nextPageToken' in response
##
for x in range(0,len(all_messages)):
b=all_messages[10]
instance= UserData(user_id=user ,label=label_id, sender = b['From'] , subject=b['Subject'] , body=b['body'])
instance.save()
print ("Hi i am here!!!")
email = EmailMessage('Your Download Ready!', 'http://127.0.0.1:8000/admin/gextracto/userdata/', to=[user], connection=connection)
email.send()
connection.close()
return Response(all_messages)
Please tell me the way to run it in background. if need any other info please do ask. Thanks
Don't know the exact requirements but I'll think about Celery to run background tasks. This approach allows to manage all post-script activities in native Django manner.
Also you can think about running the Django script using cron (as manage.py command) - but it can lead to some limitations.
What about sending emails failure - believe, you don't need to close connection after sending email. Usually I use send_mail()/send_mass_mail() functions - please, check their code to get an idea.
I'm trying to save both messages that get sent out and received in a database, including message sid, message body, so that I can process them using some logic.
class OutgoingMessage(models.Model):
''' Table of SMS messages that are sent out to users by Twilio '''
outgoing_sid = models.CharField(max_length=40)
sent_date = models.DateTimeField()
sender = models.ForeignKey(TwilioNumber, related_name='outgoing_messages')
recipient = models.ForeignKey(Caller, related_name='outgoing_messages')
message_body = models.TextField(max_length=1600)
class IncomingMessage(models.Model):
''' Table of SMS messages received by Twilio from users '''
incoming_sid = models.CharField(max_length=40)
sent_date = models.DateTimeField()
sender = models.ForeignKey(Caller, related_name='incoming_messages')
recipient = models.ForeignKey(TwilioNumber, related_name='incoming_messages')
message_body = models.TextField(max_length=1600)
Is there a straightforward way of getting the message sid from a message Twilio sends out, immediately after it gets sent? Getting the sid from an incoming message is pretty easy but the other way around is not very clear.
I'm trying to look for an alternative to using cookies, as suggested in this post
I found the answer here
# Download the Python helper library from twilio.com/docs/python/install
from twilio.rest import TwilioRestClient
# Your Account Sid and Auth Token from twilio.com/user/account
account_sid = "AC1ab0bb368322688c3d6cbb1355aeef9b"
auth_token = "{{ auth_token }}"
client = TwilioRestClient(account_sid, auth_token)
message = client.messages.create(body="Jenny please?! I love you <3",
to="+15558675309",
from_="+14158141829",
media_url="http://www.example.com/hearts.png")
print message.sid
However, this doesn't seem to work very well with django_twilio views.