Example #1
0
 def test_fails_no_content(self):
     mail = SendGrid()
     mail.api_key = app.config['SENDGRID_API_KEY']
     with self.assertRaises(ValueError):
         mail.send_email(subject='subject',
                         from_email='from',
                         to_email='to')
Example #2
0
def send(self, from_email, to_email, subject, text):
    with current_app.app_context():
        sg = SendGrid(current_app)
        sg.send_email(
            from_email=from_email,
            to_email=to_email,
            subject=subject,
            text=text)
Example #3
0
def invite_user(email):
    try:
        user = current_user._get_current_object()

        mail = SendGrid(app)

        mail.send_email(from_email=app.config['SENDGRID_DEFAULT_FROM'],
                        to_email=email,
                        subject='Come Join Quillio',
                        html=invite_html(user.email, email))

        flash('success Invitation Sent.')
    except Exception as e:
        flash('error Could not Create Invitation. {}'.format(e))

    return redirect(request.args.get('next') or url_for('meetings.home'))
Example #4
0
def signup():
    """ Signs the Current User In """

    if request.method == 'GET':
        return render_template('auth/signup.html', form=SignupForm())

    form = SignupForm(request.form)

    if not form.validate():
        flash('error Invalid Email or Password')
        return redirect(url_for('auth.signup'))

    name = form.name.data
    email = form.email.data
    password = form.password.data

    try:
        # validate that the user does not already exist
        if User.objects(email__exact=email).count() != 0:
            flash('error An Account Is Already Using That Email.')
            return redirect(url_for('auth.login'))

        # generate activation token
        activation_token = secrets.token_urlsafe(32)
        mail = SendGrid(app)

        # send registration email
        mail.send_email(from_email=app.config['SENDGRID_DEFAULT_FROM'],
                        to_email=email,
                        subject='Welcome to Quillio',
                        html=activate_html(name, activation_token, email))

        # add user to the database
        user_datastore.create_user(
            email=email,
            name=name,
            password=hash_password(password),
            activation_hash=hash_password(activation_token),
            active=True,
            authenticated=False)

        flash('Please Check Your Email For An Activation Request.')
        return redirect(url_for('auth.login'))
    except Exception as e:
        print(str(e))
        flash('error An Error has Occured, Please Try Again!')
        return redirect(url_for('auth.signup'))
Example #5
0
def forgot_password():
    """ Initializes a User's Request to Reset their Password """

    form = PasswordResetRequestForm(request.form)

    if request.method == 'GET':
        return render_template('auth/password_reset_request.html', form=form)

    if not form.validate():
        flash('error Could not Reset Password at this Time.')
        return redirect(url_for('auth.signup'))

    user = user_datastore.find_user(email=form.email.data)

    if user is None:
        flash('error Invalid Email. Please Create an Account.')
        return redirect(url_for('auth.signup'))

    # generate reset token
    reset_token = secrets.token_urlsafe(32)

    # update the user's password reset hash
    user.password_reset_hash = hash_password(reset_token)
    user.save()

    try:
        mail = SendGrid(app)

        # send the password reset email
        mail.send_email(from_email=app.config['SENDGRID_DEFAULT_FROM'],
                        to_email=user.email,
                        subject='Quillio Reset Password',
                        html=password_html(user.name, reset_token,
                                           form.email.data))

        flash('success Please Check Your Email For a Reset Confirmation.')
        return redirect(url_for('auth.login'))
    except Exception as e:
        print(str(e))
        flash('error Could Not Send Reset Request.')
        return redirect(url_for('auth.login'))
Example #6
0
def start_meeting(data):
    meeting = Meeting.objects.with_id(data['room_id'])
    meeting.active = False
    meeting.save()
    emit('endMeeting', room=data['room_id'])
    update_grammar(data['room_id'])
    pt = ""
    for ts in meeting.transcript:
        pt += '{0}: {1}\\n'.format(ts.user.name, ts.transcription)
    meeting.transcriptText = pt
    meeting.save()

    try:
        # send the password reset email
        for member in meeting.members:
            mail = SendGrid(app)
            mail.send_email(from_email=app.config['SENDGRID_DEFAULT_FROM'],
                            to_email=member.email,
                            subject='Quillio Meeting Completed',
                            html=summary_html(member.name, meeting.name,
                                              meeting.get_summary()))
    except Exception as e:
        print(str(e))
Example #7
0
import os

from flasgger import Swagger
from flask import Flask, render_template
from flask_login import LoginManager
from flask_sendgrid import SendGrid
from flask_sqlalchemy import SQLAlchemy
from flask_wtf import CsrfProtect

from config import config

db = SQLAlchemy()
mail = SendGrid()
csrf = CsrfProtect()

# Set up Flask-login
login_manager = LoginManager()
login_manager.session_protection = 'strong'
login_manager.login_view = 'auth.signin'


def create_app(config_name):
    '''For to use dynamic environment'''
    app = Flask(__name__)
    app.config.from_object(config[config_name])

    db.init_app(app)
    mail.init_app(app)
    csrf.init_app(app)
    login_manager.init_app(app)
def create_mail_server(app: Flask):
    """ Setup flask mailing server """
    # Check for Testing state - set up Sendgrid if not
    if not app.config['TESTING']:
        app.mail = SendGrid(app)
Example #9
0
class SendGridTest(unittest.TestCase):
    def setUp(self):
        self.mail = SendGrid(app)

    def test_get_api_key(self):
        self.assertEqual(self.mail.api_key, app.config['SENDGRID_API_KEY'])

    def test_fails_no_key(self):
        self.assertRaises(TypeError, self.mail.send_email)

    def test_fails_no_sender(self):
        mail = SendGrid()
        mail.api_key = app.config['SENDGRID_API_KEY']
        with self.assertRaises(ValueError):
            mail.send_email(subject='subject', to_email='to')

    def test_fails_no_content(self):
        mail = SendGrid()
        mail.api_key = app.config['SENDGRID_API_KEY']
        with self.assertRaises(ValueError):
            mail.send_email(subject='subject',
                            from_email='from',
                            to_email='to')

    @patch('python_http_client.Client._make_request')
    def test_mandrill_compat_email_send(self, mock_client):
        mock = Mock()
        mock.return_value.ok = True
        mock_client.return_value = mock

        self.mail.send_email(subject='Subject',
                             to_email='*****@*****.**',
                             html='<h2>html</h2>')

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

    @patch('python_http_client.Client._make_request')
    def test_mandrill_compat_single_recipient(self, mock_client):
        mock = Mock()
        mock.return_value.ok = True
        mock_client.return_value = mock

        self.mail.send_email(subject='Subject',
                             to_email=[{
                                 'email': '*****@*****.**'
                             }],
                             html='<h2>html</h2>')

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

    @patch('python_http_client.Client._make_request')
    def test_mandrill_compat_multiple_recipient(self, mock_client):
        mock = Mock()
        mock.return_value.ok = True
        mock_client.return_value = mock

        self.mail.send_email(subject='Subject',
                             to_email=[{
                                 'email': '*****@*****.**'
                             }, {
                                 'email': '*****@*****.**'
                             }],
                             html='<h2>html</h2>')

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

    @patch('python_http_client.Client._make_request')
    def test_single_recipient_email_object(self, mock_client):
        mock = Mock()
        mock.return_value.ok = True
        mock_client.return_value = mock

        self.mail.send_email(subject='Subject',
                             to_email=Email('*****@*****.**'),
                             html='<h2>html</h2>')

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

    @patch('python_http_client.Client._make_request')
    def test_multiple_recipient_email_object(self, mock_client):
        mock = Mock()
        mock.return_value.ok = True
        mock_client.return_value = mock

        self.mail.send_email(
            subject='Subject',
            to_email=[Email('*****@*****.**'),
                      Email('*****@*****.**')],
            html='<h2>html</h2>')

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

    @patch('python_http_client.Client._make_request')
    def test_hello_email(self, mock_client):
        self.maxDiff = None

        mock = Mock()
        mock.return_value.ok = True
        mock_client.return_value = mock
        """Minimum required to send an email"""

        self.mail.from_email = Email("*****@*****.**")
        self.mail.subject = "Hello World from the SendGrid Python Library"

        personalization = Personalization()
        personalization.add_to(Email("*****@*****.**"))
        self.mail.add_personalization(personalization)

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

        self.assertEqual(
            json.dumps(self.mail.get(), sort_keys=True),
            '{"content": [{"type": "text/plain", "value": "some text here"}, {"type": "text/html", "value": "<html><body>some text here</body></html>"}], "from": {"email": "*****@*****.**"}, "personalizations": [{"to": [{"email": "*****@*****.**"}]}], "subject": "Hello World from the SendGrid Python Library"}'
        )

    @patch('python_http_client.Client._make_request')
    def test_kitchenSink(self, mock_client):
        self.maxDiff = None

        mock = Mock()
        mock.return_value.ok = True
        mock_client.return_value = mock
        """All settings set"""

        self.mail.from_email = Email("*****@*****.**", "Example User")

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

        personalization = Personalization()
        personalization.add_to(Email("*****@*****.**", "Example User"))
        personalization.add_to(Email("*****@*****.**", "Example User"))
        personalization.add_cc(Email("*****@*****.**", "Example User"))
        personalization.add_cc(Email("*****@*****.**", "Example User"))
        personalization.add_bcc(Email("*****@*****.**"))
        personalization.add_bcc(Email("*****@*****.**"))
        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.send_at = 1443636843
        self.mail.add_personalization(personalization)

        personalization2 = Personalization()
        personalization2.add_to(Email("*****@*****.**", "Example User"))
        personalization2.add_to(Email("*****@*****.**", "Example User"))
        personalization2.add_cc(Email("*****@*****.**", "Example User"))
        personalization2.add_cc(Email("*****@*****.**", "Example User"))
        personalization2.add_bcc(Email("*****@*****.**"))
        personalization2.add_bcc(Email("*****@*****.**"))
        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.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.file_content = FileContent(
            "TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQsIGNvbnNlY3RldHVyIGFkaXBpc2NpbmcgZWxpdC4gQ3JhcyBwdW12"
        )
        attachment.file_type = FileType("application/pdf")
        attachment.file_name = FileName("balance_001.pdf")
        attachment.disposition = Disposition("attachment")
        attachment.content_id = ContentId("Balance Sheet")
        self.mail.add_attachment(attachment)

        attachment2 = Attachment()
        attachment2.file_content = FileContent("BwdW")
        attachment2.file_type = FileType("image/png")
        attachment2.file_name = FileName("banner.png")
        attachment2.disposition = Disposition("inline")
        attachment2.content_id = ContentId("Banner")
        self.mail.add_attachment(attachment2)

        self.mail.template_id = TemplateId(
            "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"))

        self.mail.add_header(Header("X-Test1", "test1"))
        self.mail.add_header(Header("X-Test3", "test2"))

        self.mail.add_header(Header("X-Test4", "test4"))

        self.mail.add_category(Category("May"))
        self.mail.add_category(Category("2016"))

        self.mail.add_custom_arg(CustomArg("campaign", "welcome"))
        self.mail.add_custom_arg(CustomArg("weekday", "morning"))

        self.mail.send_at = SendAt(1443636842)

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

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

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

        mail_settings = MailSettings()
        mail_settings.bcc_settings = BccSettings(
            True, BccSettingsEmail("*****@*****.**"))
        mail_settings.bypass_list_management = BypassListManagement(True)
        mail_settings.footer_settings = FooterSettings(
            True, FooterText("Footer Text"),
            FooterHtml("<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.click_tracking = ClickTracking(True, True)
        tracking_settings.open_tracking = OpenTracking(
            True,
            OpenTrackingSubstitutionTag(
                "Optional tag to replace with the open image in the body of the message"
            ))
        tracking_settings.subscription_tracking = SubscriptionTracking(
            True,
            SubscriptionText(
                "text to insert into the text/plain portion of the message"),
            SubscriptionHtml(
                "<html><body>html to insert into the text/html portion of the message</body></html>"
            ),
            SubscriptionSubstitutionTag(
                "Optional tag to replace with the open image in the body of the message"
            ))
        tracking_settings.ganalytics = Ganalytics(True,
                                                  UtmSource("some source"),
                                                  UtmMedium("some medium"),
                                                  UtmTerm("some term"),
                                                  UtmContent("some content"),
                                                  UtmCampaign("some campaign"))
        self.mail.tracking_settings = tracking_settings

        self.mail.reply_to = ReplyTo("*****@*****.**")
        print(json.dumps(self.mail.get(), sort_keys=True))
        self.assertEqual(
            json.dumps(self.mail.get(), sort_keys=True),
            '{"asm": {"group_id": 99, "groups_to_display": [4, 5, 6, 7, 8]}, "attachments": [{"content": "BwdW", "content_id": "Banner", "disposition": "inline", "filename": "banner.png", "type": "image/png"}, {"content": "TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQsIGNvbnNlY3RldHVyIGFkaXBpc2NpbmcgZWxpdC4gQ3JhcyBwdW12", "content_id": "Balance Sheet", "disposition": "attachment", "filename": "balance_001.pdf", "type": "application/pdf"}], "batch_id": "sendgrid_batch_id", "categories": ["2016", "May"], "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": "*****@*****.**", "name": "Example User"}, "headers": {"X-Test1": "test1", "X-Test3": "test2", "X-Test4": "test4"}, "ip_pool_name": "24", "mail_settings": {"bcc": {"email": "*****@*****.**", "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": "*****@*****.**"}, {"email": "*****@*****.**"}], "cc": [{"email": "*****@*****.**", "name": "Example User"}, {"email": "*****@*****.**", "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": "*****@*****.**", "name": "Example User"}, {"email": "*****@*****.**", "name": "Example User"}]}, {"bcc": [{"email": "*****@*****.**"}, {"email": "*****@*****.**"}], "cc": [{"email": "*****@*****.**", "name": "Example User"}, {"email": "*****@*****.**", "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": "*****@*****.**", "name": "Example User"}, {"email": "*****@*****.**", "name": "Example User"}]}], "reply_to": {"email": "*****@*****.**"}, "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"}}}'
        )
Example #10
0
__all__ = [
    'db', 'fjson', 'ip2loc', 'onedrive', 'redis', 'pat', 'sendgrid', 'sqlogger'
]

from flask_json import FlaskJSON
from flask_redis import FlaskRedis

from flask_sendgrid import SendGrid
from flask_sqlalchemy_ import SQLAlchemy
from ip2loc import IP2Loc
from onedrive import OneDrive
from pypat import Pat
from sqlalchemy_ import BaseModel
from sqlogger import SQLogger

db = SQLAlchemy(Model=BaseModel)
fjson = FlaskJSON()
ip2loc = IP2Loc()
onedrive = OneDrive()
pat = Pat()
redis = FlaskRedis()
sendgrid = SendGrid()
sqlogger = SQLogger()
Example #11
0
 def test_fails_no_content(self):
     mail = SendGrid()
     mail.api_key = app.config['SENDGRID_API_KEY']
     with self.assertRaises(ValueError):
         mail.send_email(subject='subject', from_email='from', to_email='to')
Example #12
0
 def setUp(self):
     self.mail = SendGrid(app)
Example #13
0
class SendGridTest(unittest.TestCase):

    def setUp(self):
        self.mail = SendGrid(app)

    def test_get_api_key(self):
        self.assertEqual(self.mail.api_key, app.config['SENDGRID_API_KEY'])

    def test_fails_no_key(self):
        self.assertRaises(TypeError, self.mail.send_email)

    def test_fails_no_sender(self):
        mail = SendGrid()
        mail.api_key = app.config['SENDGRID_API_KEY']
        with self.assertRaises(ValueError):
            mail.send_email(subject='subject', to_email='to')

    def test_fails_no_content(self):
        mail = SendGrid()
        mail.api_key = app.config['SENDGRID_API_KEY']
        with self.assertRaises(ValueError):
            mail.send_email(subject='subject', from_email='from', to_email='to')

    @patch('python_http_client.Client._make_request')
    def test_mandrill_compat_email_send(self, mock_client):
        mock = Mock()
        mock.return_value.ok = True
        mock_client.return_value = mock

        self.mail.send_email(
            subject='Subject',
            to_email='*****@*****.**',
            html='<h2>html</h2>'
        )

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

    @patch('python_http_client.Client._make_request')
    def test_mandrill_compat_single_recipient(self, mock_client):
        mock = Mock()
        mock.return_value.ok = True
        mock_client.return_value = mock

        self.mail.send_email(
            subject='Subject',
            to_email=[{'email': '*****@*****.**'}],
            html='<h2>html</h2>'
        )

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

    @patch('python_http_client.Client._make_request')
    def test_mandrill_compat_multiple_recipient(self, mock_client):
        mock = Mock()
        mock.return_value.ok = True
        mock_client.return_value = mock

        self.mail.send_email(
            subject='Subject',
            to_email=[{'email': '*****@*****.**'}, {'email': '*****@*****.**'}],
            html='<h2>html</h2>'
        )

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

    @patch('python_http_client.Client._make_request')
    def test_single_recipient_email_object(self, mock_client):
        mock = Mock()
        mock.return_value.ok = True
        mock_client.return_value = mock

        self.mail.send_email(
            subject='Subject',
            to_email=Email('*****@*****.**'),
            html='<h2>html</h2>'
        )

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

    @patch('python_http_client.Client._make_request')
    def test_multiple_recipient_email_object(self, mock_client):
        mock = Mock()
        mock.return_value.ok = True
        mock_client.return_value = mock

        self.mail.send_email(
            subject='Subject',
            to_email=[Email('*****@*****.**'), Email('*****@*****.**')],
            html='<h2>html</h2>'
        )

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

    @patch('python_http_client.Client._make_request')
    def test_hello_email(self, mock_client):
        self.maxDiff = None

        mock = Mock()
        mock.return_value.ok = True
        mock_client.return_value = mock

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

        self.mail.from_email = Email("*****@*****.**")
        self.mail.subject = "Hello World from the SendGrid Python Library"

        personalization = Personalization()
        personalization.add_to(Email("*****@*****.**"))
        self.mail.add_personalization(personalization)

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

        self.assertEqual(json.dumps(self.mail.get(), sort_keys=True), '{"content": [{"type": "text/plain", "value": "some text here"}, {"type": "text/html", "value": "<html><body>some text here</body></html>"}], "from": {"email": "*****@*****.**"}, "personalizations": [{"to": [{"email": "*****@*****.**"}]}], "subject": "Hello World from the SendGrid Python Library"}')

    @patch('python_http_client.Client._make_request')
    def test_kitchenSink(self, mock_client):
        self.maxDiff = None

        mock = Mock()
        mock.return_value.ok = True
        mock_client.return_value = mock

        """All settings set"""

        self.mail.from_email = Email("*****@*****.**", "Example User")

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

        personalization = Personalization()
        personalization.add_to(Email("*****@*****.**", "Example User"))
        personalization.add_to(Email("*****@*****.**", "Example User"))
        personalization.add_cc(Email("*****@*****.**", "Example User"))
        personalization.add_cc(Email("*****@*****.**", "Example User"))
        personalization.add_bcc(Email("*****@*****.**"))
        personalization.add_bcc(Email("*****@*****.**"))
        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.send_at = 1443636843
        self.mail.add_personalization(personalization)

        personalization2 = Personalization()
        personalization2.add_to(Email("*****@*****.**", "Example User"))
        personalization2.add_to(Email("*****@*****.**", "Example User"))
        personalization2.add_cc(Email("*****@*****.**", "Example User"))
        personalization2.add_cc(Email("*****@*****.**", "Example User"))
        personalization2.add_bcc(Email("*****@*****.**"))
        personalization2.add_bcc(Email("*****@*****.**"))
        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.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.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.content = "BwdW"
        attachment2.type = "image/png"
        attachment2.filename = "banner.png"
        attachment2.disposition = "inline"
        attachment2.content_id = "Banner"
        self.mail.add_attachment(attachment2)

        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"))

        self.mail.add_header(Header("X-Test1", "test1"))
        self.mail.add_header(Header("X-Test3", "test2"))

        self.mail.add_header({"X-Test4": "test4"})

        self.mail.add_category(Category("May"))
        self.mail.add_category(Category("2016"))

        self.mail.add_custom_arg(CustomArg("campaign", "welcome"))
        self.mail.add_custom_arg(CustomArg("weekday", "morning"))

        self.mail.send_at = 1443636842

        self.mail.batch_id = "sendgrid_batch_id"

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

        self.mail.ip_pool_name = "24"

        mail_settings = MailSettings()
        mail_settings.bcc_settings = BCCSettings(True, Email("*****@*****.**"))
        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.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.reply_to = Email("*****@*****.**")

        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": "*****@*****.**", "name": "Example User"}, "headers": {"X-Test1": "test1", "X-Test3": "test2", "X-Test4": "test4"}, "ip_pool_name": "24", "mail_settings": {"bcc": {"email": "*****@*****.**", "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": "*****@*****.**"}, {"email": "*****@*****.**"}], "cc": [{"email": "*****@*****.**", "name": "Example User"}, {"email": "*****@*****.**", "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": "*****@*****.**", "name": "Example User"}, {"email": "*****@*****.**", "name": "Example User"}]}, {"bcc": [{"email": "*****@*****.**"}, {"email": "*****@*****.**"}], "cc": [{"email": "*****@*****.**", "name": "Example User"}, {"email": "*****@*****.**", "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": "*****@*****.**", "name": "Example User"}, {"email": "*****@*****.**", "name": "Example User"}]}], "reply_to": {"email": "*****@*****.**"}, "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"}}}')
Example #14
0
def get_mail_context():
    """Fetch or generate SendGrid mailer object."""
    if "main" not in g:
        mail = SendGrid(current_app)
        g.mail = mail
    return g.mail
Example #15
0
from flask_sendgrid import SendGrid


sg = SendGrid()
Example #16
0
from flask import Flask, render_template, request
from flask_sendgrid import SendGrid

key = open('/vault/secrets/api-key.txt').read()
i = key.find(":", 5)
j = key.find("]")
apikey = key[i + 1:j]

app = Flask(__name__)
app.config['SENDGRID_API_KEY'] = apikey
app.config['SENDGRID_DEFAULT_FROM'] = '*****@*****.**'
mail = SendGrid(app)


@app.route('/', methods=["POST", "GET"])
def index():
    if request.method == "POST":
        name = request.form.get("name")
        email = request.form.get("email")
        message = request.form.get("message")

        mail.send_email(to_email=email,
                        subject='Thank you for your Contact',
                        text=message)

        return render_template('index.html')

    else:
        return render_template('index.html')

Example #17
0
 def setUp(self):
     self.mail = SendGrid(app)