示例#1
0
def sendMailWithPdf(email):
    #mailMsg = '{
    #       "subject": "subject",
    #      "to": "*****@*****.**",
    #     "from": "*****@*****.**",
    #    "text": "Text",
    #   "html": "",
    #  "filename": "stats.xlsx",
    # "contentId": "stats"
    #}'
    #mailMsgJson = json.loads(mailMsg)
    message = Mail()
    message.to = To(email.data['to'])
    message.subject = Subject(email.data['subject'], p=0)
    message.from_email = From(email.data['from'], 'My Team Manager')

    message.template_id = TemplateId(email.data['templateId'])
    message.attachment = Attachment(FileContent(email.data['pdf']),
                                    FileName(email.data['filename']),
                                    FileType('application/pdf'),
                                    Disposition('attachment'),
                                    ContentId('Content ID 1'))
    message.content = Content(MimeType.text, email.data['text'])
    message.content = Content(MimeType.html, email.data['html'])
    sg = SendGridAPIClient(mailApiKey)
    response = sg.send(message)
    print(response.status_code)
    print(response.body)
    print(response.headers)
示例#2
0
def send_email(recipients, subject, text_body, html_body, send_admin=False):
    message = Mail()
    msg_to = []
    for r in recipients:
        msg_to.append(To(r))
    message.to = msg_to

    if send_admin:
        admin_list = current_app.config['MAIL_ADMINS'].split(';')
        msg_bcc = []
        for a in admin_list:
            msg_bcc.append(Bcc(a))
        message.bcc = msg_bcc

    message.subject = Subject(subject)
    message.from_email = From(current_app.config['MAIL_FROM'],
                              'Indian Matrimonial')
    message.reply_to = ReplyTo(current_app.config['MAIL_REPLY_TO'],
                               'Indian Matrimonial')
    message.content = [
        Content('text/html', html_body),
        Content('text/txt', text_body)
    ]

    try:
        sg = SendGridAPIClient(current_app.config['SENDGRID_API_KEY'])
        response = sg.send(message)
        print(response.status_code),
        print(response.body)
        print(response.headers)
        return True
    except Exception as e:
        print(e)
        return False
示例#3
0
    def create(self):
        """
        set content from a list or string and then create a mail Object

        @return:
        email
        @rtype: SendGrid Object
        """

        if type(self.content) == list:
            if self.content[1] != None:
                if self.content[0] != self.content[1]:
                    self.content = "-content-"
                else:
                    self.content = self.content[0]
            else:
                self.content = self.content[0]

        # create a Mail and assign sender, object, receivers and content
        mail = Mail()
        mail.from_email = self.from_sender
        mail.subject = self.subject
        mail.to = self.to_receivers
        mail.content = Content("text/plain", self.content)
        return mail
    def test_single_email_to_a_single_recipient_content_reversed(self):
        """Tests bug found in Issue-451 with Content ordering causing a crash
        """
        from sendgrid.helpers.mail import (Mail, From, To, Subject,
                                           PlainTextContent, HtmlContent)
        self.maxDiff = None
        message = Mail()
        message.from_email = From('*****@*****.**', 'Example From Name')
        message.to = To('*****@*****.**', 'Example To Name')
        message.subject = Subject('Sending with SendGrid is Fun')
        message.content = HtmlContent(
            '<strong>and easy to do anywhere, even with Python</strong>')
        message.content = PlainTextContent(
            'and easy to do anywhere, even with Python')

        self.assertEqual(
            message.get(),
            json.loads(r'''{
                "content": [
                    {
                        "type": "text/plain",
                        "value": "and easy to do anywhere, even with Python"
                    },
                    {
                        "type": "text/html",
                        "value": "<strong>and easy to do anywhere, even with Python</strong>"
                    }
                ],
                "from": {
                    "email": "*****@*****.**",
                    "name": "Example From Name"
                },
                "personalizations": [
                    {
                        "to": [
                            {
                                "email": "*****@*****.**",
                                "name": "Example To Name"
                            }
                        ]
                    }
                ],
                "subject": "Sending with SendGrid is Fun"
            }''')
        )
    def test_single_email_to_a_single_recipient_content_reversed(self):
        """Tests bug found in Issue-451 with Content ordering causing a crash
        """
        from sendgrid.helpers.mail import (Mail, From, To, Subject,
                                           PlainTextContent, HtmlContent)
        self.maxDiff = None
        message = Mail()
        message.from_email = From('*****@*****.**', 'Example From Name')
        message.to = To('*****@*****.**', 'Example To Name')
        message.subject = Subject('Sending with SendGrid is Fun')
        message.content = HtmlContent(
            '<strong>and easy to do anywhere, even with Python</strong>')
        message.content = PlainTextContent(
            'and easy to do anywhere, even with Python')

        self.assertEqual(
            message.get(),
            json.loads(r'''{
                "content": [
                    {
                        "type": "text/plain",
                        "value": "and easy to do anywhere, even with Python"
                    },
                    {
                        "type": "text/html",
                        "value": "<strong>and easy to do anywhere, even with Python</strong>"
                    }
                ],
                "from": {
                    "email": "*****@*****.**",
                    "name": "Example From Name"
                },
                "personalizations": [
                    {
                        "to": [
                            {
                                "email": "*****@*****.**",
                                "name": "Example To Name"
                            }
                        ]
                    }
                ],
                "subject": "Sending with SendGrid is Fun"
            }'''))
示例#6
0
def send_mail(from_mail: str, to_mail: str, subject: str, content: str, cc: List[str] = None) -> object:
    sg = sendgrid.SendGridAPIClient(config.SENDGRID_KEY)

    mail = Mail()
    mail.from_email = From(from_mail, "UCC Netsoc")
    mail. subject = subject
    mail.content = Content("text/plain", content)

    p = sendgrid.Personalization()
    p.add_to(To(to_mail))
    if cc:
        for email in cc:
            p.add_cc(Email(email))
    mail.add_personalization(p)
    return sg.send(mail)
示例#7
0
def warn_ops(num_recipients):
    mail = Mail()
    mail.to = To("*****@*****.**")

    #this declaration looks stupid because of PEP8 rules for line length
    mail.content = Content(
        MimeType.text, "The script for sending onboarding \
        reminders is sending to {} panelists. That's a big number.".format(
            num_recipients))

    mail.from_email = Email(SENDER_EMAIL, SENDER_NAME)
    mail.subject = Subject("Many onboarding reminders warning")
    mail.bcc = Bcc(BCC)
    response = sg.client.mail.send.post(request_body=mail.get())
    logger.write("Ops warning for many reminders.\n",
                 "Number of reminders sent: ", str(num_recipients))
    logResponseData(logger, response)
示例#8
0
    def create_email(
        self,
        to_list: List["str"],
        subject: str,
        html_content: str,
        image: bytes = None,
        content_type: str = None,
        send_at: datetime = None,
    ) -> Mail:
        """
        Create a new sendgrid email object.

        Params:
        ------
        to_list: List[str] - The recipients list.
        subject: str - The email subject.
        html_contentet: str - HTML text to fill the email.
        image: bytes - A optional image to attachment in email.
        content_type: str - The content type of the image.
        send_at: datetime - The datetime when the email must be sended.

        Return:
        ------
        message: Mail - The sendgrid email object.
        """
        message = Mail()
        message.from_email = From(self.from_email)
        message.subject = Subject(subject)

        _users_list = []
        for _to in to_list:
            _users_list.append(To(_to))
        message.to = _users_list

        if image:
            ext = str(content_type).split("/")[1]
            timestamp = datetime.utcnow().strftime("%Y-%m-%d-%H%M%S")
            message.attachment = Attachment(
                FileContent(image), FileName(f'event_image-{timestamp}.{ext}'),
                FileType(str(content_type)), Disposition('attachment'))

        if send_at:
            message.send_at = SendAt(self.get_unix_time(send_at), p=0)

        message.content = Content(MimeType.html, html_content)
        return message
示例#9
0
def send_email(from_email: str, to_emails: List[str], subject: str,
               body: str) -> None:
    """
    Sends an HTML email

    Args:
        - from_email (str): the from address for the email
        - to_emails (List[str]) the destination(s) for the email
        - subject (str): the subject for the email
        - body (str): the body of the email - supports HTML

    """
    message = Mail(
        from_email=from_email,
        to_emails=to_emails,
        subject=subject,
    )
    message.content = Content(MimeType.text, body)
    if config.sendgrid.send_email:
        sendgrid_client.send(message)
def send_email(from_email: str,
               to_email: str,
               subject: str,
               email: str,
               attachements=[],
               apikey=None) -> int:
    message = Mail(
        from_email=from_email,
        to_emails=to_email,
        subject=subject,
    )

    message.content = Content(MimeType.text, email)
    try:
        apikey = apikey if apikey else os.environ.get('SENDGRID_API_KEY1234')
        sg = sendgrid.SendGridAPIClient(apikey)
        response = sg.send(message)
        return response.status_code
    except Exception as e:
        logging.error(e)
        return 500
示例#11
0
def send_email(email, name):
    global API_KEY
    global SUBJECT
    global BODY

    BODY = "Hi {}".format(name)

    message = Mail(
        from_email='*****@*****.**',
        to_emails=email,
        subject=SUBJECT,
    )

    message.content = Content('text/plain', BODY)
    try:
        sg = sendgrid.SendGridAPIClient(API_KEY)
        response = sg.send(message)
        print(response.status_code)
        print(response.body)
        print(response.headers)

    except Exception as e:
        print(e)
    def test_kitchen_sink(self):
        from sendgrid.helpers.mail import (
            Mail, From, To, Cc, Bcc, Subject, Substitution, Header, CustomArg,
            SendAt, Content, MimeType, Attachment, FileName, FileContent,
            FileType, Disposition, ContentId, TemplateId, Section, ReplyTo,
            Category, BatchId, Asm, GroupId, GroupsToDisplay, IpPoolName,
            MailSettings, BccSettings, BccSettingsEmail, BypassListManagement,
            FooterSettings, FooterText, FooterHtml, SandBoxMode, SpamCheck,
            SpamThreshold, SpamUrl, TrackingSettings, ClickTracking,
            SubscriptionTracking, SubscriptionText, SubscriptionHtml,
            SubscriptionSubstitutionTag, OpenTracking,
            OpenTrackingSubstitutionTag, Ganalytics, UtmSource, UtmMedium,
            UtmTerm, UtmContent, UtmCampaign)

        self.maxDiff = None

        message = Mail()

        # Define Personalizations

        message.to = To('*****@*****.**', 'Example User1', p=0)
        message.to = [
            To('*****@*****.**', 'Example User2', p=0),
            To('*****@*****.**', 'Example User3', p=0)
        ]

        message.cc = Cc('*****@*****.**', 'Example User4', p=0)
        message.cc = [
            Cc('*****@*****.**', 'Example User5', p=0),
            Cc('*****@*****.**', 'Example User6', p=0)
        ]

        message.bcc = Bcc('*****@*****.**', 'Example User7', p=0)
        message.bcc = [
            Bcc('*****@*****.**', 'Example User8', p=0),
            Bcc('*****@*****.**', 'Example User9', p=0)
        ]

        message.subject = Subject('Sending with SendGrid is Fun 0', p=0)

        message.header = Header('X-Test1', 'Test1', p=0)
        message.header = Header('X-Test2', 'Test2', p=0)
        message.header = [
            Header('X-Test3', 'Test3', p=0),
            Header('X-Test4', 'Test4', p=0)
        ]

        message.substitution = Substitution('%name1%', 'Example Name 1', p=0)
        message.substitution = Substitution('%city1%', 'Example City 1', p=0)
        message.substitution = [
            Substitution('%name2%', 'Example Name 2', p=0),
            Substitution('%city2%', 'Example City 2', p=0)
        ]

        message.custom_arg = CustomArg('marketing1', 'true', p=0)
        message.custom_arg = CustomArg('transactional1', 'false', p=0)
        message.custom_arg = [
            CustomArg('marketing2', 'false', p=0),
            CustomArg('transactional2', 'true', p=0)
        ]

        message.send_at = SendAt(1461775051, p=0)

        message.to = To('*****@*****.**', 'Example User10', p=1)
        message.to = [
            To('*****@*****.**', 'Example User11', p=1),
            To('*****@*****.**', 'Example User12', p=1)
        ]

        message.cc = Cc('*****@*****.**', 'Example User13', p=1)
        message.cc = [
            Cc('*****@*****.**', 'Example User14', p=1),
            Cc('*****@*****.**', 'Example User15', p=1)
        ]

        message.bcc = Bcc('*****@*****.**', 'Example User16', p=1)
        message.bcc = [
            Bcc('*****@*****.**', 'Example User17', p=1),
            Bcc('*****@*****.**', 'Example User18', p=1)
        ]

        message.header = Header('X-Test5', 'Test5', p=1)
        message.header = Header('X-Test6', 'Test6', p=1)
        message.header = [
            Header('X-Test7', 'Test7', p=1),
            Header('X-Test8', 'Test8', p=1)
        ]

        message.substitution = Substitution('%name3%', 'Example Name 3', p=1)
        message.substitution = Substitution('%city3%', 'Example City 3', p=1)
        message.substitution = [
            Substitution('%name4%', 'Example Name 4', p=1),
            Substitution('%city4%', 'Example City 4', p=1)
        ]

        message.custom_arg = CustomArg('marketing3', 'true', p=1)
        message.custom_arg = CustomArg('transactional3', 'false', p=1)
        message.custom_arg = [
            CustomArg('marketing4', 'false', p=1),
            CustomArg('transactional4', 'true', p=1)
        ]

        message.send_at = SendAt(1461775052, p=1)

        message.subject = Subject('Sending with SendGrid is Fun 1', p=1)

        # The values below this comment are global to entire message

        message.from_email = From('*****@*****.**', 'Twilio SendGrid')

        message.reply_to = ReplyTo('*****@*****.**',
                                   'Twilio SendGrid Reply')

        message.subject = Subject('Sending with SendGrid is Fun 2')

        message.content = Content(MimeType.text,
                                  'and easy to do anywhere, even with Python')
        message.content = Content(
            MimeType.html,
            '<strong>and easy to do anywhere, even with Python</strong>')
        message.content = [
            Content('text/calendar', 'Party Time!!'),
            Content('text/custom', 'Party Time 2!!')
        ]

        message.attachment = Attachment(
            FileContent('base64 encoded content 1'),
            FileName('balance_001.pdf'), FileType('application/pdf'),
            Disposition('attachment'), ContentId('Content ID 1'))
        message.attachment = [
            Attachment(FileContent('base64 encoded content 2'),
                       FileName('banner.png'), FileType('image/png'),
                       Disposition('inline'), ContentId('Content ID 2')),
            Attachment(FileContent('base64 encoded content 3'),
                       FileName('banner2.png'), FileType('image/png'),
                       Disposition('inline'), ContentId('Content ID 3'))
        ]

        message.template_id = TemplateId(
            '13b8f94f-bcae-4ec6-b752-70d6cb59f932')

        message.section = Section('%section1%',
                                  'Substitution for Section 1 Tag')
        message.section = [
            Section('%section2%', 'Substitution for Section 2 Tag'),
            Section('%section3%', 'Substitution for Section 3 Tag')
        ]

        message.header = Header('X-Test9', 'Test9')
        message.header = Header('X-Test10', 'Test10')
        message.header = [
            Header('X-Test11', 'Test11'),
            Header('X-Test12', 'Test12')
        ]

        message.category = Category('Category 1')
        message.category = Category('Category 2')
        message.category = [Category('Category 1'), Category('Category 2')]

        message.custom_arg = CustomArg('marketing5', 'false')
        message.custom_arg = CustomArg('transactional5', 'true')
        message.custom_arg = [
            CustomArg('marketing6', 'true'),
            CustomArg('transactional6', 'false')
        ]

        message.send_at = SendAt(1461775053)

        message.batch_id = BatchId("HkJ5yLYULb7Rj8GKSx7u025ouWVlMgAi")

        message.asm = Asm(GroupId(1), GroupsToDisplay([1, 2, 3, 4]))

        message.ip_pool_name = IpPoolName("IP Pool Name")

        mail_settings = MailSettings()
        mail_settings.bcc_settings = BccSettings(
            False, BccSettingsEmail("*****@*****.**"))
        mail_settings.bypass_list_management = BypassListManagement(False)
        mail_settings.footer_settings = FooterSettings(
            True, FooterText("w00t"), FooterHtml("<string>w00t!<strong>"))
        mail_settings.sandbox_mode = SandBoxMode(True)
        mail_settings.spam_check = SpamCheck(True, SpamThreshold(5),
                                             SpamUrl("https://example.com"))
        message.mail_settings = mail_settings

        tracking_settings = TrackingSettings()
        tracking_settings.click_tracking = ClickTracking(True, False)
        tracking_settings.open_tracking = OpenTracking(
            True, OpenTrackingSubstitutionTag("open_tracking"))
        tracking_settings.subscription_tracking = SubscriptionTracking(
            True, SubscriptionText("Goodbye"),
            SubscriptionHtml("<strong>Goodbye!</strong>"),
            SubscriptionSubstitutionTag("unsubscribe"))
        tracking_settings.ganalytics = Ganalytics(True,
                                                  UtmSource("utm_source"),
                                                  UtmMedium("utm_medium"),
                                                  UtmTerm("utm_term"),
                                                  UtmContent("utm_content"),
                                                  UtmCampaign("utm_campaign"))
        message.tracking_settings = tracking_settings
        self.assertEqual(
            message.get(),
            json.loads(r'''{
                "asm": {
                    "group_id": 1,
                    "groups_to_display": [
                        1,
                        2,
                        3,
                        4
                    ]
                },
                "attachments": [
                    {
                        "content": "base64 encoded content 3",
                        "content_id": "Content ID 3",
                        "disposition": "inline",
                        "filename": "banner2.png",
                        "type": "image/png"
                    },
                    {
                        "content": "base64 encoded content 2",
                        "content_id": "Content ID 2",
                        "disposition": "inline",
                        "filename": "banner.png",
                        "type": "image/png"
                    },
                    {
                        "content": "base64 encoded content 1",
                        "content_id": "Content ID 1",
                        "disposition": "attachment",
                        "filename": "balance_001.pdf",
                        "type": "application/pdf"
                    }
                ],
                "batch_id": "HkJ5yLYULb7Rj8GKSx7u025ouWVlMgAi",
                "categories": [
                    "Category 2",
                    "Category 1",
                    "Category 2",
                    "Category 1"
                ],
                "content": [
                    {
                        "type": "text/plain",
                        "value": "and easy to do anywhere, even with Python"
                    },
                    {
                        "type": "text/html",
                        "value": "<strong>and easy to do anywhere, even with Python</strong>"
                    },
                    {
                        "type": "text/calendar",
                        "value": "Party Time!!"
                    },
                    {
                        "type": "text/custom",
                        "value": "Party Time 2!!"
                    }
                ],
                "custom_args": {
                    "marketing5": "false",
                    "marketing6": "true",
                    "transactional5": "true",
                    "transactional6": "false"
                },
                "from": {
                    "email": "*****@*****.**",
                    "name": "Twilio SendGrid"
                },
                "headers": {
                    "X-Test10": "Test10",
                    "X-Test11": "Test11",
                    "X-Test12": "Test12",
                    "X-Test9": "Test9"
                },
                "ip_pool_name": "IP Pool Name",
                "mail_settings": {
                    "bcc": {
                        "email": "*****@*****.**",
                        "enable": false
                    },
                    "bypass_list_management": {
                        "enable": false
                    },
                    "footer": {
                        "enable": true,
                        "html": "<string>w00t!<strong>",
                        "text": "w00t"
                    },
                    "sandbox_mode": {
                        "enable": true
                    },
                    "spam_check": {
                        "enable": true,
                        "post_to_url": "https://example.com",
                        "threshold": 5
                    }
                },
                "personalizations": [
                    {
                        "bcc": [
                            {
                                "email": "*****@*****.**",
                                "name": "Example User7"
                            },
                            {
                                "email": "*****@*****.**",
                                "name": "Example User8"
                            },
                            {
                                "email": "*****@*****.**",
                                "name": "Example User9"
                            }
                        ],
                        "cc": [
                            {
                                "email": "*****@*****.**",
                                "name": "Example User4"
                            },
                            {
                                "email": "*****@*****.**",
                                "name": "Example User5"
                            },
                            {
                                "email": "*****@*****.**",
                                "name": "Example User6"
                            }
                        ],
                        "custom_args": {
                            "marketing1": "true",
                            "marketing2": "false",
                            "transactional1": "false",
                            "transactional2": "true"
                        },
                        "headers": {
                            "X-Test1": "Test1",
                            "X-Test2": "Test2",
                            "X-Test3": "Test3",
                            "X-Test4": "Test4"
                        },
                        "send_at": 1461775051,
                        "subject": "Sending with SendGrid is Fun 0",
                        "substitutions": {
                            "%city1%": "Example City 1",
                            "%city2%": "Example City 2",
                            "%name1%": "Example Name 1",
                            "%name2%": "Example Name 2"
                        },
                        "to": [
                            {
                                "email": "*****@*****.**",
                                "name": "Example User1"
                            },
                            {
                                "email": "*****@*****.**",
                                "name": "Example User2"
                            },
                            {
                                "email": "*****@*****.**",
                                "name": "Example User3"
                            }
                        ]
                    },
                    {
                        "bcc": [
                            {
                                "email": "*****@*****.**",
                                "name": "Example User16"
                            },
                            {
                                "email": "*****@*****.**",
                                "name": "Example User17"
                            },
                            {
                                "email": "*****@*****.**",
                                "name": "Example User18"
                            }
                        ],
                        "cc": [
                            {
                                "email": "*****@*****.**",
                                "name": "Example User13"
                            },
                            {
                                "email": "*****@*****.**",
                                "name": "Example User14"
                            },
                            {
                                "email": "*****@*****.**",
                                "name": "Example User15"
                            }
                        ],
                        "custom_args": {
                            "marketing3": "true",
                            "marketing4": "false",
                            "transactional3": "false",
                            "transactional4": "true"
                        },
                        "headers": {
                            "X-Test5": "Test5",
                            "X-Test6": "Test6",
                            "X-Test7": "Test7",
                            "X-Test8": "Test8"
                        },
                        "send_at": 1461775052,
                        "subject": "Sending with SendGrid is Fun 1",
                        "substitutions": {
                            "%city3%": "Example City 3",
                            "%city4%": "Example City 4",
                            "%name3%": "Example Name 3",
                            "%name4%": "Example Name 4"
                        },
                        "to": [
                            {
                                "email": "*****@*****.**",
                                "name": "Example User10"
                            },
                            {
                                "email": "*****@*****.**",
                                "name": "Example User11"
                            },
                            {
                                "email": "*****@*****.**",
                                "name": "Example User12"
                            }
                        ]
                    }
                ],
                "reply_to": {
                    "email": "*****@*****.**",
                    "name": "Twilio SendGrid Reply"
                },
                "sections": {
                    "%section1%": "Substitution for Section 1 Tag",
                    "%section2%": "Substitution for Section 2 Tag",
                    "%section3%": "Substitution for Section 3 Tag"
                },
                "send_at": 1461775053,
                "subject": "Sending with SendGrid is Fun 2",
                "template_id": "13b8f94f-bcae-4ec6-b752-70d6cb59f932",
                "tracking_settings": {
                    "click_tracking": {
                        "enable": true,
                        "enable_text": false
                    },
                    "ganalytics": {
                        "enable": true,
                        "utm_campaign": "utm_campaign",
                        "utm_content": "utm_content",
                        "utm_medium": "utm_medium",
                        "utm_source": "utm_source",
                        "utm_term": "utm_term"
                    },
                    "open_tracking": {
                        "enable": true,
                        "substitution_tag": "open_tracking"
                    },
                    "subscription_tracking": {
                        "enable": true,
                        "html": "<strong>Goodbye!</strong>",
                        "substitution_tag": "unsubscribe",
                        "text": "Goodbye"
                    }
                }
            }'''))
示例#13
0
def build_kitchen_sink():
    """All settings set"""
    from sendgrid.helpers.mail import (
        Mail, From, To, Cc, Bcc, Subject, PlainTextContent, 
        HtmlContent, SendGridException, Substitution, 
        Header, CustomArg, SendAt, Content, MimeType, Attachment,
        FileName, FileContent, FileType, Disposition, ContentId,
        TemplateId, Section, ReplyTo, Category, BatchId, Asm,
        GroupId, GroupsToDisplay, IpPoolName, MailSettings,
        BccSettings, BccSettingsEmail, BypassListManagement,
        FooterSettings, FooterText, FooterHtml, SandBoxMode,
        SpamCheck, SpamThreshold, SpamUrl, TrackingSettings,
        ClickTracking, SubscriptionTracking, SubscriptionText,
        SubscriptionHtml, SubscriptionSubstitutionTag,
        OpenTracking, OpenTrackingSubstitutionTag, Ganalytics,
        UtmSource, UtmMedium, UtmTerm, UtmContent, UtmCampaign)
    import time
    import datetime

    message = Mail()

    # Define Personalizations 

    message.to = To('*****@*****.**', 'Example User1', p=0)
    message.to = [ 
        To('*****@*****.**', 'Example User2', p=0),
        To('*****@*****.**', 'Example User3', p=0)
    ]

    message.cc = Cc('*****@*****.**', 'Example User4', p=0)
    message.cc = [ 
        Cc('*****@*****.**', 'Example User5', p=0),
        Cc('*****@*****.**', 'Example User6', p=0)
    ]

    message.bcc = Bcc('*****@*****.**', 'Example User7', p=0)
    message.bcc = [ 
        Bcc('*****@*****.**', 'Example User8', p=0),
        Bcc('*****@*****.**', 'Example User9', p=0)
    ]

    message.subject = Subject('Sending with SendGrid is Fun 0', p=0)

    message.header = Header('X-Test1', 'Test1', p=0)
    message.header = Header('X-Test2', 'Test2', p=0)
    message.header = [
        Header('X-Test3', 'Test3', p=0),
        Header('X-Test4', 'Test4', p=0)
    ]

    message.substitution = Substitution('%name1%', 'Example Name 1', p=0)
    message.substitution = Substitution('%city1%', 'Example City 1', p=0)
    message.substitution = [
        Substitution('%name2%', 'Example Name 2', p=0),
        Substitution('%city2%', 'Example City 2', p=0)
    ]

    message.custom_arg = CustomArg('marketing1', 'true', p=0)
    message.custom_arg = CustomArg('transactional1', 'false', p=0)
    message.custom_arg = [
        CustomArg('marketing2', 'false', p=0),
        CustomArg('transactional2', 'true', p=0)
    ]

    message.send_at = SendAt(1461775051, p=0)

    message.to = To('*****@*****.**', 'Example User10', p=1)
    message.to = [ 
        To('*****@*****.**', 'Example User11', p=1),
        To('*****@*****.**', 'Example User12', p=1)
    ]

    message.cc = Cc('*****@*****.**', 'Example User13', p=1)
    message.cc = [ 
        Cc('*****@*****.**', 'Example User14', p=1),
        Cc('*****@*****.**', 'Example User15', p=1)
    ]

    message.bcc = Bcc('*****@*****.**', 'Example User16', p=1)
    message.bcc = [ 
        Bcc('*****@*****.**', 'Example User17', p=1),
        Bcc('*****@*****.**', 'Example User18', p=1)
    ]

    message.header = Header('X-Test5', 'Test5', p=1)
    message.header = Header('X-Test6', 'Test6', p=1)
    message.header = [
        Header('X-Test7', 'Test7', p=1),
        Header('X-Test8', 'Test8', p=1)
    ]

    message.substitution = Substitution('%name3%', 'Example Name 3', p=1)
    message.substitution = Substitution('%city3%', 'Example City 3', p=1)
    message.substitution = [
        Substitution('%name4%', 'Example Name 4', p=1),
        Substitution('%city4%', 'Example City 4', p=1)
    ]

    message.custom_arg = CustomArg('marketing3', 'true', p=1)
    message.custom_arg = CustomArg('transactional3', 'false', p=1)
    message.custom_arg = [
        CustomArg('marketing4', 'false', p=1),
        CustomArg('transactional4', 'true', p=1)
    ]

    message.send_at = SendAt(1461775052, p=1)

    message.subject = Subject('Sending with SendGrid is Fun 1', p=1)

    # The values below this comment are global to entire message

    message.from_email = From('*****@*****.**', 'DX')

    message.reply_to = ReplyTo('*****@*****.**', 'DX Reply')

    message.subject = Subject('Sending with SendGrid is Fun 2')

    message.content = Content(MimeType.text, 'and easy to do anywhere, even with Python')
    message.content = Content(MimeType.html, '<strong>and easy to do anywhere, even with Python</strong>')
    message.content = [
        Content('text/calendar', 'Party Time!!'),
        Content('text/custom', 'Party Time 2!!')
    ]

    message.attachment = Attachment(FileContent('base64 encoded content 1'),
                                    FileType('application/pdf'),
                                    FileName('balance_001.pdf'),
                                    Disposition('attachment'),
                                    ContentId('Content ID 1'))
    message.attachment = [
        Attachment(FileContent('base64 encoded content 2'),
                FileType('image/png'),
                FileName('banner.png'),
                Disposition('inline'),
                ContentId('Content ID 2')),
        Attachment(FileContent('base64 encoded content 3'),
                FileType('image/png'),
                FileName('banner2.png'),
                Disposition('inline'),
                ContentId('Content ID 3'))
    ]

    message.template_id = TemplateId('13b8f94f-bcae-4ec6-b752-70d6cb59f932')

    message.section = Section('%section1%', 'Substitution for Section 1 Tag')
    message.section = [
        Section('%section2%', 'Substitution for Section 2 Tag'),
        Section('%section3%', 'Substitution for Section 3 Tag')    
    ]

    message.header = Header('X-Test9', 'Test9')
    message.header = Header('X-Test10', 'Test10')
    message.header = [
        Header('X-Test11', 'Test11'),
        Header('X-Test12', 'Test12')
    ]

    message.category = Category('Category 1')
    message.category = Category('Category 2')
    message.category = [
        Category('Category 1'),
        Category('Category 2')
    ]

    message.custom_arg = CustomArg('marketing5', 'false')
    message.custom_arg = CustomArg('transactional5', 'true')
    message.custom_arg = [
        CustomArg('marketing6', 'true'),
        CustomArg('transactional6', 'false')
    ]

    message.send_at = SendAt(1461775053)

    message.batch_id = BatchId("HkJ5yLYULb7Rj8GKSx7u025ouWVlMgAi")

    message.asm = Asm(GroupId(1), GroupsToDisplay([1,2,3,4]))

    message.ip_pool_name = IpPoolName("IP Pool Name")

    mail_settings = MailSettings()
    mail_settings.bcc_settings = BccSettings(False, BccSettingsTo("*****@*****.**"))
    mail_settings.bypass_list_management = BypassListManagement(False)
    mail_settings.footer_settings = FooterSettings(True, FooterText("w00t"), FooterHtml("<string>w00t!<strong>"))
    mail_settings.sandbox_mode = SandBoxMode(True)
    mail_settings.spam_check = SpamCheck(True, SpamThreshold(5), SpamUrl("https://example.com"))
    message.mail_settings = mail_settings

    tracking_settings = TrackingSettings()
    tracking_settings.click_tracking = ClickTracking(True, False)
    tracking_settings.open_tracking = OpenTracking(True, OpenTrackingSubstitutionTag("open_tracking"))
    tracking_settings.subscription_tracking = SubscriptionTracking(
        True, 
        SubscriptionText("Goodbye"),
        SubscriptionHtml("<strong>Goodbye!</strong>"),
        SubscriptionSubstitutionTag("unsubscribe"))
    tracking_settings.ganalytics = Ganalytics(
        True,
        UtmSource("utm_source"),
        UtmMedium("utm_medium"),
        UtmTerm("utm_term"),
        UtmContent("utm_content"),
        UtmCampaign("utm_campaign"))
    message.tracking_settings = tracking_settings

    return message.get()
示例#14
0
    CustomArg('transactional4', 'true', p=1)
]

message.send_at = SendAt(1461775052, p=1)

message.subject = Subject('Sending with SendGrid is Fun 1', p=1)

# The values below this comment are global to entire message

message.from_email = From('*****@*****.**', 'DX')

message.reply_to = ReplyTo('*****@*****.**', 'DX Reply')

message.subject = Subject('Sending with SendGrid is Fun 2')

message.content = Content(MimeType.text, 'and easy to do anywhere, even with Python')
message.content = Content(MimeType.html, '<strong>and easy to do anywhere, even with Python</strong>')
message.content = [
    Content('text/calendar', 'Party Time!!'),
    Content('text/custom', 'Party Time 2!!')
]

message.attachment = Attachment(FileContent('base64 encoded content 1'),
                                FileType('application/pdf'),
                                FileName('balance_001.pdf'),
                                Disposition('attachment'),
                                ContentId('Content ID 1'))
message.attachment = [
    Attachment(FileContent('base64 encoded content 2'),
               FileType('image/png'),
               FileName('banner.png'),
示例#15
0
import os
import json

import python_http_client
from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import Mail, From, To, Subject, PlainTextContent, HtmlContent, SendGridException

API_KEY = 'Hn6D'
TEMPLATE_ID = 'bf513'

message = Mail(subject=Subject("my subject"),
               from_email=From('*****@*****.**', 'sender'),
               to_emails=To('*****@*****.**', 'Vitalii'))
# message.template_id=TEMPLATE_ID
# message.dynamic_template_data = {"unsubscribe": "<<< unsubscribe custom text >>>", "unsubscribe_preferences": "<<< unsubscribe_preferences custom text >>>"}
message.content = PlainTextContent("this is test content")
try:
    sendgrid_client = SendGridAPIClient(API_KEY)
    print(json.dumps(message.get(), sort_keys=True, indent=4))
    response = sendgrid_client.send(message=message)
    if 300 > response.status_code >= 200:
        print(response.status_code)
        print(response.body)
except SendGridException as e:
    print(e.message)
except python_http_client.exceptions.HTTPError as e:
    print(e.body)
示例#16
0
def SendEmails(HubPullRequest, EmailContents, SendMethod):
    if SendMethod == 'SMTP':
        #
        # Send emails to SMTP Server
        #
        try:
            SmtpServer = smtplib.SMTP(SMTP_ADDRESS, SMTP_PORT_NUMBER)
            SmtpServer.starttls()
            SmtpServer.ehlo()
            SmtpServer.login(SMTP_USER_NAME, SMTP_PASSWORD)
            Index = 0
            for Email in EmailContents:
                Index = Index + 1
                EmailMessage = email.message_from_string(Email)
                print('pr[%d] email[%d]' % (HubPullRequest.number, Index),
                      '----> SMTP Email Start <----')
                print(Email)
                print('pr[%d] email[%d]' % (HubPullRequest.number, Index),
                      '----> SMTP Email End <----')
                if 'From' in EmailMessage:
                    try:
                        FromAddress, FromName = ParseEmailAddress(
                            EmailMessage['From'])
                    except:
                        print('Parsed From: Bad address:',
                              EmailMessage['From'])
                        FromAddress = '*****@*****.**'
                        FromName = 'From %s via TianoCore Webhook' % (
                            HubPullRequest.user.login)
                else:
                    print('Parsed From: Missing address:')
                    FromAddress = '*****@*****.**'
                    FromName = 'From %s via TianoCore Webhook' % (
                        HubPullRequest.user.login)
                ToList = []
                if 'To' in EmailMessage:
                    ToList = ToList + EmailMessage['To'].split(',')
                if 'Cc' in EmailMessage:
                    ToList = ToList + EmailMessage['Cc'].split(',')
                try:
                    SmtpServer.sendmail(FromAddress, ToList, Email)
                    print('SMTP send mail success')
                except:
                    print('ERROR: SMTP send mail failed')
            SmtpServer.quit()
        except:
            print(
                'SendEmails: error: can not connect or login or send messages.'
            )
    elif SendMethod == 'SendGrid':
        #
        # Send emails to SendGrid
        #
        Index = 0
        for Email in EmailContents:
            Index = Index + 1
            EmailMessage = email.message_from_string(Email)
            print('pr[%d] email[%d]' % (HubPullRequest.number, Index),
                  '----> SendGrid Email Start <----')
            print(Email)
            print('pr[%d] email[%d]' % (HubPullRequest.number, Index),
                  '----> SendGrid Email End   <----')
            message = Mail()
            if 'From' in EmailMessage:
                try:
                    EmailAddress, EmailName = ParseEmailAddress(
                        EmailMessage['From'])
                    message.from_email = From(EmailAddress, EmailName)
                except:
                    print('Parsed From: Bad address:', EmailMessage['From'])
                    message.from_email = From(
                        '*****@*****.**',
                        'From %s via TianoCore Webhook' %
                        (HubPullRequest.user.login))
            else:
                print('Parsed From: Missing address:')
                message.from_email = From(
                    '*****@*****.**', 'From %s via TianoCore Webhook' %
                    (HubPullRequest.user.login))
            UniqueAddressList = []
            if 'To' in EmailMessage:
                for Address in EmailMessage['To'].split(','):
                    try:
                        EmailAddress, EmailName = ParseEmailAddress(Address)
                        if EmailAddress.lower() in UniqueAddressList:
                            continue
                        UniqueAddressList.append(EmailAddress.lower())
                        message.add_to(To(EmailAddress, EmailName))
                    except:
                        print('Parsed To: Bad address:', Address)
                        continue
            if 'Cc' in EmailMessage:
                for Address in EmailMessage['Cc'].split(','):
                    try:
                        EmailAddress, EmailName = ParseEmailAddress(Address)
                        if EmailAddress.lower() in UniqueAddressList:
                            continue
                        UniqueAddressList.append(EmailAddress.lower())
                        message.add_cc(Cc(EmailAddress, EmailName))
                    except:
                        print('Parsed Cc: Bad address:', Address)
                        continue
            message.subject = Subject(EmailMessage['Subject'])
            for Field in ['Message-Id', 'In-Reply-To']:
                if Field in EmailMessage:
                    message.header = Header(Field, EmailMessage[Field])
            message.content = Content(MimeType.text,
                                      EmailMessage.get_payload())
            try:
                sendgrid_client = SendGridAPIClient(SENDGRID_API_KEY)
                response = sendgrid_client.send(message)
                print('SendGridAPIClient send success')
                time.sleep(1)
            except Exception as e:
                print('ERROR: SendGridAPIClient failed')
    else:
        Index = 0
        for Email in EmailContents:
            Index = Index + 1
            EmailMessage = email.message_from_string(Email)
            print('pr[%d] email[%d]' % (HubPullRequest.number, Index),
                  '----> Draft Email Start <----')
            if 'From' in EmailMessage:
                try:
                    EmailAddress, EmailName = ParseEmailAddress(
                        EmailMessage['From'])
                    print('Parsed From:', EmailAddress, EmailName)
                except:
                    print('Parsed From: Bad address:', EmailMessage['From'])
            else:
                print('Parsed From: Missing address:')
            UniqueAddressList = []
            if 'To' in EmailMessage:
                for Address in EmailMessage['To'].split(','):
                    try:
                        EmailAddress, EmailName = ParseEmailAddress(Address)
                        if EmailAddress.lower() in UniqueAddressList:
                            continue
                        UniqueAddressList.append(EmailAddress.lower())
                        print('Parsed To:', EmailAddress, EmailName)
                    except:
                        print('Parsed To: Bad address:', Address)
                        continue
            if 'Cc' in EmailMessage:
                for Address in EmailMessage['Cc'].split(','):
                    try:
                        EmailAddress, EmailName = ParseEmailAddress(Address)
                        if EmailAddress.lower() in UniqueAddressList:
                            continue
                        UniqueAddressList.append(EmailAddress.lower())
                        print('Parsed Cc:', EmailAddress, EmailName)
                    except:
                        print('Parsed Cc: Bad address:', Address)
                        continue
            print('--------------------')
            print(Email)
            print('pr[%d] email[%d]' % (HubPullRequest.number, Index),
                  '----> Draft Email End   <----')
示例#17
0
    CustomArg('transactional4', 'true', p=1)
]

message.send_at = SendAt(1461775052, p=1)

message.subject = Subject('Sending with SendGrid is Fun 1', p=1)

# The values below this comment are global to entire message

message.from_email = From('*****@*****.**', 'DX')

message.reply_to = ReplyTo('*****@*****.**', 'DX Reply')

message.subject = Subject('Sending with SendGrid is Fun 2')

message.content = Content(MimeType.text,
                          'and easy to do anywhere, even with Python')
message.content = Content(
    MimeType.html,
    '<strong>and easy to do anywhere, even with Python</strong>')
message.content = [
    Content('text/calendar', 'Party Time!!'),
    Content('text/custom', 'Party Time 2!!')
]

message.attachment = Attachment(FileContent('base64 encoded content 1'),
                                FileType('application/pdf'),
                                FileName('balance_001.pdf'),
                                Disposition('attachment'),
                                ContentId('Content ID 1'))
message.attachment = [
    Attachment(FileContent('base64 encoded content 2'), FileType('image/png'),
示例#18
0
def build_kitchen_sink():
    """All settings set"""
    from sendgrid.helpers.mail import (
        Mail, From, To, Cc, Bcc, Subject, PlainTextContent, 
        HtmlContent, SendGridException, Substitution, 
        Header, CustomArg, SendAt, Content, MimeType, Attachment,
        FileName, FileContent, FileType, Disposition, ContentId,
        TemplateId, Section, ReplyTo, Category, BatchId, Asm,
        GroupId, GroupsToDisplay, IpPoolName, MailSettings,
        BccSettings, BccSettingsEmail, BypassListManagement,
        FooterSettings, FooterText, FooterHtml, SandBoxMode,
        SpamCheck, SpamThreshold, SpamUrl, TrackingSettings,
        ClickTracking, SubscriptionTracking, SubscriptionText,
        SubscriptionHtml, SubscriptionSubstitutionTag,
        OpenTracking, OpenTrackingSubstitutionTag, Ganalytics,
        UtmSource, UtmMedium, UtmTerm, UtmContent, UtmCampaign)
    import time
    import datetime

    message = Mail()

    # Define Personalizations 

    message.to = To('*****@*****.**', 'Example User1', p=0)
    message.to = [ 
        To('*****@*****.**', 'Example User2', p=0),
        To('*****@*****.**', 'Example User3', p=0)
    ]

    message.cc = Cc('*****@*****.**', 'Example User4', p=0)
    message.cc = [ 
        Cc('*****@*****.**', 'Example User5', p=0),
        Cc('*****@*****.**', 'Example User6', p=0)
    ]

    message.bcc = Bcc('*****@*****.**', 'Example User7', p=0)
    message.bcc = [ 
        Bcc('*****@*****.**', 'Example User8', p=0),
        Bcc('*****@*****.**', 'Example User9', p=0)
    ]

    message.subject = Subject('Sending with SendGrid is Fun 0', p=0)

    message.header = Header('X-Test1', 'Test1', p=0)
    message.header = Header('X-Test2', 'Test2', p=0)
    message.header = [
        Header('X-Test3', 'Test3', p=0),
        Header('X-Test4', 'Test4', p=0)
    ]

    message.substitution = Substitution('%name1%', 'Example Name 1', p=0)
    message.substitution = Substitution('%city1%', 'Example City 1', p=0)
    message.substitution = [
        Substitution('%name2%', 'Example Name 2', p=0),
        Substitution('%city2%', 'Example City 2', p=0)
    ]

    message.custom_arg = CustomArg('marketing1', 'true', p=0)
    message.custom_arg = CustomArg('transactional1', 'false', p=0)
    message.custom_arg = [
        CustomArg('marketing2', 'false', p=0),
        CustomArg('transactional2', 'true', p=0)
    ]

    message.send_at = SendAt(1461775051, p=0)

    message.to = To('*****@*****.**', 'Example User10', p=1)
    message.to = [ 
        To('*****@*****.**', 'Example User11', p=1),
        To('*****@*****.**', 'Example User12', p=1)
    ]

    message.cc = Cc('*****@*****.**', 'Example User13', p=1)
    message.cc = [ 
        Cc('*****@*****.**', 'Example User14', p=1),
        Cc('*****@*****.**', 'Example User15', p=1)
    ]

    message.bcc = Bcc('*****@*****.**', 'Example User16', p=1)
    message.bcc = [ 
        Bcc('*****@*****.**', 'Example User17', p=1),
        Bcc('*****@*****.**', 'Example User18', p=1)
    ]

    message.header = Header('X-Test5', 'Test5', p=1)
    message.header = Header('X-Test6', 'Test6', p=1)
    message.header = [
        Header('X-Test7', 'Test7', p=1),
        Header('X-Test8', 'Test8', p=1)
    ]

    message.substitution = Substitution('%name3%', 'Example Name 3', p=1)
    message.substitution = Substitution('%city3%', 'Example City 3', p=1)
    message.substitution = [
        Substitution('%name4%', 'Example Name 4', p=1),
        Substitution('%city4%', 'Example City 4', p=1)
    ]

    message.custom_arg = CustomArg('marketing3', 'true', p=1)
    message.custom_arg = CustomArg('transactional3', 'false', p=1)
    message.custom_arg = [
        CustomArg('marketing4', 'false', p=1),
        CustomArg('transactional4', 'true', p=1)
    ]

    message.send_at = SendAt(1461775052, p=1)

    message.subject = Subject('Sending with SendGrid is Fun 1', p=1)

    # The values below this comment are global to entire message

    message.from_email = From('*****@*****.**', 'DX')

    message.reply_to = ReplyTo('*****@*****.**', 'DX Reply')

    message.subject = Subject('Sending with SendGrid is Fun 2')

    message.content = Content(MimeType.text, 'and easy to do anywhere, even with Python')
    message.content = Content(MimeType.html, '<strong>and easy to do anywhere, even with Python</strong>')
    message.content = [
        Content('text/calendar', 'Party Time!!'),
        Content('text/custom', 'Party Time 2!!')
    ]

    message.attachment = Attachment(FileContent('base64 encoded content 1'),
                                    FileType('application/pdf'),
                                    FileName('balance_001.pdf'),
                                    Disposition('attachment'),
                                    ContentId('Content ID 1'))
    message.attachment = [
        Attachment(FileContent('base64 encoded content 2'),
                FileType('image/png'),
                FileName('banner.png'),
                Disposition('inline'),
                ContentId('Content ID 2')),
        Attachment(FileContent('base64 encoded content 3'),
                FileType('image/png'),
                FileName('banner2.png'),
                Disposition('inline'),
                ContentId('Content ID 3'))
    ]

    message.template_id = TemplateId('13b8f94f-bcae-4ec6-b752-70d6cb59f932')

    message.section = Section('%section1%', 'Substitution for Section 1 Tag')
    message.section = [
        Section('%section2%', 'Substitution for Section 2 Tag'),
        Section('%section3%', 'Substitution for Section 3 Tag')    
    ]

    message.header = Header('X-Test9', 'Test9')
    message.header = Header('X-Test10', 'Test10')
    message.header = [
        Header('X-Test11', 'Test11'),
        Header('X-Test12', 'Test12')
    ]

    message.category = Category('Category 1')
    message.category = Category('Category 2')
    message.category = [
        Category('Category 1'),
        Category('Category 2')
    ]

    message.custom_arg = CustomArg('marketing5', 'false')
    message.custom_arg = CustomArg('transactional5', 'true')
    message.custom_arg = [
        CustomArg('marketing6', 'true'),
        CustomArg('transactional6', 'false')
    ]

    message.send_at = SendAt(1461775053)

    message.batch_id = BatchId("HkJ5yLYULb7Rj8GKSx7u025ouWVlMgAi")

    message.asm = Asm(GroupId(1), GroupsToDisplay([1,2,3,4]))

    message.ip_pool_name = IpPoolName("IP Pool Name")

    mail_settings = MailSettings()
    mail_settings.bcc_settings = BccSettings(False, BccSettingsEmail("*****@*****.**"))
    mail_settings.bypass_list_management = BypassListManagement(False)
    mail_settings.footer_settings = FooterSettings(True, FooterText("w00t"), FooterHtml("<string>w00t!<strong>"))
    mail_settings.sandbox_mode = SandBoxMode(True)
    mail_settings.spam_check = SpamCheck(True, SpamThreshold(5), SpamUrl("https://example.com"))
    message.mail_settings = mail_settings

    tracking_settings = TrackingSettings()
    tracking_settings.click_tracking = ClickTracking(True, False)
    tracking_settings.open_tracking = OpenTracking(True, OpenTrackingSubstitutionTag("open_tracking"))
    tracking_settings.subscription_tracking = SubscriptionTracking(
        True, 
        SubscriptionText("Goodbye"),
        SubscriptionHtml("<strong>Goodbye!</strong>"),
        SubscriptionSubstitutionTag("unsubscribe"))
    tracking_settings.ganalytics = Ganalytics(
        True,
        UtmSource("utm_source"),
        UtmMedium("utm_medium"),
        UtmTerm("utm_term"),
        UtmContent("utm_content"),
        UtmCampaign("utm_campaign"))
    message.tracking_settings = tracking_settings

    return message.get()
    def test_kitchen_sink(self):
        from sendgrid.helpers.mail import (
            Mail, From, To, Cc, Bcc, Subject, Substitution, Header,
            CustomArg, SendAt, Content, MimeType, Attachment, FileName,
            FileContent, FileType, Disposition, ContentId, TemplateId,
            Section, ReplyTo, Category, BatchId, Asm, GroupId, GroupsToDisplay,
            IpPoolName, MailSettings, BccSettings, BccSettingsEmail,
            BypassListManagement, FooterSettings, FooterText,
            FooterHtml, SandBoxMode, SpamCheck, SpamThreshold, SpamUrl,
            TrackingSettings, ClickTracking, SubscriptionTracking,
            SubscriptionText, SubscriptionHtml, SubscriptionSubstitutionTag,
            OpenTracking, OpenTrackingSubstitutionTag, Ganalytics,
            UtmSource, UtmMedium, UtmTerm, UtmContent, UtmCampaign)

        self.maxDiff = None

        message = Mail()

        # Define Personalizations

        message.to = To('*****@*****.**', 'Example User1', p=0)
        message.to = [
            To('*****@*****.**', 'Example User2', p=0),
            To('*****@*****.**', 'Example User3', p=0)
        ]

        message.cc = Cc('*****@*****.**', 'Example User4', p=0)
        message.cc = [
            Cc('*****@*****.**', 'Example User5', p=0),
            Cc('*****@*****.**', 'Example User6', p=0)
        ]

        message.bcc = Bcc('*****@*****.**', 'Example User7', p=0)
        message.bcc = [
            Bcc('*****@*****.**', 'Example User8', p=0),
            Bcc('*****@*****.**', 'Example User9', p=0)
        ]

        message.subject = Subject('Sending with SendGrid is Fun 0', p=0)

        message.header = Header('X-Test1', 'Test1', p=0)
        message.header = Header('X-Test2', 'Test2', p=0)
        message.header = [
            Header('X-Test3', 'Test3', p=0),
            Header('X-Test4', 'Test4', p=0)
        ]

        message.substitution = Substitution('%name1%', 'Example Name 1', p=0)
        message.substitution = Substitution('%city1%', 'Example City 1', p=0)
        message.substitution = [
            Substitution('%name2%', 'Example Name 2', p=0),
            Substitution('%city2%', 'Example City 2', p=0)
        ]

        message.custom_arg = CustomArg('marketing1', 'true', p=0)
        message.custom_arg = CustomArg('transactional1', 'false', p=0)
        message.custom_arg = [
            CustomArg('marketing2', 'false', p=0),
            CustomArg('transactional2', 'true', p=0)
        ]

        message.send_at = SendAt(1461775051, p=0)

        message.to = To('*****@*****.**', 'Example User10', p=1)
        message.to = [
            To('*****@*****.**', 'Example User11', p=1),
            To('*****@*****.**', 'Example User12', p=1)
        ]

        message.cc = Cc('*****@*****.**', 'Example User13', p=1)
        message.cc = [
            Cc('*****@*****.**', 'Example User14', p=1),
            Cc('*****@*****.**', 'Example User15', p=1)
        ]

        message.bcc = Bcc('*****@*****.**', 'Example User16', p=1)
        message.bcc = [
            Bcc('*****@*****.**', 'Example User17', p=1),
            Bcc('*****@*****.**', 'Example User18', p=1)
        ]

        message.header = Header('X-Test5', 'Test5', p=1)
        message.header = Header('X-Test6', 'Test6', p=1)
        message.header = [
            Header('X-Test7', 'Test7', p=1),
            Header('X-Test8', 'Test8', p=1)
        ]

        message.substitution = Substitution('%name3%', 'Example Name 3', p=1)
        message.substitution = Substitution('%city3%', 'Example City 3', p=1)
        message.substitution = [
            Substitution('%name4%', 'Example Name 4', p=1),
            Substitution('%city4%', 'Example City 4', p=1)
        ]

        message.custom_arg = CustomArg('marketing3', 'true', p=1)
        message.custom_arg = CustomArg('transactional3', 'false', p=1)
        message.custom_arg = [
            CustomArg('marketing4', 'false', p=1),
            CustomArg('transactional4', 'true', p=1)
        ]

        message.send_at = SendAt(1461775052, p=1)

        message.subject = Subject('Sending with SendGrid is Fun 1', p=1)

        # The values below this comment are global to entire message

        message.from_email = From('*****@*****.**', 'DX')

        message.reply_to = ReplyTo('*****@*****.**', 'DX Reply')

        message.subject = Subject('Sending with SendGrid is Fun 2')

        message.content = Content(
            MimeType.text,
            'and easy to do anywhere, even with Python')
        message.content = Content(
            MimeType.html,
            '<strong>and easy to do anywhere, even with Python</strong>')
        message.content = [
            Content('text/calendar', 'Party Time!!'),
            Content('text/custom', 'Party Time 2!!')
        ]

        message.attachment = Attachment(
            FileContent('base64 encoded content 1'),
            FileName('balance_001.pdf'),
            FileType('application/pdf'),
            Disposition('attachment'),
            ContentId('Content ID 1'))
        message.attachment = [
            Attachment(
                FileContent('base64 encoded content 2'),
                FileName('banner.png'),
                FileType('image/png'),
                Disposition('inline'),
                ContentId('Content ID 2')),
            Attachment(
                FileContent('base64 encoded content 3'),
                FileName('banner2.png'),
                FileType('image/png'),
                Disposition('inline'),
                ContentId('Content ID 3'))
        ]

        message.template_id = TemplateId(
            '13b8f94f-bcae-4ec6-b752-70d6cb59f932')

        message.section = Section(
            '%section1%', 'Substitution for Section 1 Tag')
        message.section = [
            Section('%section2%', 'Substitution for Section 2 Tag'),
            Section('%section3%', 'Substitution for Section 3 Tag')
        ]

        message.header = Header('X-Test9', 'Test9')
        message.header = Header('X-Test10', 'Test10')
        message.header = [
            Header('X-Test11', 'Test11'),
            Header('X-Test12', 'Test12')
        ]

        message.category = Category('Category 1')
        message.category = Category('Category 2')
        message.category = [
            Category('Category 1'),
            Category('Category 2')
        ]

        message.custom_arg = CustomArg('marketing5', 'false')
        message.custom_arg = CustomArg('transactional5', 'true')
        message.custom_arg = [
            CustomArg('marketing6', 'true'),
            CustomArg('transactional6', 'false')
        ]

        message.send_at = SendAt(1461775053)

        message.batch_id = BatchId("HkJ5yLYULb7Rj8GKSx7u025ouWVlMgAi")

        message.asm = Asm(GroupId(1), GroupsToDisplay([1, 2, 3, 4]))

        message.ip_pool_name = IpPoolName("IP Pool Name")

        mail_settings = MailSettings()
        mail_settings.bcc_settings = BccSettings(
            False, BccSettingsEmail("*****@*****.**"))
        mail_settings.bypass_list_management = BypassListManagement(False)
        mail_settings.footer_settings = FooterSettings(
            True, FooterText("w00t"), FooterHtml("<string>w00t!<strong>"))
        mail_settings.sandbox_mode = SandBoxMode(True)
        mail_settings.spam_check = SpamCheck(
            True, SpamThreshold(5), SpamUrl("https://example.com"))
        message.mail_settings = mail_settings

        tracking_settings = TrackingSettings()
        tracking_settings.click_tracking = ClickTracking(True, False)
        tracking_settings.open_tracking = OpenTracking(
            True, OpenTrackingSubstitutionTag("open_tracking"))
        tracking_settings.subscription_tracking = SubscriptionTracking(
            True,
            SubscriptionText("Goodbye"),
            SubscriptionHtml("<strong>Goodbye!</strong>"),
            SubscriptionSubstitutionTag("unsubscribe"))
        tracking_settings.ganalytics = Ganalytics(
            True,
            UtmSource("utm_source"),
            UtmMedium("utm_medium"),
            UtmTerm("utm_term"),
            UtmContent("utm_content"),
            UtmCampaign("utm_campaign"))
        message.tracking_settings = tracking_settings
        self.assertEqual(
            message.get(),
            json.loads(r'''{
                "asm": {
                    "group_id": 1,
                    "groups_to_display": [
                        1,
                        2,
                        3,
                        4
                    ]
                },
                "attachments": [
                    {
                        "content": "base64 encoded content 3",
                        "content_id": "Content ID 3",
                        "disposition": "inline",
                        "filename": "banner2.png",
                        "type": "image/png"
                    },
                    {
                        "content": "base64 encoded content 2",
                        "content_id": "Content ID 2",
                        "disposition": "inline",
                        "filename": "banner.png",
                        "type": "image/png"
                    },
                    {
                        "content": "base64 encoded content 1",
                        "content_id": "Content ID 1",
                        "disposition": "attachment",
                        "filename": "balance_001.pdf",
                        "type": "application/pdf"
                    }
                ],
                "batch_id": "HkJ5yLYULb7Rj8GKSx7u025ouWVlMgAi",
                "categories": [
                    "Category 2",
                    "Category 1",
                    "Category 2",
                    "Category 1"
                ],
                "content": [
                    {
                        "type": "text/plain",
                        "value": "and easy to do anywhere, even with Python"
                    },
                    {
                        "type": "text/html",
                        "value": "<strong>and easy to do anywhere, even with Python</strong>"
                    },
                    {
                        "type": "text/calendar",
                        "value": "Party Time!!"
                    },
                    {
                        "type": "text/custom",
                        "value": "Party Time 2!!"
                    }
                ],
                "custom_args": {
                    "marketing5": "false",
                    "marketing6": "true",
                    "transactional5": "true",
                    "transactional6": "false"
                },
                "from": {
                    "email": "*****@*****.**",
                    "name": "DX"
                },
                "headers": {
                    "X-Test10": "Test10",
                    "X-Test11": "Test11",
                    "X-Test12": "Test12",
                    "X-Test9": "Test9"
                },
                "ip_pool_name": "IP Pool Name",
                "mail_settings": {
                    "bcc": {
                        "email": "*****@*****.**",
                        "enable": false
                    },
                    "bypass_list_management": {
                        "enable": false
                    },
                    "footer": {
                        "enable": true,
                        "html": "<string>w00t!<strong>",
                        "text": "w00t"
                    },
                    "sandbox_mode": {
                        "enable": true
                    },
                    "spam_check": {
                        "enable": true,
                        "post_to_url": "https://example.com",
                        "threshold": 5
                    }
                },
                "personalizations": [
                    {
                        "bcc": [
                            {
                                "email": "*****@*****.**",
                                "name": "Example User7"
                            },
                            {
                                "email": "*****@*****.**",
                                "name": "Example User8"
                            },
                            {
                                "email": "*****@*****.**",
                                "name": "Example User9"
                            }
                        ],
                        "cc": [
                            {
                                "email": "*****@*****.**",
                                "name": "Example User4"
                            },
                            {
                                "email": "*****@*****.**",
                                "name": "Example User5"
                            },
                            {
                                "email": "*****@*****.**",
                                "name": "Example User6"
                            }
                        ],
                        "custom_args": {
                            "marketing1": "true",
                            "marketing2": "false",
                            "transactional1": "false",
                            "transactional2": "true"
                        },
                        "headers": {
                            "X-Test1": "Test1",
                            "X-Test2": "Test2",
                            "X-Test3": "Test3",
                            "X-Test4": "Test4"
                        },
                        "send_at": 1461775051,
                        "subject": "Sending with SendGrid is Fun 0",
                        "substitutions": {
                            "%city1%": "Example City 1",
                            "%city2%": "Example City 2",
                            "%name1%": "Example Name 1",
                            "%name2%": "Example Name 2"
                        },
                        "to": [
                            {
                                "email": "*****@*****.**",
                                "name": "Example User1"
                            },
                            {
                                "email": "*****@*****.**",
                                "name": "Example User2"
                            },
                            {
                                "email": "*****@*****.**",
                                "name": "Example User3"
                            }
                        ]
                    },
                    {
                        "bcc": [
                            {
                                "email": "*****@*****.**",
                                "name": "Example User16"
                            },
                            {
                                "email": "*****@*****.**",
                                "name": "Example User17"
                            },
                            {
                                "email": "*****@*****.**",
                                "name": "Example User18"
                            }
                        ],
                        "cc": [
                            {
                                "email": "*****@*****.**",
                                "name": "Example User13"
                            },
                            {
                                "email": "*****@*****.**",
                                "name": "Example User14"
                            },
                            {
                                "email": "*****@*****.**",
                                "name": "Example User15"
                            }
                        ],
                        "custom_args": {
                            "marketing3": "true",
                            "marketing4": "false",
                            "transactional3": "false",
                            "transactional4": "true"
                        },
                        "headers": {
                            "X-Test5": "Test5",
                            "X-Test6": "Test6",
                            "X-Test7": "Test7",
                            "X-Test8": "Test8"
                        },
                        "send_at": 1461775052,
                        "subject": "Sending with SendGrid is Fun 1",
                        "substitutions": {
                            "%city3%": "Example City 3",
                            "%city4%": "Example City 4",
                            "%name3%": "Example Name 3",
                            "%name4%": "Example Name 4"
                        },
                        "to": [
                            {
                                "email": "*****@*****.**",
                                "name": "Example User10"
                            },
                            {
                                "email": "*****@*****.**",
                                "name": "Example User11"
                            },
                            {
                                "email": "*****@*****.**",
                                "name": "Example User12"
                            }
                        ]
                    }
                ],
                "reply_to": {
                    "email": "*****@*****.**",
                    "name": "DX Reply"
                },
                "sections": {
                    "%section1%": "Substitution for Section 1 Tag",
                    "%section2%": "Substitution for Section 2 Tag",
                    "%section3%": "Substitution for Section 3 Tag"
                },
                "send_at": 1461775053,
                "subject": "Sending with SendGrid is Fun 2",
                "template_id": "13b8f94f-bcae-4ec6-b752-70d6cb59f932",
                "tracking_settings": {
                    "click_tracking": {
                        "enable": true,
                        "enable_text": false
                    },
                    "ganalytics": {
                        "enable": true,
                        "utm_campaign": "utm_campaign",
                        "utm_content": "utm_content",
                        "utm_medium": "utm_medium",
                        "utm_source": "utm_source",
                        "utm_term": "utm_term"
                    },
                    "open_tracking": {
                        "enable": true,
                        "substitution_tag": "open_tracking"
                    },
                    "subscription_tracking": {
                        "enable": true,
                        "html": "<strong>Goodbye!</strong>",
                        "substitution_tag": "unsubscribe",
                        "text": "Goodbye"
                    }
                }
            }''')
        )