Skip to content

Commit

Permalink
Merge pull request #275 from ittus/master
Browse files Browse the repository at this point in the history
Add 'Sending email with attachment' Use Case
  • Loading branch information
thinkingserious authored Mar 23, 2017
2 parents 20f53cf + 5037f6a commit 9086caf
Showing 1 changed file with 48 additions and 0 deletions.
48 changes: 48 additions & 0 deletions USE_CASES.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ This documentation provides examples for specific use cases. Please [open an iss
# Table of Contents

* [Transactional Templates](#transactional_templates)
* [Attachment](#attachment)

<a name="transactional_templates"></a>
# Transactional Templates
Expand Down Expand Up @@ -121,3 +122,50 @@ print(response.status_code)
print(response.body)
print(response.headers)
```

<a name="attachment"></a>
# Attachment

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

sg = sendgrid.SendGridAPIClient(apikey=os.environ.get('SENDGRID_API_KEY'))
from_email = Email("test@example.com")
subject = "subject"
to_email = Email("to_email@example.com")
content = Content("text/html", "I'm a content example")

file_path = "file_path.pdf"
with open(file_path,'rb') as f:
data = f.read()
f.close()
encoded = base64.b64encode(data).decode()

attachment = Attachment()
attachment.set_content(encoded)
attachment.set_type("application/pdf")
attachment.set_filename("test.pdf")
attachment.set_disposition("attachment")
attachment.set_content_id("Example Content ID")

mail = Mail(from_email, subject, to_email, content)
mail.add_attachment(attachment)
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 9086caf

Please sign in to comment.