Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add use case for generation of Plain Text Content from HTML #665

Merged
merged 1 commit into from
Dec 7, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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("test@exmaple.com")
subject = "subject"
to_emila = Email("to_email@example.com")
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)
```