I want to setup email signature for each user in the domain. The thing is I already have a html signature ready but I dont know how to use html signature with GMAIl API. I am using python and when I try to do that, it only converts it to text. Is there any way to embed html signature in a variable which then inserts into the gmail account using GMAIl API?
I recommend checking the documentation Managing signatures
primary_alias = None
aliases = gmail_service.users().settings().sendAs().\
list(userId='me').execute()
for alias in aliases.get('sendAs'):
if alias.get('isPrimary'):
primary_alias = alias
break
sendAsConfiguration = {
'signature': 'I heart cats'
}
result = gmail_service.users().settings().sendAs().\
patch(userId='me',
sendAsEmail=primary_alias.get('sendAsEmail'),
body=sendAsConfiguration).execute()
print 'Updated signature for: %s' % result.get('displayName')
The documentation states it should be HTML
Thanks for the reply. I found the solution to use html signatures. What I did is created html files using python script (You can also create them in any other way. I just did using python because I wanted a single script to create a html signature as well as change the email signature for the user).
And then imported whole html as text inside a python variable as shown below.
file = open(test.html, 'r')
htmlfile = file.read()
ESignature = {'signature': htmlfile}
After that in the email signature body parameter I just used the variable where I stored the html signature and it worked.
sig = service.users().settings().sendAs().update(userId='me', sendAsEmail="test#example.org", body=ESignature).execute()
Related
I am a beginner to the Django framework and I am building a Django app that uses the Slack RTM API.
I have a coded a program in python that performs the OAuth authentication process like so :
def initialize():
url="https://slack.com/api/rtm.connect"
payload={"token":"xxx"}
r=requests.post(url,payload)
res=json.loads(r.text)
url1=res['url']
ws = create_connection(url1)
return ws
My Requirement:
The stream of events I receive (from my slack channel that my slack app is added to) is processed to filter out events of the type - message ,then match the message with a regex pattern and then store the matched string in a database.
As a stand alone python program I am receiving the stream of events from my channel.
My questions:
How do I successfully integrate this code to Django so that I can
fulfill my requirement?
Do I put the code in templates/views? What is the
recommended method to process this stream of data?
def initialize():
url = "https://slack.com/api/rtm.connect"
r = requests.get(url, params={'token': '<YOUR TOKEN>'})
res = r.json()
url1=res['url']
ws = create_connection(url1) #Note: There is no function called create_connnection() so it will raise an error
return ws
if you read the API web methods, you see :
Preferred HTTP method: GET
See here: Slack rtm.connect method
look at the comment, and thats the right code, see the differences between this code and yours.
basically to get JSON from a request don't use json.loads because this search your local computer not the request
use r.json() so it call the json you got from r.
Note that r.text will return raw text output so when you want to get url it will not be identified, with r.json you can call the object url as stated about
Hope this help.
and please could you tell us more what you wanna do with this in view ? because template is a directory which contains all the HTML files which you don't need to work with.
but why views.py ?
I have a Django project where I am working on an email client. I've decided to use python's IMAPClient instead of standard library's imaplib for getting access to the messages. Currently, I don't make use of python's email package to encode/decode responses received from IMAPClient, and I have a feeling that I manually implement things that should be handled by email.
Example code for downloading attachment:
def download_attachment(server, msgid, index, encoding):
# index and encoding is known from previous analysis of bodystructure
file_content = f_fetch(server, msgid, index)
# the below code should be handled by email's message_from_bytes
# and subsequent get_payload(decode = True) function
if encoding == 'base64':
file_content = base64.b64decode(file_content)
elif ...
...
endif
#writing file_content to a folder
return
def f_fetch(server, msgid, index):
if not index:
index = '1'
response = server.fetch(msgid, 'BODY[' + index + ']')
key = ('BODY[' + index + ']').encode('utf-8')
if type(msgid) is str:
msgid = int(msgid)
return response[msgid][key]
So the question is, how should I rewrite this code to make use of email.
Specifically, what should I do with the response from IMAPClient to pass it to email's message_from_bytes() function?
If you wish to parse an email using the email package's message_from_bytes() function then you need to give it the entire, raw email body. To get this, fetch using the RFC822 selector like this:
fetch_data = server.fetch(msgid, ['RFC822'])
parsed = email.message_from_bytes(fetch_data[msgid][b'RFC822'])
If you're pulling individual message parts/attachments from the IMAP server, then the server is effectively doing the parsing work for you and you don't need to use the email package's parser.
I have a working app using the imgur API with python.
from imgurpython import ImgurClient
client_id = '5b786edf274c63c'
client_secret = 'e44e529f76cb43769d7dc15eb47d45fc3836ff2f'
client = ImgurClient(client_id, client_secret)
items = client.subreddit_gallery('rarepuppers')
for item in items:
print(item.link)
It outputs a set of imgur links. I want to display all those pictures on a webpage.
Does anyone know how I can integrate python to do that in an HTML page?
OK, I haven't tested this, but it should work. The HTML is really basic (but you never mentioned anything about formatting) so give this a shot:
from imgurpython import ImgurClient
client_id = '5b786edf274c63c'
client_secret = 'e44e529f76cb43769d7dc15eb47d45fc3836ff2f'
client = ImgurClient(client_id, client_secret)
items = client.subreddit_gallery('rarepuppers')
htmloutput = open('somename.html', 'w')
htmloutput.write("[html headers here]")
htmloutput.write("<body>")
for item in items:
print(item.link)
htmloutput.write('SOME DESCRIPTION<br>')
htmloutput.write("</body</html>")
htmloutput.close
You can remove the print(item.link) statement in the code above - it's there to give you some comfort that stuff is happening.
I've made a few assumptions:
The item.link returns a string with only the unformatted link. If it's already in html format, then remove the HTML around item.link in the example above.
You know how to add an HTML header. Let me know if you do not.
This script will create the html file in the folder it's run from. This is probably not the greatest of ideas. So adjust the path of the created file appropriately.
Once again, though, if that is a real client secret, you probably want to change it ASAP.
I'm trying to read facebook conversations of a page using a python script. With this code
import facebook
at = "page access token"
pid = "page id"
api = facebook.GraphAPI( at )
p = api.get_object( 'me/conversations')
print p
I get a dictionary containing the following
{'paging': {'next': 'https://graph.facebook.com/v2.5/1745249635693902/conversations?access_token=<my_access_token>&limit=25&until=1454344040&__paging_token=<my_access_token>', 'previous': 'https://graph.facebook.com/v2.5/1745249635693902/conversations?access_token=<my_access_token>&limit=25&since=1454344040&__paging_token=<my_access_token>'}, 'data': [{'link': '/Python-1745249635693902/manager/messages/?mercurythreadid=user%3A100000386799941&threadid=mid.1454344039847%3A2e3ac25e0302042916&folder=inbox', 'id': 't_mid.1454344039847:2e3ac25e0302042916', 'updated_time': '2016-02-01T16:27:20+0000'}]}
What are those fields? How can I get the text of the message?
Edit: I tried asking for the "messages" field by adding
msg = api.get_object( p['data'][0]['id']+'/messages')
print msg
but it just returns the same fields. I've searched in the API docs for a while, but I didn't find anything helpful. Is it even possible to read the message content of a facebook page's conversation using python?
I managed to find the answer myself; the question was not well posed and did not match what I was exactly looking for.
I wanted to get the content of the messages of facebook conversations of a page. Following the facebook graph API documentation, this can be achieved by asking for the conversations ({page-id}/conversations), then the messages in said conversations ({conversation-id}/messages, https://developers.facebook.com/docs/graph-api/reference/v2.5/conversation/messages), and finally asking for the message itself should return a dict with all the fields, content included (/{message-id}, https://developers.facebook.com/docs/graph-api/reference/v2.5/message).
At least this is how I believed it should have been; however the last request returned only the fields 'created_time' and 'id'.
What I was really trying to ask was a way to fetch the 'message' (content) field. I was assuming the function graph.get_object() from the official python facebook sdk should have returned all the fields in any case, since it has only one documented argument (http://facebook-sdk.readthedocs.org/en/latest/api.html) - the graph path for the requested object, and adding additional field request is not allowed.
The answer I was looking for was in this other question, Request fields in Python Facebook SDK.
Apparently, it's possible to ask for specific fields ( that are not returned otherwise ) by passing an **args dict with such fields along with the path requested.
In a GET request to the Facebook graph that would be the equivalent of adding
?fields=<requested fieds>
to the object path.
This is the working code:
#!/usr/bin/env python
import facebook
at = <my access token>
pid = <my page id>
api = facebook.GraphAPI( at )
args = {'fields' : 'message'} #requested fields
conv = api.get_object( 'me/conversations')
msg = api.get_object( conv['data'][0]['id']+'/messages')
for el in msg['data']:
content = api.get_object( el['id'], **args) #adding the field request
print content
I am working on a django web application. I want to enable my app to send emails through gmail (I can use either an app-wide google account or the logged-in users one).
I know already that I can create a hyperlink which opens up gmail's compose window. I also know that I can prepopulate all the fields (to, cc, bcc, body) with values I want but there seem to be limits which are unacceptable for me: My application requires the email's body to be generated on a per-case basis. This message has to include hyperlinks, tables and be an HTML enabled text in general.
Question: How can I open a compose email page in gmail with the message body prefilled with custom HTML text?
There is also Prefilling gmail compose screen with HTML text but doesn't seem to answer my question.
You want to construct a string like this:
var myMailTo = function constructMailTo() {
var newLine = "%0D%0A";
var emailRecipient = encodeURI('example#example.com');
var subjectTitle = encodeURI('Urgent: this email is so urgent!');
var bodyContent = newLine + newLine + newLine + encodeURI('This mail was generated by me.')
return "mailto:" + emailRecipient + '?subject=' + subjectTitle + '&body=' + bodyContent;
}
Send us mail
Remember that the string needs to be encoded. This example is just pseudocode.
The compiled example looks like this:
Send us feedback