compose email with prefilled html body in gmail - python

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

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

Is it possible to output the recipient email in a twilio verify email?

I have set up my react app to grab the data from the URL in the format
http://localhost:3000/confirm-email/email#example.com?code=469907
Is it possible to output the recipient's email in the sendgrid template.
The docs only show how to do this with only the code but it doesn't allow users to verify from another device like their phone without having to re-enter their email address.
It's not the biggest issue as I can check if the email parameter exists in the URL and add an input field if it does not have it from local storage but once again users would not be able to verify from a separate device.
I have figured it out after checking out the
https://www.twilio.com/code-exchange/one-click-email-verification-magic-links
Documentation. Although this solution was only in javascript and my backend is python/Django rest framework.
The only thing you need to do is set substitutions in JSON format in the client_configuration
def verifications(user_destination, via):
return client.verify \
.services(settings.TWILIO_VERIFICATION_SID) \
.verifications \
.create(
to=user_destination,
channel=via,
channel_configuration={
'substitutions': {
'email': user_destination
}
}
)
You can make any substitution into the sendgrid templates this way.
Here is a code example in flask
https://github.com/digitaluniverse/digitaluniverse-magic_link_elasticBeanstalk

Using Python and gmail API, how can I send messages with multiple attachements?

Looking to create and send messages with multiple files attached. Per the online gmail api documentation, there is a function for building messages with an attachment but no documentation for howto use it to create a message with multiple attachments.
Can I use the gmail API to send messages with multiple attachments programmatically? How might one do this?
With this function, you can send to one or multiple recipient emails, and also you can attach zero, one or more files. Coding improvement recommendations are welcome, however the way it is now, it works.
Python v3.7
smtplib from https://github.com/python/cpython/blob/3.7/Lib/smtplib.py (download the code and create the smtplib.py on your project folder)
def send_email(se_from, se_pwd, se_to, se_subject, se_plain_text='', se_html_text='', se_attachments=[]):
""" Send an email with the specifications in parameters
The following youtube channel helped me a lot to build this function:
https://www.youtube.com/watch?v=JRCJ6RtE3xU
How to Send Emails Using Python - Plain Text, Adding Attachments, HTML Emails, and More
Corey Schafer youtube channel
Input:
se_from : email address that will send the email
se_pwd : password for authentication (uses SMTP.SSL for authentication)
se_to : destination email. For various emails, use ['email1#example.com', 'email2#example.com']
se_subject : email subject line
se_plain_text : body text in plain format, in case html is not supported
se_html_text : body text in html format
se_attachments : list of attachments. For various attachments, use ['path1\file1.ext1', 'path2\file2.ext2', 'path3\file3.ext3']. Follow your OS guidelines for directory paths. Empty list ([]) if no attachments
Returns
-------
se_error_code : returns True if email was successful (still need to incorporate exception handling routines)
"""
import smtplib
from email.message import EmailMessage
# Join email parts following smtp structure
msg = EmailMessage()
msg['From'] = se_from
msg['To'] = se_to
msg['Subject'] = se_subject
msg.set_content(se_plain_text)
# Adds the html text only if there is one
if se_html_text != '':
msg.add_alternative("""{}""".format(se_html_text), subtype='html')
# Checks if there are files to be sent in the email
if len(se_attachments) > 0:
# Goes through every file in files list
for file in se_attachments:
with open(file, 'rb') as f:
file_data = f.read()
file_name = f.name
# Attaches the file to the message. Leaves google to detect the application to open it
msg.add_attachment(file_data, maintype='application', subtype='octet-stream', filename=file_name)
# Sends the email that has been built
with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp:
smtp.login(se_from, se_pwd)
smtp.send_message(msg)
return True
Don't forget to activate less secure apps on your google account (https://myaccount.google.com/lesssecureapps) for this code to work.
Hope this helps

Gmail displays both HTML and text and HTML parts of email

I am sending an email to a gmail account using Python. This is the code I'm using
msg = email.mime.multipart.MIMEMultipart()
msg['From'] = 'myemail#gmail.com'
msg['To'] = 'toemail#gmail.com'
msg['Subject'] = 'HTML test'
msg_html = email.mime.text.MIMEText('<html><head></head><body><b>This is HTML</b></body></html>', 'html')
msg_txt = email.mime.text.MIMEText('This is text','plain')
msg.attach(msg_html)
msg.attach(msg_txt)
#SNIP SMTP connection code
smtpConn.sendmail('myemail#gmail.com', 'toemail#gmail.com', msg.as_string())
When I view this email in gmail both the HTML and text version are shown like this:
This is HTML
This is text
It should be either displaying text or html, what causes this behavior.
The message is being sent as multipart/mixed (as this is the default) when it needs to be sent as multipart/alternative. mixed means that each part contains different content and all should be displayed, while alternative means that all parts have the same content in different formats and only one should be displayed.
msg = email.mime.multipart.MIMEMultipart("alternative")
Additionally, you should put the parts in increasing order of preference, i.e., text before HTML. The MUA (GMail in this case) will render the last part it knows how to display.
See the Wikipedia article on MIME for a good introduction to formatting MIME messages.

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

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"

Categories