-
Notifications
You must be signed in to change notification settings - Fork 714
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #665 from cmccandless/issue-354
Add use case for generation of Plain Text Content from HTML
- Loading branch information
Showing
2 changed files
with
59 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | ||
``` |