Making a program that sends an email which hyperlinks text in django - python

confirm_links = 'To confirm this order http://mywebsite.com '
deny_links = '\nTo deny this order http://mywebsite.com
email=EmailMessage('title_text', confirm_links+deny_links, to=['youremail#gmail.com'])
email.send()
signals.post_save.connect(send_email_on_new_order, sender= PurchaseOrder, dispatch_uid = 'send_email_on_new_order')
My program sends a link to the user where they can click those two links to either confirm or deny their order. I would like to make it to where, they don't see the line http://mywebsite.com and instead just see "order" hyperlinked which goes to http://mywebsite.com

Quote from docs:
By default, the MIME type of the body parameter in an EmailMessage is
"text/plain"
Put your links in <a> tags and set email.content_subtype = "html":
confirm_links = 'To confirm this order'
deny_links = '\nTo deny this order'
email=EmailMessage('title_text', confirm_links+deny_links, to=['youremail#gmail.com'])
email.content_subtype = "html"
email.send()
Though, it's a good practice to send both text and HTML versions of a message. Consider using EmailMultiAlternatives for that.

If you just want to make a classic link, you just have to use the HTML <a> tag. Also if you want to point to a particular URL, you can use the reverse() function (see the documentation about URL)
Also set email.content_subtype = "html"

Related

How to change email signature using GMAIL API?

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()

Parsing out body and tables from emails

I currently am getting the body/content of the emails in Python using the following:
import email
message = email.message_from_file(open(file))
messages = [part.get_payload() for part in message.walk() if part.get_content_type() == 'text/plain']
This seems to work well in most cases, but I noticed that sometimes there are html tables that don't get picked up. It starts with
<html>
<style type='text/css">
Would it just be to add or part.get_content_tye() == 'text/css'?
If I had to guess, I would guess that you need to add 'text/html'.
However, you should be able to figure out what content-type is in the email by examining the content of that variable.
import email
message = email.message_from_file(open(file))
# Remove the content-type filter completely
messages = [(part.get_payload(), part.get_content_type()) for part in message.walk()]
# print the whole thing out so that you can see what content-types are in there.
print(message)
This will help you see what content types are in there and you can then filter the ones that you need.

Read facebook messages using python sdk

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

Adding headers to Django EmailMultiAlternatives

In Django EmailMultiAlternatives documentation there is nothing about how to add headers like "format" or "Reply-To" in EmailMultiAlternatives. It took a while for me to figure it out and I am sending this post to help others with saving their time.
As you can see in django's source code, EmailMultiAlternatives inherits from EmailMessage, so they take the same parameters in the init constructor. This way, we can add headers like:
msg = EmailMultiAlternatives(
subject, message, from_email, to_list,
headers={'Reply-To': "email#example.com", 'format': 'flowed'}
)
Back in 2015 OP complained, that there were no instructions in documentation, how to add headers such as "Format" and "Reply-To" in Django mail (django.core.mail) module. However today, while using same documentation link. We can find description and examples in 2018 easily:
class EmailMessage[source]
The EmailMessage class is initialized with the following parameters
(in the given order, if positional arguments are used). All parameters
are optional and can be set at any time prior to calling the send()
method.
subject: The subject line of the email.
body: The body text. This should be a plain text message.
from_email: The sender’s address. Both fred#example.com and Fred <fred#example.com> forms are legal. If omitted, the DEFAULT_FROM_EMAIL
setting is used.
to: A list or tuple of recipient addresses.
bcc: A list or tuple of addresses used in the “Bcc” header when sending the email.
connection: An email backend instance. Use this parameter if you want to use the same connection for multiple messages. If omitted, a
new connection is created when send() is called.
attachments: A list of attachments to put on the message. These can be either email.MIMEBase.MIMEBase instances, or (filename, content, mimetype) triples.
headers: A dictionary of extra headers to put on the message. The keys are the header name, values are the header values. It’s up to the
caller to ensure header names and values are in the correct format for
an email message. The corresponding attribute is extra_headers.
cc: A list or tuple of recipient addresses used in the “Cc” header when sending the email.
For example:
email = EmailMessage('Hello', 'Body goes here', 'from#example.com',
['to1#example.com', 'to2#example.com'], ['bcc#example.com'],
headers = {'Reply-To': 'another#example.com', 'format': 'flowed'})
As we see from examples, EmailMessage has headers argument (dictionary) too, EmailMultiAlternatives according to docstring in source code is:
A version of EmailMessage that makes it easy to send multipart/alternative
messages. For example, including text and HTML versions of the text is
made easier.
So if you don't need something specific, EmailMessage is fine, because currently EmailMultiAlternatives is for easy inclusion of text and HTML versions of text.

compose email with prefilled html body in gmail

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

Categories