Skip to content

Commit 5625d13

Browse files
committed
Add use case for generation of Plain Text Content from HTML
Resolves #354
1 parent 33a3576 commit 5625d13

File tree

2 files changed

+59
-0
lines changed

2 files changed

+59
-0
lines changed

use_cases/README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ This directory provides examples for specific use cases of this library. Please
1414
### Working with Mail
1515
* [Asynchronous Mail Send](asynchronous_mail_send.md)
1616
* [Attachment](attachment.md)
17+
* [Sending HTML-Only Content](sending_html_content.md)
1718
* [Transactional Templates](transational_templates.md)
1819

1920
### Library Features

use_cases/sending_html_content.md

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
# Sending HTML-only Content
2+
3+
4+
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.
5+
6+
## Using `beautifulsoup4`
7+
8+
```python
9+
import sendgrid
10+
import os
11+
from sendgrid.helpers.mail import Email, Content, Mail
12+
try:
13+
# Python 3
14+
import urllib.request as urllib
15+
except ImportError:
16+
# Python 2
17+
import urllib2 as urllib
18+
from bs4 import BeautifulSoup
19+
20+
html_text = """
21+
<html>
22+
<body>
23+
<p>
24+
Some
25+
<b>
26+
bad
27+
<i>
28+
HTML
29+
</i>
30+
</b>
31+
</p>
32+
</body>
33+
</html>
34+
"""
35+
36+
sg = sendgrid.SendGridAPIClient(apikey=os.environ.get('SENDGRID_API_KEY'))
37+
from_email = Email("test@exmaple.com")
38+
subject = "subject"
39+
to_emila = Email("to_email@example.com")
40+
html_content = Content("text/html", html_text)
41+
42+
mail = Mail(from_email, subject, to_email, html_content)
43+
44+
soup = BeautifulSoup(html_text)
45+
plain_text = soup.get_text()
46+
plain_content = Content("text/plain", plain_text)
47+
mail.add_content(plain_content)
48+
49+
try:
50+
response = sg.client.mail.send.post(request_body=mail.get())
51+
except urllib.HTTPError as e:
52+
print(e.read())
53+
exit()
54+
55+
print(response.status_code)
56+
print(response.body)
57+
print(response.headers)
58+
```

0 commit comments

Comments
 (0)