Skip to content

Commit

Permalink
Merge pull request #665 from cmccandless/issue-354
Browse files Browse the repository at this point in the history
Add use case for generation of Plain Text Content from HTML
  • Loading branch information
thinkingserious authored Dec 7, 2018
2 parents 284ebaa + 1819e60 commit 0282aab
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 0 deletions.
1 change: 1 addition & 0 deletions use_cases/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ This directory provides examples for specific use cases of this library. Please
### Working with Mail
* [Asynchronous Mail Send](asynchronous_mail_send.md)
* [Attachment](attachment.md)
* [Sending HTML-Only Content](sending_html_content.md)
* [Transactional Templates](transational_templates.md)

### Library Features
Expand Down
58 changes: 58 additions & 0 deletions use_cases/sending_html_content.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
# Sending HTML-only Content


Currently, we require both HTML and Plain Text content for improved deliverability. In some cases, only HTML may be available. The below example shows how to obtain the Plain Text equivalent of the HTML content.

## Using `beautifulsoup4`

```python
import sendgrid
import os
from sendgrid.helpers.mail import Email, Content, Mail
try:
# Python 3
import urllib.request as urllib
except ImportError:
# Python 2
import urllib2 as urllib
from bs4 import BeautifulSoup

html_text = """
<html>
<body>
<p>
Some
<b>
bad
<i>
HTML
</i>
</b>
</p>
</body>
</html>
"""

sg = sendgrid.SendGridAPIClient(apikey=os.environ.get('SENDGRID_API_KEY'))
from_email = Email("[email protected]")
subject = "subject"
to_emila = Email("[email protected]")
html_content = Content("text/html", html_text)

mail = Mail(from_email, subject, to_email, html_content)

soup = BeautifulSoup(html_text)
plain_text = soup.get_text()
plain_content = Content("text/plain", plain_text)
mail.add_content(plain_content)

try:
response = sg.client.mail.send.post(request_body=mail.get())
except urllib.HTTPError as e:
print(e.read())
exit()

print(response.status_code)
print(response.body)
print(response.headers)
```

0 comments on commit 0282aab

Please sign in to comment.