Skip to content

Commit

Permalink
upgraded SendGrid API support
Browse files Browse the repository at this point in the history
always forget the version number
  • Loading branch information
frankV committed Jan 14, 2018
1 parent f1eca89 commit 64b824c
Show file tree
Hide file tree
Showing 5 changed files with 65 additions and 66 deletions.
1 change: 0 additions & 1 deletion .travis.yml
Expand Up @@ -9,7 +9,6 @@ cache:
- pip
install:
- pip install -r requirements-test.txt -e .
- pip install coveralls
script: python setup.py test
after_success:
- coveralls
Expand Down
43 changes: 22 additions & 21 deletions flask_sendgrid.py
Expand Up @@ -9,6 +9,10 @@
from sendgrid.helpers.mail import Email, Content, Personalization


__version__ = '0.6'
__versionfull__ = __version__


class SendGrid(SGMail):
app = None
api_key = None
Expand All @@ -21,36 +25,36 @@ def __init__(self, app=None, **opts):
super(SGMail, self).__init__()
self.from_email = None
self.subject = None
self.personalizations = None
self.contents = None
self.attachments = None
self.template_id = None
self.sections = None
self.headers = None
self.categories = None
self.custom_args = None
self.send_at = None
self.batch_id = None
self.asm = None
self.ip_pool_name = None
self.mail_settings = None
self.tracking_settings = None
self.reply_to = None
self._personalizations = None
self._contents = None
self._attachments = None
self._template_id = None
self._sections = None
self._headers = None
self._categories = None
self._custom_args = None
self._send_at = None
self._batch_id = None
self._asm = None
self._ip_pool_name = None
self._mail_settings = None
self._tracking_settings = None
self._reply_to = None

def init_app(self, app):
self.app = app
self.api_key = app.config['SENDGRID_API_KEY']
self.default_from = app.config['SENDGRID_DEFAULT_FROM']
self.client = SendGridAPIClient(apikey=self.api_key).client

def send_email(self, to_email, subject, from_email=None, html=None, text=None, *args, **kwargs):
def send_email(self, to_email, subject, from_email=None, html=None, text=None, *args, **kwargs): # noqa
if not any([from_email, self.default_from]):
raise ValueError("Missing from email and no default.")
if not any([html, text]):
raise ValueError("Missing html or text.")

self.set_from(Email(from_email or self.default_from))
self.set_subject(subject)
self.from_email = Email(from_email or self.default_from)
self.subject = subject

personalization = Personalization()

Expand All @@ -76,6 +80,3 @@ def _extract_emails(self, emails):
elif type(emails[0]) is dict:
for email in emails:
yield Email(email['email'])

__version__ = '0.5.2'
__versionfull__ = __version__
2 changes: 2 additions & 0 deletions requirements-test.txt
@@ -1,3 +1,4 @@
flask
pyflakes==1.2.3
pytest==2.9.2
pytest-cache==1.0
Expand All @@ -7,3 +8,4 @@ pytest-pep8==1.0.6
pep8==1.7.0
coverage==4.2
mock==2.0.0
coveralls
4 changes: 1 addition & 3 deletions setup.py
Expand Up @@ -88,9 +88,7 @@ def run_tests(self):
py_modules=['flask_sendgrid'],
zip_safe=False,
platforms='any',
install_requires=[
'Flask',
'SendGrid'],
install_requires=['SendGrid'],
tests_require=get_requirements('-test'),
cmdclass={'test': PyTest},
classifiers=[
Expand Down
81 changes: 40 additions & 41 deletions tests/test_extension.py
Expand Up @@ -56,7 +56,7 @@ def test_mandrill_compat_email_send(self, mock_client):
html='<h2>html</h2>'
)

self.assertEqual(json.dumps(self.mail.get(), sort_keys=True), '{"content": [{"type": "text/html", "value": "<h2>html</h2>"}], "from": {"email": "from"}, "personalizations": [{"to": [{"email": "test@example.com"}]}], "subject": "Subject"}')
self.assertEqual(json.dumps(self.mail.get(), sort_keys=True), '{"content": [{"type": "text/html", "value": "<h2>html</h2>"}], "from": {"name": "from"}, "personalizations": [{"to": [{"email": "test@example.com"}]}], "subject": "Subject"}')

@patch('python_http_client.Client._make_request')
def test_mandrill_compat_single_recipient(self, mock_client):
Expand All @@ -70,7 +70,7 @@ def test_mandrill_compat_single_recipient(self, mock_client):
html='<h2>html</h2>'
)

self.assertEqual(json.dumps(self.mail.get(), sort_keys=True), '{"content": [{"type": "text/html", "value": "<h2>html</h2>"}], "from": {"email": "from"}, "personalizations": [{"to": [{"email": "test@example.com"}]}], "subject": "Subject"}')
self.assertEqual(json.dumps(self.mail.get(), sort_keys=True), '{"content": [{"type": "text/html", "value": "<h2>html</h2>"}], "from": {"name": "from"}, "personalizations": [{"to": [{"email": "test@example.com"}]}], "subject": "Subject"}')

@patch('python_http_client.Client._make_request')
def test_mandrill_compat_multiple_recipient(self, mock_client):
Expand All @@ -84,7 +84,7 @@ def test_mandrill_compat_multiple_recipient(self, mock_client):
html='<h2>html</h2>'
)

self.assertEqual(json.dumps(self.mail.get(), sort_keys=True), '{"content": [{"type": "text/html", "value": "<h2>html</h2>"}], "from": {"email": "from"}, "personalizations": [{"to": [{"email": "test1@example.com"}, {"email": "test2@example.com"}]}], "subject": "Subject"}')
self.assertEqual(json.dumps(self.mail.get(), sort_keys=True), '{"content": [{"type": "text/html", "value": "<h2>html</h2>"}], "from": {"name": "from"}, "personalizations": [{"to": [{"email": "test1@example.com"}, {"email": "test2@example.com"}]}], "subject": "Subject"}')

@patch('python_http_client.Client._make_request')
def test_single_recipient_email_object(self, mock_client):
Expand All @@ -98,7 +98,7 @@ def test_single_recipient_email_object(self, mock_client):
html='<h2>html</h2>'
)

self.assertEqual(json.dumps(self.mail.get(), sort_keys=True), '{"content": [{"type": "text/html", "value": "<h2>html</h2>"}], "from": {"email": "from"}, "personalizations": [{"to": [{"email": "test1@example.com"}]}], "subject": "Subject"}')
self.assertEqual(json.dumps(self.mail.get(), sort_keys=True), '{"content": [{"type": "text/html", "value": "<h2>html</h2>"}], "from": {"name": "from"}, "personalizations": [{"to": [{"email": "test1@example.com"}]}], "subject": "Subject"}')

@patch('python_http_client.Client._make_request')
def test_multiple_recipient_email_object(self, mock_client):
Expand All @@ -112,7 +112,7 @@ def test_multiple_recipient_email_object(self, mock_client):
html='<h2>html</h2>'
)

self.assertEqual(json.dumps(self.mail.get(), sort_keys=True), '{"content": [{"type": "text/html", "value": "<h2>html</h2>"}], "from": {"email": "from"}, "personalizations": [{"to": [{"email": "test1@example.com"}, {"email": "test2@example.com"}]}], "subject": "Subject"}')
self.assertEqual(json.dumps(self.mail.get(), sort_keys=True), '{"content": [{"type": "text/html", "value": "<h2>html</h2>"}], "from": {"name": "from"}, "personalizations": [{"to": [{"email": "test1@example.com"}, {"email": "test2@example.com"}]}], "subject": "Subject"}')

@patch('python_http_client.Client._make_request')
def test_hello_email(self, mock_client):
Expand All @@ -124,9 +124,8 @@ def test_hello_email(self, mock_client):

"""Minimum required to send an email"""

self.mail.set_from(Email("test@example.com"))

self.mail.set_subject("Hello World from the SendGrid Python Library")
self.mail.from_email = Email("test@example.com")
self.mail.subject = "Hello World from the SendGrid Python Library"

personalization = Personalization()
personalization.add_to(Email("test@example.com"))
Expand All @@ -147,9 +146,9 @@ def test_kitchenSink(self, mock_client):

"""All settings set"""

self.mail.set_from(Email("test@example.com", "Example User"))
self.mail.from_email = Email("test@example.com", "Example User")

self.mail.set_subject("Hello World from the SendGrid Python Library")
self.mail.subject = "Hello World from the SendGrid Python Library"

personalization = Personalization()
personalization.add_to(Email("test@example.com", "Example User"))
Expand All @@ -158,14 +157,14 @@ def test_kitchenSink(self, mock_client):
personalization.add_cc(Email("test@example.com", "Example User"))
personalization.add_bcc(Email("test@example.com"))
personalization.add_bcc(Email("test@example.com"))
personalization.set_subject("Hello World from the Personalized SendGrid Python Library")
personalization.subject = "Hello World from the Personalized SendGrid Python Library"
personalization.add_header(Header("X-Test", "test"))
personalization.add_header(Header("X-Mock", "true"))
personalization.add_substitution(Substitution("%name%", "Example User"))
personalization.add_substitution(Substitution("%city%", "Denver"))
personalization.add_custom_arg(CustomArg("user_id", "343"))
personalization.add_custom_arg(CustomArg("type", "marketing"))
personalization.set_send_at(1443636843)
personalization.send_at = 1443636843
self.mail.add_personalization(personalization)

personalization2 = Personalization()
Expand All @@ -175,36 +174,36 @@ def test_kitchenSink(self, mock_client):
personalization2.add_cc(Email("test@example.com", "Example User"))
personalization2.add_bcc(Email("test@example.com"))
personalization2.add_bcc(Email("test@example.com"))
personalization2.set_subject("Hello World from the Personalized SendGrid Python Library")
personalization2.subject = "Hello World from the Personalized SendGrid Python Library"
personalization2.add_header(Header("X-Test", "test"))
personalization2.add_header(Header("X-Mock", "true"))
personalization2.add_substitution(Substitution("%name%", "Example User"))
personalization2.add_substitution(Substitution("%city%", "Denver"))
personalization2.add_custom_arg(CustomArg("user_id", "343"))
personalization2.add_custom_arg(CustomArg("type", "marketing"))
personalization2.set_send_at(1443636843)
personalization2.send_at = 1443636843
self.mail.add_personalization(personalization2)

self.mail.add_content(Content("text/plain", "some text here"))
self.mail.add_content(Content("text/html", "<html><body>some text here</body></html>"))

attachment = Attachment()
attachment.set_content("TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQsIGNvbnNlY3RldHVyIGFkaXBpc2NpbmcgZWxpdC4gQ3JhcyBwdW12")
attachment.set_type("application/pdf")
attachment.set_filename("balance_001.pdf")
attachment.set_disposition("attachment")
attachment.set_content_id("Balance Sheet")
attachment.content = "TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQsIGNvbnNlY3RldHVyIGFkaXBpc2NpbmcgZWxpdC4gQ3JhcyBwdW12"
attachment.type = "application/pdf"
attachment.filename = "balance_001.pdf"
attachment.disposition = "attachment"
attachment.content_id = "Balance Sheet"
self.mail.add_attachment(attachment)

attachment2 = Attachment()
attachment2.set_content("BwdW")
attachment2.set_type("image/png")
attachment2.set_filename("banner.png")
attachment2.set_disposition("inline")
attachment2.set_content_id("Banner")
attachment2.content = "BwdW"
attachment2.type = "image/png"
attachment2.filename = "banner.png"
attachment2.disposition = "inline"
attachment2.content_id = "Banner"
self.mail.add_attachment(attachment2)

self.mail.set_template_id("13b8f94f-bcae-4ec6-b752-70d6cb59f932")
self.mail.template_id = "13b8f94f-bcae-4ec6-b752-70d6cb59f932"

self.mail.add_section(Section("%section1%", "Substitution Text for Section 1"))
self.mail.add_section(Section("%section2%", "Substitution Text for Section 2"))
Expand All @@ -220,29 +219,29 @@ def test_kitchenSink(self, mock_client):
self.mail.add_custom_arg(CustomArg("campaign", "welcome"))
self.mail.add_custom_arg(CustomArg("weekday", "morning"))

self.mail.set_send_at(1443636842)
self.mail.send_at = 1443636842

self.mail.set_batch_id("sendgrid_batch_id")
self.mail.batch_id = "sendgrid_batch_id"

self.mail.set_asm(ASM(99, [4, 5, 6, 7, 8]))
self.mail.asm = ASM(99, [4, 5, 6, 7, 8])

self.mail.set_ip_pool_name("24")
self.mail.ip_pool_name = "24"

mail_settings = MailSettings()
mail_settings.set_bcc_settings(BCCSettings(True, Email("test@example.com")))
mail_settings.set_bypass_list_management(BypassListManagement(True))
mail_settings.set_footer_settings(FooterSettings(True, "Footer Text", "<html><body>Footer Text</body></html>"))
mail_settings.set_sandbox_mode(SandBoxMode(True))
mail_settings.set_spam_check(SpamCheck(True, 1, "https://spamcatcher.sendgrid.com"))
self.mail.set_mail_settings(mail_settings)
mail_settings.bcc_settings = BCCSettings(True, Email("test@example.com"))
mail_settings.bypass_list_management = BypassListManagement(True)
mail_settings.footer_settings = FooterSettings(True, "Footer Text", "<html><body>Footer Text</body></html>")
mail_settings.sandbox_mode = SandBoxMode(True)
mail_settings.spam_check = SpamCheck(True, 1, "https://spamcatcher.sendgrid.com")
self.mail.mail_settings = mail_settings

tracking_settings = TrackingSettings()
tracking_settings.set_click_tracking(ClickTracking(True, True))
tracking_settings.set_open_tracking(OpenTracking(True, "Optional tag to replace with the open image in the body of the message"))
tracking_settings.set_subscription_tracking(SubscriptionTracking(True, "text to insert into the text/plain portion of the message", "<html><body>html to insert into the text/html portion of the message</body></html>", "Optional tag to replace with the open image in the body of the message"))
tracking_settings.set_ganalytics(Ganalytics(True, "some source", "some medium", "some term", "some content", "some campaign"))
self.mail.set_tracking_settings(tracking_settings)
tracking_settings.click_tracking = ClickTracking(True, True)
tracking_settings.open_tracking = OpenTracking(True, "Optional tag to replace with the open image in the body of the message")
tracking_settings.subscription_tracking = SubscriptionTracking(True, "text to insert into the text/plain portion of the message", "<html><body>html to insert into the text/html portion of the message</body></html>", "Optional tag to replace with the open image in the body of the message")
tracking_settings.ganalytics = Ganalytics(True, "some source", "some medium", "some term", "some content", "some campaign")
self.mail.tracking_settings = tracking_settings

self.mail.set_reply_to(Email("test@example.com"))
self.mail.reply_to = Email("test@example.com")

self.assertEqual(json.dumps(self.mail.get(), sort_keys=True), '{"asm": {"group_id": 99, "groups_to_display": [4, 5, 6, 7, 8]}, "attachments": [{"content": "TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQsIGNvbnNlY3RldHVyIGFkaXBpc2NpbmcgZWxpdC4gQ3JhcyBwdW12", "content_id": "Balance Sheet", "disposition": "attachment", "filename": "balance_001.pdf", "type": "application/pdf"}, {"content": "BwdW", "content_id": "Banner", "disposition": "inline", "filename": "banner.png", "type": "image/png"}], "batch_id": "sendgrid_batch_id", "categories": ["May", "2016"], "content": [{"type": "text/plain", "value": "some text here"}, {"type": "text/html", "value": "<html><body>some text here</body></html>"}], "custom_args": {"campaign": "welcome", "weekday": "morning"}, "from": {"email": "test@example.com", "name": "Example User"}, "headers": {"X-Test1": "test1", "X-Test3": "test2", "X-Test4": "test4"}, "ip_pool_name": "24", "mail_settings": {"bcc": {"email": "test@example.com", "enable": true}, "bypass_list_management": {"enable": true}, "footer": {"enable": true, "html": "<html><body>Footer Text</body></html>", "text": "Footer Text"}, "sandbox_mode": {"enable": true}, "spam_check": {"enable": true, "post_to_url": "https://spamcatcher.sendgrid.com", "threshold": 1}}, "personalizations": [{"bcc": [{"email": "test@example.com"}, {"email": "test@example.com"}], "cc": [{"email": "test@example.com", "name": "Example User"}, {"email": "test@example.com", "name": "Example User"}], "custom_args": {"type": "marketing", "user_id": "343"}, "headers": {"X-Mock": "true", "X-Test": "test"}, "send_at": 1443636843, "subject": "Hello World from the Personalized SendGrid Python Library", "substitutions": {"%city%": "Denver", "%name%": "Example User"}, "to": [{"email": "test@example.com", "name": "Example User"}, {"email": "test@example.com", "name": "Example User"}]}, {"bcc": [{"email": "test@example.com"}, {"email": "test@example.com"}], "cc": [{"email": "test@example.com", "name": "Example User"}, {"email": "test@example.com", "name": "Example User"}], "custom_args": {"type": "marketing", "user_id": "343"}, "headers": {"X-Mock": "true", "X-Test": "test"}, "send_at": 1443636843, "subject": "Hello World from the Personalized SendGrid Python Library", "substitutions": {"%city%": "Denver", "%name%": "Example User"}, "to": [{"email": "test@example.com", "name": "Example User"}, {"email": "test@example.com", "name": "Example User"}]}], "reply_to": {"email": "test@example.com"}, "sections": {"%section1%": "Substitution Text for Section 1", "%section2%": "Substitution Text for Section 2"}, "send_at": 1443636842, "subject": "Hello World from the SendGrid Python Library", "template_id": "13b8f94f-bcae-4ec6-b752-70d6cb59f932", "tracking_settings": {"click_tracking": {"enable": true, "enable_text": true}, "ganalytics": {"enable": true, "utm_campaign": "some campaign", "utm_content": "some content", "utm_medium": "some medium", "utm_source": "some source", "utm_term": "some term"}, "open_tracking": {"enable": true, "substitution_tag": "Optional tag to replace with the open image in the body of the message"}, "subscription_tracking": {"enable": true, "html": "<html><body>html to insert into the text/html portion of the message</body></html>", "substitution_tag": "Optional tag to replace with the open image in the body of the message", "text": "text to insert into the text/plain portion of the message"}}}')

0 comments on commit 64b824c

Please sign in to comment.