Exemplo n.º 1
0
    def create_mail(self,
                    tos,
                    subject,
                    template,
                    context,
                    template_type="text/html",
                    sender=None):
        if sender == None:
            sender = Config.DEFAULT_SENDGRID_SENDER
        html_content, text_content = None, None
        if template_type == "all":
            html_content = render_template(template, **context)
            text_content = render_template(template, **context)
        elif template_type == "text/html":
            html_content = render_template(template, **context)

        elif template_type == "text/plain":
            text_content = render_template(template, **context)
        else:
            raise ValueError("Invalid Content Type")
        message = Mail(
            from_email=sender,
            to_emails=tos,
            subject=subject,
        )

        if html_content:
            message.add_content(html_content, MimeType.html)
        if text_content:
            message.add_content(text_content, MimeType.text)
        return message
Exemplo n.º 2
0
    def send_email_report(new_items):
        from sendgrid import SendGridAPIClient
        from sendgrid.helpers.mail import (Mail, MimeType, Attachment,
                                           FileContent, FileName, FileType,
                                           Disposition, ContentId)
        import base64

        email_config = GitHubMonitor.__load_email_config()
        if not email_config or not new_items:
            return
        try:
            # construct email
            email = Mail()
            email.from_email = email_config.sender
            for recipient in email_config.recipients:
                email.add_to(recipient)
            today = time.strftime('%Y-%m-%d', time.localtime())
            email.subject = f"[{today}] GitHub Monitoring Report"
            email.add_content(GitHubMonitor.generate_html_report(new_items),
                              MimeType.html)
            # send email
            sendgrid = SendGridAPIClient(email_config.api_key)
            logger.info(f"Sending email report...")
            r = sendgrid.send(email)
            if r.status_code > 400:
                logger.error(f"SendGrid API failed: error={r.status_code}")
        except Exception as e:
            logger.error(f"Failed to send Site SSL Report: {e}")
Exemplo n.º 3
0
    def test_helloEmail(self):
        self.maxDiff = None
        """Minimum required to send an email"""
        mail = Mail()

        mail.from_email = Email("*****@*****.**")

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

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

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

        self.assertEqual(
            json.dumps(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"}')
Exemplo n.º 4
0
    def get(self, request, *args, **kwargs):
        self.template = self.get_object(kwargs.get('tp_pk'))
        self.person = self.get_person(kwargs.get('to_pk'), kwargs.get('tp_pk'))

        mail = Mail()
        mail.set_from(Email(self.request.user.email))
        mail.set_subject(self.template.title)

        personalization = Personalization()
        personalization.add_to(Email(self.person.email))
        mail.add_personalization(personalization)

        body = self.render_body(self.person.name, self.template.template_email.path)
        mail.add_content(Content("text/html", body))

        if self.template.attachment:
            path = self.template.attachment.path
            ext = path.split('.')[-1]
            with open(path, "rb") as f:
                mail.add_attachment(self.attach_file(
                    f, ext, self.template.slug, self.template.title))

        self.sg.client.mail.send.post(request_body=mail.get())
        messages.info(
            request,
            """You have just send an email to <strong>{0.email}</strong>
            with the subject <strong>{1}</strong>
            """
            .format(self.person, self.template.title))

        self.person.email_sent = True
        self.person.save()

        return super(SendEmailView, self).get(request, *args, **kwargs)
Exemplo n.º 5
0
    def get_message(self, **kwargs):
        """
        Get message object for email
        """
        config = get_configurations()
        message = Mail()
        if "from_email" in kwargs:
            sender = Email()
            message_content = kwargs.get("message_content", "")
            sender.name = kwargs.get("sender", config['SENDGRID']['sender'])
            sender.email = kwargs.get("from_email",
                                      config['SENDGRID']['fromemail'])
            message.from_email = sender
        if "subject" in kwargs:
            message.subject = kwargs.get("subject", "")
        if "text" in kwargs:
            content = Content("text/plain", kwargs.get("text", ""))
            message.add_content(content)
        if "html" in kwargs:
            content = Content("text/html", kwargs.get("html", ""))
            message.add_content(content)
        if "category" in kwargs:
            category = Category(kwargs.get("category", ""))
            message.add_category(category)

        personalization = self.create_personalization(**kwargs)
        if personalization:
            message.add_personalization(personalization)

        return message.get()
    def send_forgot_password_email(self, name: str, email: str,
                                   new_password: str) -> bool:
        """
        Send email to a user containing their new system generated password
        """

        text_version = self.text_template.format(username=name,
                                                 password=new_password)
        html_version = flask.render_template(self.html_template,
                                             username=name,
                                             password=new_password)

        sg = sendgrid.SendGridAPIClient(apikey=self.api_key)

        from_email = Email(self.sender_email)
        to_email = Email(email)
        subject = self.email_subject
        content_text = Content("text/plain", text_version)
        send_new_password_email = Mail(from_email, subject, to_email,
                                       content_text)
        content_html = Content("text/html", html_version)
        send_new_password_email.add_content(content_html)

        try:
            email_response = sg.client.mail.send.post(
                request_body=send_new_password_email.get())
            logger.info("Sent forgot password email to {} with "
                        "response code : {}".format(
                            email, email_response.status_code))
            return True
        except http.client.IncompleteRead as e:
            logger.error("Sendgrid API Key may not be set correctly", e)
            return False
Exemplo n.º 7
0
Arquivo: email.py Projeto: serbyy/blog
def send_email(subject, sender, recipients, text_body, html_body):
    message = Mail(
        from_email=sender,
        # to_emails=recipients,
        subject=subject,
        html_content=Content('text/html', html_body))
    txt_content = Content('text/txt', text_body)
    message.add_content(txt_content)

    #for personalization so you can't see other people sent email
    for r in recipients:
        person = Personalization()
        person.add_to(Email(r))
        message.add_personalization(person)

    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
Exemplo n.º 8
0
    def send_email_message(self, recipient, subject, html_message, text_message, sender_email, sender_name):
        """ Send email message via sendgrid-python.

        Args:
            recipient: Email address or tuple of (Name, Email-address).
            subject: Subject line.
            html_message: The message body in HTML.
            text_message: The message body in plain text.
        """

        if not current_app.testing:  # pragma: no cover
            try:
                # Prepare Sendgrid helper objects
                from sendgrid.helpers.mail import Email, Content, Substitution, Mail
                from_email = Email(sender_email, sender_name)
                to_email = Email(recipient)
                text_content = Content('text/plain', text_message)
                html_content = Content('text/html', html_message)
                # Prepare Sendgrid Mail object
                # Note: RFC 1341: text must be first, followed by html
                mail = Mail(from_email, subject, to_email, text_content)
                mail.add_content(html_content)
                # Send mail via the Sendgrid API
                response = self.sg.client.mail.send.post(request_body=mail.get())
                print(response.status_code)
                print(response.body)
                print(response.headers)
            except ImportError:
                raise ConfigError(SENDGRID_IMPORT_ERROR_MESSAGE)
            except Exception as e:
                print(e)
                print(e.body)
                raise
Exemplo n.º 9
0
    def test_helloEmail(self):
        self.maxDiff = None

        """Minimum required to send an email"""
        mail = Mail()

        mail.from_email = Email("*****@*****.**")

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

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

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

        self.assertEqual(
            json.dumps(
                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"}'
        )

        self.assertTrue(isinstance(str(mail), str))
Exemplo n.º 10
0
    def send_notification(self, to_subdata=None, notify_type=None, data=None):
        """ Sends a notification to a specific user

        Keyword args:
           to_subdata:       the subscription data for this transport
           to_username(str): the user we're sending to
           notify_type(str): the type of notification we're sending
           data(dict):       a dictionary containing the raw data for the notification

        Note:
           the subscription data for sendgrid is simply an email address
        """
        logger.debug('SendGrid sending notification to %s', to_subdata)
        from_email = Email('*****@*****.**', 'steemit.com')

        try:
            mail_content = self.renderer.render(notify_type, data)
        except Exception:
            logger.exception(
                'Exception occurred when rendering email template')
            return

        mail = Mail(from_email)
        mail.subject = mail_content['subject']
        mail.add_content(Content('text/plain', mail_content['text']))
        if mail_content['html'] is not None:
            mail.add_content(Content('text/html', mail_content['html']))

        response = self.sg.client.mail.send.post(request_body=mail.get())
        logger.debug('SendGrid response code %s', response.status_code)
        logger.debug('SendGrid response body %s', response.body)
        logger.debug('SendGrid response headers %s', str(response.headers))
Exemplo n.º 11
0
    def get_message(self, **kwargs):
        """
        Get message object for email
        """
        message = Mail()
        if "from_email" in kwargs:
            sender = Email()
            message_content = kwargs.get("message_content", "")
            sender.name = message_content.get("sender",
                                              emailconf.DEFAULT_SENDER)
            sender.email = kwargs.get("from_email",
                                      emailconf.DEFAULT_SENDER_EMAIL)
            message.from_email = sender
        if "subject" in kwargs:
            message.subject = kwargs.get("subject", "")
        if "text" in kwargs:
            content = Content("text/plain", kwargs.get("text", ""))
            message.add_content(content)
        if "html" in kwargs:
            content = Content("text/html", kwargs.get("html", ""))
            message.add_content(content)
        if "category" in kwargs:
            category = Category(kwargs.get("category", ""))
            message.add_category(category)

        personalization = self.create_personalization(**kwargs)
        if personalization:
            message.add_personalization(personalization)

        return message.get()
Exemplo n.º 12
0
def construct_email(mailfrom: str, mailto: list, subject: str, content: str,
                    attfilename: str, data: str):
    """
    still intake one mailfrom and one mailto for now

    params:
    mailfrom: an email,
    mailto: an email,
    subject: str,
    data: csv-ready string
    attfilename: filename for attachment
    """
    mail = Mail()

    mail.from_email = Email(mailfrom)

    mail.subject = subject

    mail.add_content(Content("text/html", content))

    personalization = Personalization()
    for i in mailto:
        personalization.add_to(Email(i))
    mail.add_personalization(personalization)

    attachment = Attachment()
    attachment.content = str(base64.b64encode(data.encode('utf-8')), 'utf-8')
    attachment.type = 'text/csv'
    attachment.filename = attfilename
    attachment.disposition = 'attachment'
    mail.add_attachment(attachment)
    return mail
Exemplo n.º 13
0
def make_envelope(to, type, email_args):
    if current_app and current_app.config.get("TESTING"):
        return None

    from grant.user.models import User
    user = User.get_by_email(to)
    info = get_info_lookup[type](email_args)

    if user and 'subscription' in info:
        sub = info['subscription']
        if user and not is_subscribed(user.settings.email_subscriptions, sub):
            current_app.logger.debug(f'Ignoring send_email to {to} of type {type} because user is unsubscribed.')
            return None

    email = generate_email(type, email_args, user)
    mail = Mail(
        from_email=Email(SENDGRID_DEFAULT_FROM, SENDGRID_DEFAULT_FROMNAME),
        to_email=Email(to),
        subject=email['info']['subject'],
    )
    mail.add_content(Content('text/plain', email['text']))
    mail.add_content(Content('text/html', email['html']))

    mail.___type = type
    mail.___to = to

    return mail
Exemplo n.º 14
0
    def send_notification(self, notification):
        if self.can_send:
            to_email = toolz.get_in(notification, ['transports', 'sms', 'subdata'])
            logger.debug('SendGrid sending notification', to_email=to_email)
            from_email = Email('*****@*****.**', 'steemit.com')

            mail_content = self.render(notification)

            mail = Mail(
                from_email=from_email,
                to_email=to_email,
                subject=mail_content['subject'],
                content=Content('text/plain', mail_content['text']))

            if mail_content['html'] is not None:
                mail.add_content(Content('text/html', mail_content['html']))

            logger.debug('send_notification', mail=mail)

            response = self.sg.client.mail.send.post(request_body=mail.get())

            logger.debug(
                'SendGrid response',
                code=response.status_code,
                body=response.body,
                headers=response.headers)
        return notification
Exemplo n.º 15
0
    def _make_sendgrid_mail(self, message):
        mail = Mail()
        if message.sender:
            mail.from_email = Email(message.sender)
        else:
            mail.from_email = Email(self.default_sender)

        if message.subject:
            mail.subject = message.subject

        if message.recipients:
            if type(message.recipients) == list:
                personalization = Personalization()
                for recipient in message.recipients:
                    personalization.add_to(Email(recipient))
                mail.add_personalization(personalization)
            else:
                raise Exception("unsupported type yet")
        if message.body:
            mail.add_content(Content("text/plain", message.body))

        if message.html:
            mail.add_content(Content("text/html", message.html))

        if message.reply_to:
            mail.reply_to = Email(message.reply_to)

        return mail
Exemplo n.º 16
0
 def MailGrid(self,*args,**kwargs):
     mail_txt = Content('text/plain',emailbody)
     message = Mail(
         from_email=sendermail,
         to_emails=recivermail,
         subject=subject,
         html_content=htmlcontent
         )
     message.add_content(mail_txt)
     if attach is not None:
         if os.path.isfile(attach):
             head, tail = os.path.split(attach)
             with open(attach, 'rb') as f:
                 data = f.read()
                 f.close()
             encoded = base64.b64encode(data).decode()
         else:
             encoded = attach
         attachment = Attachment()
         attachment.file_content = FileContent(encoded)
         attachment.file_type = FileType('application/pdf')
         attachment.file_name = FileName(tail)
         attachment.disposition = Disposition('attachment')
         attachment.content_id = ContentId('Example Content ID')
         message.attachment = attachment
     SENDGRID_API_KEY = "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"
     sendgrid_client = sendgrid.SendGridAPIClient(SENDGRID_API_KEY )
     response = sendgrid_client.send(message)
     print(response.status_code)
     print(response.body)
     print(response.headers)
Exemplo n.º 17
0
    def _create_email(self, email: dict, email_id: str) -> Mail:
        self.log_debug('converting email %s to sendgrid format', email_id)
        mail = Mail()
        personalization = Personalization()

        for i, to in enumerate(email.get('to', [])):
            personalization.add_to(Email(to))
            self.log_debug('added to %d to email %s', i, email_id)

        for i, cc in enumerate(email.get('cc', [])):
            personalization.add_cc(Email(cc))
            self.log_debug('added cc %d to email %s', i, email_id)

        for i, bcc in enumerate(email.get('bcc', [])):
            personalization.add_bcc(Email(bcc))
            self.log_debug('added bcc %d to email %s', i, email_id)

        mail.add_personalization(personalization)
        self.log_debug('added recipients to email %s', email_id)

        mail.subject = email.get('subject', '(no subject)')
        self.log_debug('added subject to email %s', email_id)

        mail.add_content(Content('text/html', email.get('body')))
        self.log_debug('added content to email %s', email_id)

        mail.from_email = Email(email.get('from'))
        self.log_debug('added from to email %s', email_id)

        for i, attachment in enumerate(email.get('attachments', [])):
            mail.add_attachment(self._create_attachment(attachment))
            self.log_debug('added attachment %d to email %s', i, email_id)

        self.log_debug('converted email %s to sendgrid format', email_id)
        return mail
Exemplo n.º 18
0
    def form_valid(self, form):
        self.template = form.cleaned_data['template']
        self.email = form.cleaned_data['email']
        self.subject = form.cleaned_data['subject']

        mail = Mail()
        mail.set_from(Email(self.request.user.email))
        mail.set_subject(self.subject)

        personalization = Personalization()
        personalization.add_to(Email(self.email))
        mail.add_personalization(personalization)

        body_personalized = self.render_body(
                form.cleaned_data['name'],
                self.template.template_file.path)
        body = self.render_content(
                body_personalized,
                form.cleaned_data['content'],
                self.subject)
        mail.add_content(Content("text/html", body))

        if form.cleaned_data['attachment']:
            file_name = form.cleaned_data['attachment'].name
            ext = file_name.split('.')[-1]
            with form.cleaned_data['attachment'] as f:
                mail.add_attachment(self.attach_file(
                    f, ext,
                    slugify(file_name),
                    self.subject))

        self.sg.client.mail.send.post(request_body=mail.get())

        return super(CustomEmailView, self).form_valid(form)
Exemplo n.º 19
0
def send_email(recipients, gt_email, subject, content):
    """Sends email.
    If an authorization error occurs ensure endgrid.env file is in root, then 'source ./sendgrid.env'

    Args:
        recipients (User or list): Individual User or list of students.
        gt_email (str): The address that the email will come from (can be anything we want).
        subject (str): subject of the email.
        content (str): content of the email.

    Returns:
        HttpResponse: HttpResponse.
    """

    # Check if the recipients list is empty
    if not recipients:
        return HttpResponse("No recipients were found.")

    student_email_list = []

    # Only a single student
    if isinstance(recipients, User):
        student_email_list.append(Email(recipients.email))

    elif isinstance(recipients, list):
        if isinstance(recipients[0], str):
            for student in recipients:
                student_email_list.append(Email(student))
        else:
            for student in recipients:
                student_email_list.append(Email(student.email))
    else:
        return HttpResponseBadRequest("Bad Request")

    # Handle email sending
    sendgrid = SendGridAPIClient(settings.EMAIL_SENDGRID_KEY)

    mail = Mail()
    mail.from_email = Email(gt_email)
    mail.subject = subject
    mail.add_content(Content("text/plain", content))

    if settings.DEBUG:
        # if debug, send email to grepthink email
        personalization = Personalization()
        # If you wish to receive emails to personal email you can refector the below email. Do NOT update repo.
        personalization.add_to(Email("*****@*****.**"))
        mail.add_personalization(personalization)
    else:
        # add recipients to the outgoing Mail object
        # Ensure everyone can't see everyone elses emails in the 'to:' of the email
        for email in student_email_list:
            personalization = Personalization()
            personalization.add_to(email)
            mail.add_personalization(personalization)

    sendgrid.client.mail.send.post(request_body=mail.get())

    return HttpResponse("Email Sent!")
Exemplo n.º 20
0
def send_email(to, subject, html_content, files=None,
               dryrun=False, cc=None, bcc=None,
               mime_subtype='mixed', **kwargs):
    """
    Send an email with html content using sendgrid.

    To use this plugin:
    0. include sendgrid subpackage as part of your Airflow installation, e.g.,
    pip install airflow[sendgrid]
    1. update [email] backend in airflow.cfg, i.e.,
    [email]
    email_backend = airflow.contrib.utils.sendgrid.send_email
    2. configure Sendgrid specific environment variables at all Airflow instances:
    SENDGRID_MAIL_FROM={your-mail-from}
    SENDGRID_API_KEY={your-sendgrid-api-key}.
    """
    mail = Mail()
    mail.from_email = Email(os.environ.get('SENDGRID_MAIL_FROM'))
    mail.subject = subject

    # Add the recipient list of to emails.
    personalization = Personalization()
    to = get_email_address_list(to)
    for to_address in to:
        personalization.add_to(Email(to_address))
    if cc:
        cc = get_email_address_list(cc)
        for cc_address in cc:
            personalization.add_cc(Email(cc_address))
    if bcc:
        bcc = get_email_address_list(bcc)
        for bcc_address in bcc:
            personalization.add_bcc(Email(bcc_address))

    # Add custom_args to personalization if present
    pers_custom_args = kwargs.get('personalization_custom_args', None)
    if isinstance(pers_custom_args, dict):
        for key in pers_custom_args.keys():
            personalization.add_custom_arg(CustomArg(key, pers_custom_args[key]))

    mail.add_personalization(personalization)
    mail.add_content(Content('text/html', html_content))

    categories = kwargs.get('categories', [])
    for cat in categories:
        mail.add_category(Category(cat))

    # Add email attachment.
    for fname in files or []:
        basename = os.path.basename(fname)
        attachment = Attachment()
        with open(fname, "rb") as f:
            attachment.content = base64.b64encode(f.read())
            attachment.type = mimetypes.guess_type(basename)[0]
            attachment.filename = basename
            attachment.disposition = "attachment"
            attachment.content_id = '<%s>' % basename
        mail.add_attachment(attachment)
    _post_sendgrid_mail(mail.get())
Exemplo n.º 21
0
    def test_unicode_values_in_substitutions_helper(self):

        """ Test that the Substitutions helper accepts unicode values """

        self.maxDiff = None

        """Minimum required to send an email"""
        mail = Mail()

        mail.from_email = Email("*****@*****.**")

        mail.subject = "Testing unicode substitutions with the SendGrid Python Library"

        personalization = Personalization()
        personalization.add_to(Email("*****@*****.**"))
        personalization.add_substitution(Substitution("%city%", u"Αθήνα"))
        mail.add_personalization(personalization)

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

        expected_result = {
            "content": [
                {
                    "type": "text/plain",
                    "value": "some text here"
                },
                {
                    "type": "text/html",
                    "value": "<html><body>some text here</body></html>"
                }
            ],
            "from": {
                "email": "*****@*****.**"
            },
            "personalizations": [
                {
                    "substitutions": {
                        "%city%": u"Αθήνα"
                    },
                    "to": [
                        {
                            "email": "*****@*****.**"
                        }
                    ]
                }
            ],
            "subject": "Testing unicode substitutions with the SendGrid Python Library",
        }

        self.assertEqual(
            json.dumps(mail.get(), sort_keys=True),
            json.dumps(expected_result, sort_keys=True)
        )
Exemplo n.º 22
0
def send_notification(notification, trigger_check, metric_log):
    print('send_notification starting with params: '
          f'notification_id={metric_log.affiliate_id} '
          f'trigger check={trigger_check.id}'
          f'trigger={trigger_check.trigger}')

    to_emails = []
    for receiver in notification.receivers.all():
        if receiver.name == 'Affiliate Manager':
            affiliate = get_affiliate(metric_log.affiliate_id)
            employee = Employee.objects.get(pk=affiliate.account_manager_id)
            email_address = (employee.email if not employee.use_secondary else
                             employee.secondary_email)

            to_emails.append(email_address)
        if receiver.name == 'Account Manager':
            ho_offer = get_offer(metric_log.offer_id)
            manager_id = ho_offer.Advertiser['account_manager_id']
            employee = Employee.objects.get(pk=manager_id)
            email_address = (employee.email if not employee.use_secondary else
                             employee.secondary_email)
            to_emails.append(email_address)
        if receiver.name == 'Administrators':
            for recipient in Recipient.objects.filter(active=True):
                to_emails.append(recipient.email)

    macros = {
        '{value}': metric_log.value,
        '{offer-id}': metric_log.offer_id,
        '{offer-name}': Offer.objects.get(pk=metric_log.offer_id).name,
        '{affiliate-id}': metric_log.affiliate_id
    }

    sg = sendgrid.SendGridAPIClient(apikey=settings.SENDGRID_API_KEY)

    mail = Mail()
    mail.from_email = Email(settings.NETWORK_EMAIL)
    subject = notification.subject
    message = notification.message
    for macro, value in macros.items():
        message = message.replace(macro, str(value))
        subject = subject.replace(macro, str(value))
    now = datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S")
    message += f"<br><br><small>generated at: {now}</small>"
    mail.subject = subject
    mail.add_content(Content("text/html", message))
    personalization = Personalization()
    for email in to_emails:
        personalization.add_to(Email(email))
    mail.add_personalization(personalization)
    response = sg.client.mail.send.post(request_body=mail.get())

    print(f'send_notification: response.status_code={response.status_code}')

    print('send_notification: '
          f'notification_id={metric_log.affiliate_id} '
          f'trigger check={trigger_check.id}')
Exemplo n.º 23
0
def send_mail(api_key, subject, content, to=['*****@*****.**']):
    sg = sendgrid.SendGridAPIClient(apikey=api_key)

    mail = Mail(Email("*****@*****.**", "Open State Foundation"),
                subject, Email(to[0], to[0]))

    mail.add_content(Content("text/plain", content))
    mail.add_content(Content("text/html", content))

    sg.client.mail.send.post(request_body=mail.get())
Exemplo n.º 24
0
    def _prepare_sendgrid_data(self):
        self.ensure_one()
        s_mail = Mail()
        s_mail.set_from(Email(self.email_from))
        if self.reply_to:
            s_mail.set_reply_to(Email(self.reply_to))
        s_mail.add_custom_arg(CustomArg('odoo_id', self.message_id))
        html = self.body_html or ' '

        p = re.compile(r'<.*?>')  # Remove HTML markers
        text_only = self.body_text or p.sub('', html.replace('<br/>', '\n'))

        s_mail.add_content(Content("text/plain", text_only))
        s_mail.add_content(Content("text/html", html))

        test_address = config.get('sendgrid_test_address')

        # We use only one personalization for transactional e-mail
        personalization = Personalization()
        personalization.set_subject(self.subject or ' ')
        addresses = list()
        if not test_address:
            if self.email_to and self.email_to not in addresses:
                personalization.add_to(Email(self.email_to))
                addresses.append(self.email_to)
            for recipient in self.recipient_ids:
                if recipient.email not in addresses:
                    personalization.add_to(Email(recipient.email))
                    addresses.append(recipient.email)
            if self.email_cc and self.email_cc not in addresses:
                personalization.add_cc(Email(self.email_cc))
        else:
            _logger.info('Sending email to test address {}'.format(
                test_address))
            personalization.add_to(Email(test_address))
            self.email_to = test_address

        if self.sendgrid_template_id:
            s_mail.set_template_id(self.sendgrid_template_id.remote_id)

        for substitution in self.substitution_ids:
            personalization.add_substitution(Substitution(
                substitution.key, substitution.value))

        s_mail.add_personalization(personalization)

        for attachment in self.attachment_ids:
            s_attachment = Attachment()
            # Datas are not encoded properly for sendgrid
            s_attachment.set_content(base64.b64encode(base64.b64decode(
                attachment.datas)))
            s_attachment.set_filename(attachment.name)
            s_mail.add_attachment(s_attachment)

        return s_mail.get()
Exemplo n.º 25
0
    def send(self, notification):
        '''
        Accepts a notification and sends an email using included data.
        If SENDGRID_REPORTING_KEY and EMAIL_REPORT_SENDER are available
        in config, it uses Sendgrid to deliver the email. Otherwise, it
        uses plain SMTP through send_email()
        '''
        user = notification.user

        to = notification.email or user.email
        full_name = user.get_nice_name()
        first_name = user.first_name or user.get_nice_name()

        if (hasattr(config, "SENDGRID_REPORTING_KEY")
                and hasattr(config, "EMAIL_REPORT_SENDER")):
            from sendgrid.helpers.mail import (Email, Mail, Personalization,
                                               Content, Substitution)
            import sendgrid

            self.sg_instance = sendgrid.SendGridAPIClient(
                apikey=config.SENDGRID_REPORTING_KEY)

            mail = Mail()
            mail.from_email = Email(config.EMAIL_REPORT_SENDER,
                                    "Mist.io Reports")
            personalization = Personalization()
            personalization.add_to(Email(to, full_name))
            personalization.subject = notification.subject
            sub1 = Substitution("%name%", first_name)
            personalization.add_substitution(sub1)
            if "unsub_link" in notification:
                sub2 = Substitution("%nsub%", notification.unsub_link)
                personalization.add_substitution(sub2)
            mail.add_personalization(personalization)

            mail.add_content(Content("text/plain", notification.body))
            if "html_body" in notification:
                mail.add_content(Content("text/html", notification.html_body))

            mdict = mail.get()
            try:
                return self.sg_instance.client.mail.send.post(
                    request_body=mdict)
            except urllib2.URLError as exc:
                logging.error(exc)
                exit()
            except Exception as exc:
                logging.error(str(exc.status_code) + ' - ' + exc.reason)
                logging.error(exc.to_dict)
                exit()
        else:
            send_email(notification.subject,
                       notification.body, [to],
                       sender="config.EMAIL_REPORT_SENDER")
Exemplo n.º 26
0
def send_email(to, subject, html_content, files=None,
               dryrun=False, cc=None, bcc=None,
               mime_subtype='mixed', **kwargs):
    """
    Send an email with html content using sendgrid.

    To use this plugin:
    0. include sendgrid subpackage as part of your Airflow installation, e.g.,
    pip install airflow[sendgrid]
    1. update [email] backend in airflow.cfg, i.e.,
    [email]
    email_backend = airflow.contrib.utils.sendgrid.send_email
    2. configure Sendgrid specific environment variables at all Airflow instances:
    SENDGRID_MAIL_FROM={your-mail-from}
    SENDGRID_API_KEY={your-sendgrid-api-key}.
    """
    mail = Mail()
    mail.from_email = Email(os.environ.get('SENDGRID_MAIL_FROM'))
    mail.subject = subject

    # Add the recipient list of to emails.
    personalization = Personalization()
    to = get_email_address_list(to)
    for to_address in to:
        personalization.add_to(Email(to_address))
    if cc:
        cc = get_email_address_list(cc)
        for cc_address in cc:
            personalization.add_cc(Email(cc_address))
    if bcc:
        bcc = get_email_address_list(bcc)
        for bcc_address in bcc:
            personalization.add_bcc(Email(bcc_address))
    mail.add_personalization(personalization)
    mail.add_content(Content('text/html', html_content))

    # Add custom_args to personalization if present
    pers_custom_args = kwargs.get('personalization_custom_args', None)
    if isinstance(pers_custom_args, dict):
        for key in pers_custom_args.keys():
            personalization.add_custom_arg(CustomArg(key, pers_custom_args[key]))

    # Add email attachment.
    for fname in files or []:
        basename = os.path.basename(fname)
        attachment = Attachment()
        with open(fname, "rb") as f:
            attachment.content = base64.b64encode(f.read())
            attachment.type = mimetypes.guess_type(basename)[0]
            attachment.filename = basename
            attachment.disposition = "attachment"
            attachment.content_id = '<%s>' % basename
        mail.add_attachment(attachment)
    _post_sendgrid_mail(mail.get())
Exemplo n.º 27
0
    def _create_email(self, email: dict, email_id: str) -> Mail:
        self.log_debug('converting email %s to sendgrid format', email_id)
        mail = Mail()
        personalization = Personalization()

        for i, to in enumerate(email.get('to', [])):
            personalization.add_to(Email(to))
            self.log_debug('added to %d to email %s', i, email_id)

        for i, cc in enumerate(email.get('cc', [])):
            personalization.add_cc(Email(cc))
            self.log_debug('added cc %d to email %s', i, email_id)

        for i, bcc in enumerate(email.get('bcc', [])):
            personalization.add_bcc(Email(bcc))
            self.log_debug('added bcc %d to email %s', i, email_id)

        mail.add_personalization(personalization)
        self.log_debug('added recipients to email %s', email_id)

        mail.subject = email.get('subject', '(no subject)')
        self.log_debug('added subject to email %s', email_id)

        mail.add_content(
            Content('text/html', email.get('body', '(no content)')))
        self.log_debug('added content to email %s', email_id)

        # at some point SendGrid had the ability to send from subdomains of a verified
        # domain, so verifying {domain} let us send from {client}.{domain}
        # ...this feature went away so the following is a work-around which
        # changes the from address to the verified root domain but using reply-to
        # so that the email still gets routed back to the original client
        # ...this is a pretty ugly hack and the real fix is to change the logic of
        # how we sign up users on clients to use the new format {user}-{client}@{domain}
        from_email = email.get('from')
        if from_email:
            user, client_domain = from_email.split('@')
            client_domain_parts = client_domain.split('.')
            if len(client_domain_parts) == 3:
                client = client_domain_parts[0]
                domain = '.'.join(client_domain_parts[1:])
                mail.from_email = Email('{}-{}@{}'.format(
                    user, client, domain))
                mail.reply_to = Email(from_email)
            else:
                mail.from_email = Email(from_email)
            self.log_debug('added from to email %s', email_id)

        for i, attachment in enumerate(email.get('attachments', [])):
            mail.add_attachment(self._create_attachment(attachment))
            self.log_debug('added attachment %d to email %s', i, email_id)

        self.log_debug('converted email %s to sendgrid format', email_id)
        return mail
Exemplo n.º 28
0
    def _make_sendgrid_mail(self, message):
        mail = Mail()
        if message.sender:
            mail.from_email = Email(message.sender)
        else:
            mail.from_email = Email(self.default_sender)

        if message.mail_options and message.mail_options.get('from_name'):
            mail.from_email.name = message.mail_options.get('from_name')

        template_id = getattr(message, 'template_id', None)
        if template_id:
            mail.template_id = template_id

        if message.subject:
            mail.subject = message.subject

        if message.recipients:
            if type(message.recipients) == list:
                personalization = Personalization()
                for recipient in message.recipients:
                    personalization.add_to(Email(recipient))

                dynamic_template_data = getattr(message,
                                                'dynamic_template_data', None)
                if dynamic_template_data:
                    personalization.dynamic_template_data = dynamic_template_data

                mail.add_personalization(personalization)
            else:
                raise Exception("unsupported type yet")
        if message.body:
            mail.add_content(Content("text/plain", message.body))

        if message.html:
            mail.add_content(Content("text/html", message.html))

        if message.reply_to:
            mail.reply_to = Email(message.reply_to)

        if message.attachments:
            for attachment in message.attachments:
                file_content = base64.b64encode(
                    attachment.data).decode('UTF-8')
                mail.add_attachment(
                    Attachment(
                        file_content=file_content,
                        file_name=attachment.filename,
                        file_type=attachment.content_type,
                        disposition=attachment.disposition,
                    ))

        return mail
Exemplo n.º 29
0
def create_mail_config(from_email: str, subject: str, to_emails: List[str],
                       content: str) -> dict:
    mail = Mail()

    mail.from_email = Email(from_email)
    mail.subject = subject
    personalization = Personalization()
    for email in to_emails:
        personalization.add_to(Email(email))
    mail.add_personalization(personalization)
    mail.add_content(Content("text/html", content))

    return mail.get()
Exemplo n.º 30
0
    def _prepare_sendgrid_data(self):
        self.ensure_one()
        s_mail = Mail()
        s_mail.set_from(Email(self.email_from))
        s_mail.set_reply_to(Email(self.reply_to))
        s_mail.add_custom_arg(CustomArg('odoo_id', self.message_id))
        html = self.body_html or ' '

        p = re.compile(r'<.*?>')  # Remove HTML markers
        text_only = self.body_text or p.sub('', html.replace('<br/>', '\n'))

        s_mail.add_content(Content("text/plain", text_only))
        s_mail.add_content(Content("text/html", html))

        test_address = config.get('sendgrid_test_address')

        # TODO For now only one personalization (transactional e-mail)
        personalization = Personalization()
        personalization.set_subject(self.subject or ' ')
        if not test_address:
            if self.email_to:
                personalization.add_to(Email(self.email_to))
            for recipient in self.recipient_ids:
                personalization.add_to(Email(recipient.email))
            if self.email_cc:
                personalization.add_cc(Email(self.email_cc))
        else:
            _logger.info('Sending email to test address {}'.format(
                test_address))
            personalization.add_to(Email(test_address))
            self.email_to = test_address

        if self.sendgrid_template_id:
            s_mail.set_template_id(self.sendgrid_template_id.remote_id)

        for substitution in self.substitution_ids:
            personalization.add_substitution(Substitution(
                substitution.key, substitution.value))

        s_mail.add_personalization(personalization)

        for attachment in self.attachment_ids:
            s_attachment = Attachment()
            # Datas are not encoded properly for sendgrid
            s_attachment.set_content(base64.b64encode(base64.b64decode(
                attachment.datas)))
            s_attachment.set_filename(attachment.name)
            s_mail.add_attachment(s_attachment)

        return s_mail.get()
Exemplo n.º 31
0
    def build(self, to_email, subject, body):
        mail = Mail()
        from_email = self.config['MAILER_FROM_EMAIL']
        from_name = self.config['MAILER_FROM_NAME']
        mail.from_email = Email(from_email, from_name)
        mail.subject = subject

        personalization = Personalization()
        personalization.add_to(Email(to_email))
        mail.add_personalization(personalization)

        mail.add_content(Content("text/plain", body))

        return mail.get()
Exemplo n.º 32
0
    def _build_sg_mail(self, email):
        mail = Mail()
        from_name, from_email = rfc822.parseaddr(email.from_email)
        # Python sendgrid client should improve
        # sendgrid/helpers/mail/mail.py:164
        if not from_name:
            from_name = None
        mail.set_from(Email(from_email, from_name))
        mail.set_subject(email.subject)

        personalization = Personalization()
        for e in email.to:
            personalization.add_to(Email(e))
        for e in email.cc:
            personalization.add_cc(Email(e))
        for e in email.bcc:
            personalization.add_bcc(Email(e))
        personalization.set_subject(email.subject)
        mail.add_content(Content("text/plain", email.body))
        if isinstance(email, EmailMultiAlternatives):
            for alt in email.alternatives:
                if alt[1] == "text/html":
                    mail.add_content(Content(alt[1], alt[0]))
        elif email.content_subtype == "html":
            mail.contents = []
            mail.add_content(Content("text/plain", ' '))
            mail.add_content(Content("text/html", email.body))

        if hasattr(email, 'categories'):
            for c in email.categories:
                mail.add_category(Category(c))

        if hasattr(email, 'template_id'):
            mail.set_template_id(email.template_id)
            if hasattr(email, 'substitutions'):
                for k, v in email.substitutions.items():
                    personalization.add_substitution(Substitution(k, v))

        for k, v in email.extra_headers.items():
            mail.add_header({k: v})

        for attachment in email.attachments:
            if isinstance(attachment, MIMEBase):
                attach = Attachment()
                attach.set_filename(attachment.get_filename())
                attach.set_content(base64.b64encode(attachment.get_payload()))
                mail.add_attachment(attach)
            elif isinstance(attachment, tuple):
                attach = Attachment()
                attach.set_filename(attachment[0])
                base64_attachment = base64.b64encode(attachment[1])
                if sys.version_info >= (3, ):
                    attach.set_content(str(base64_attachment, 'utf-8'))
                else:
                    attach.set_content(base64_attachment)
                attach.set_type(attachment[2])
                mail.add_attachment(attach)

        mail.add_personalization(personalization)
        return mail.get()
Exemplo n.º 33
0
def _setup_email(_notify):
    mail = Mail()

    mail.from_email = Email(**_notify.from_email)

    for attachment in _notify.attachment_list():
        _att = Attachment()
        _att.content = gb64(attachment)
        _att.filename = os.path.split(attachment)[-1]
        _att.disposition = "attachment"
        mail.add_attachment(_att)

    mail.add_content(Content("text/html", _notify.message))

    return mail
Exemplo n.º 34
0
 def create_message(self, email_attributes: Dict[str, Any]) -> Any:
     mail = Mail()
     mail.from_email = Email(email_attributes["FromEmail"],
                             email_attributes["FromName"])
     mail.subject = email_attributes["Subject"]
     p = Personalization()
     for recipient in email_attributes["Recipients"]:
         p.add_to(Email(recipient["Email"], recipient.get("Name")))
     mail.add_personalization(p)
     for category in email_attributes.get("categories", []):
         mail.add_category(Category(category))
     # mail.add_content(Content("text/plain", "some text here"))
     mail.add_content(Content("text/html", email_attributes["Html-part"]))
     if email_attributes["Attachments"]:
         mail = self.add_attachments(mail, email_attributes["Attachments"])
     return mail.get()
Exemplo n.º 35
0
    def test_sendgrid_api_key(self):
        """Tests if including SendGrid API will throw an Exception"""

        # Minimum required to send an email
        self.max_diff = None
        mail = Mail()

        mail.from_email = Email("*****@*****.**")

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

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

        # Try to include SendGrid API key
        try:
            mail.add_content(
                Content(
                    "text/plain",
                    "some SG.2123b1B.1212lBaC here"))
            mail.add_content(
                Content(
                    "text/html",
                    "<html><body>some SG.Ba2BlJSDba.232Ln2 here</body></html>"))

            self.assertEqual(
                json.dumps(
                    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"}'
            )

        # Exception should be thrown
        except Exception:
            pass

        # Exception not thrown
        else:
            self.fail("Should have failed as SendGrid API key included")
Exemplo n.º 36
0
    def _build_sg_mail(self, msg):
        mail = Mail()

        mail.from_email = Email(*self._parse_email_address(msg.from_email))
        mail.subject = msg.subject

        personalization = Personalization()
        for addr in msg.to:
            personalization.add_to(Email(*self._parse_email_address(addr)))

        for addr in msg.cc:
            personalization.add_cc(Email(*self._parse_email_address(addr)))

        for addr in msg.bcc:
            personalization.add_bcc(Email(*self._parse_email_address(addr)))

        personalization.subject = msg.subject

        for k, v in msg.extra_headers.items():
            if k.lower() == "reply-to":
                mail.reply_to = Email(v)
            else:
                personalization.add_header(Header(k, v))

        if hasattr(msg, "template_id"):
            mail.template_id = msg.template_id
            if hasattr(msg, "substitutions"):
                for k, v in msg.substitutions.items():
                    personalization.add_substitution(Substitution(k, v))

        # write through the ip_pool_name attribute
        if hasattr(msg, "ip_pool_name"):
            if not isinstance(msg.ip_pool_name, basestring):
                raise ValueError(
                    "ip_pool_name must be a string, got: {}; "
                    "see https://sendgrid.com/docs/API_Reference/Web_API_v3/Mail/"
                    "index.html#-Request-Body-Parameters".format(
                        type(msg.ip_pool_name)))
            if not 2 <= len(msg.ip_pool_name) <= 64:
                raise ValueError(
                    "the number of characters of ip_pool_name must be min 2 and max 64, got: {}; "
                    "see https://sendgrid.com/docs/API_Reference/Web_API_v3/Mail/"
                    "index.html#-Request-Body-Parameters".format(
                        len(msg.ip_pool_name)))
            mail.ip_pool_name = msg.ip_pool_name

        # write through the send_at attribute
        if hasattr(msg, "send_at"):
            if not isinstance(msg.send_at, int):
                raise ValueError(
                    "send_at must be an integer, got: {}; "
                    "see https://sendgrid.com/docs/API_Reference/SMTP_API/scheduling_parameters.html#-Send-At".format(
                        type(msg.send_at)))
            personalization.send_at = msg.send_at

        mail.add_personalization(personalization)

        if hasattr(msg, "reply_to") and msg.reply_to:
            if mail.reply_to:
                # If this code path is triggered, the reply_to on the sg mail was set in a header above
                reply_to = Email(*self._parse_email_address(msg.reply_to))
                if reply_to.email != mail.reply_to.email or reply_to.name != mail.reply_to.name:
                    raise ValueError("Sendgrid only allows 1 email in the reply-to field.  " +
                                     "Reply-To header value != reply_to property value.")

            if not isinstance(msg.reply_to, basestring):
                if len(msg.reply_to) > 1:
                    raise ValueError("Sendgrid only allows 1 email in the reply-to field")
                mail.reply_to = Email(*self._parse_email_address(msg.reply_to[0]))
            else:
                mail.reply_to = Email(*self._parse_email_address(msg.reply_to))

        for attch in msg.attachments:
            attachment = Attachment()

            if isinstance(attch, MIMEBase):
                filename = attch.get_filename()
                if not filename:
                    ext = mimetypes.guess_extension(attch.get_content_type())
                    filename = "part-{0}{1}".format(uuid.uuid4().hex, ext)
                attachment.filename = filename
                # todo: Read content if stream?
                attachment.content = attch.get_payload().replace("\n", "")
                attachment.type = attch.get_content_type()
                content_id = attch.get("Content-ID")
                if content_id:
                    # Strip brackets since sendgrid's api adds them
                    if content_id.startswith("<") and content_id.endswith(">"):
                        content_id = content_id[1:-1]
                    attachment.content_id = content_id
                    attachment.disposition = "inline"

            else:
                filename, content, mimetype = attch

                attachment.filename = filename
                # Convert content from chars to bytes, in both Python 2 and 3.
                # todo: Read content if stream?
                if isinstance(content, str):
                    content = content.encode('utf-8')
                attachment.content = base64.b64encode(content).decode()
                attachment.type = mimetype

            mail.add_attachment(attachment)

        msg.body = ' ' if msg.body == '' else msg.body

        if isinstance(msg, EmailMultiAlternatives):
            mail.add_content(Content("text/plain", msg.body))
            for alt in msg.alternatives:
                if alt[1] == "text/html":
                    mail.add_content(Content(alt[1], alt[0]))
        elif msg.content_subtype == "html":
            mail.add_content(Content("text/plain", " "))
            mail.add_content(Content("text/html", msg.body))
        else:
            mail.add_content(Content("text/plain", msg.body))

        if hasattr(msg, "categories"):
            for cat in msg.categories:
                mail.add_category(Category(cat))

        if hasattr(msg, "asm"):
            if "group_id" not in msg.asm:
                raise KeyError("group_id not found in asm")

            if "groups_to_display" in msg.asm:
                mail.asm = ASM(msg.asm["group_id"], msg.asm["groups_to_display"])
            else:
                mail.asm = ASM(msg.asm["group_id"])

        mail_settings = MailSettings()
        mail_settings.sandbox_mode = SandBoxMode(self.sandbox_mode)
        mail.mail_settings = mail_settings

        tracking_settings = TrackingSettings()
        tracking_settings.open_tracking = OpenTracking(self.track_email)
        mail.tracking_settings = tracking_settings

        return mail.get()
Exemplo n.º 37
0
def send_email(to, subject, html_content, files=None, dryrun=False, cc=None,
               bcc=None, mime_subtype='mixed', sandbox_mode=False, **kwargs):
    """
    Send an email with html content using sendgrid.

    To use this plugin:
    0. include sendgrid subpackage as part of your Airflow installation, e.g.,
    pip install 'apache-airflow[sendgrid]'
    1. update [email] backend in airflow.cfg, i.e.,
    [email]
    email_backend = airflow.contrib.utils.sendgrid.send_email
    2. configure Sendgrid specific environment variables at all Airflow instances:
    SENDGRID_MAIL_FROM={your-mail-from}
    SENDGRID_API_KEY={your-sendgrid-api-key}.
    """
    if files is None:
        files = []

    mail = Mail()
    from_email = kwargs.get('from_email') or os.environ.get('SENDGRID_MAIL_FROM')
    from_name = kwargs.get('from_name') or os.environ.get('SENDGRID_MAIL_SENDER')
    mail.from_email = Email(from_email, from_name)
    mail.subject = subject
    mail.mail_settings = MailSettings()

    if sandbox_mode:
        mail.mail_settings.sandbox_mode = SandBoxMode(enable=True)

    # Add the recipient list of to emails.
    personalization = Personalization()
    to = get_email_address_list(to)
    for to_address in to:
        personalization.add_to(Email(to_address))
    if cc:
        cc = get_email_address_list(cc)
        for cc_address in cc:
            personalization.add_cc(Email(cc_address))
    if bcc:
        bcc = get_email_address_list(bcc)
        for bcc_address in bcc:
            personalization.add_bcc(Email(bcc_address))

    # Add custom_args to personalization if present
    pers_custom_args = kwargs.get('personalization_custom_args', None)
    if isinstance(pers_custom_args, dict):
        for key in pers_custom_args.keys():
            personalization.add_custom_arg(CustomArg(key, pers_custom_args[key]))

    mail.add_personalization(personalization)
    mail.add_content(Content('text/html', html_content))

    categories = kwargs.get('categories', [])
    for cat in categories:
        mail.add_category(Category(cat))

    # Add email attachment.
    for fname in files:
        basename = os.path.basename(fname)

        attachment = Attachment()
        attachment.type = mimetypes.guess_type(basename)[0]
        attachment.filename = basename
        attachment.disposition = "attachment"
        attachment.content_id = '<{0}>'.format(basename)

        with open(fname, "rb") as f:
            attachment.content = base64.b64encode(f.read()).decode('utf-8')

        mail.add_attachment(attachment)
    _post_sendgrid_mail(mail.get())
Exemplo n.º 38
0
    def _build_sg_mail(self, email):
        mail = Mail()
        from_name, from_email = rfc822.parseaddr(email.from_email)
        # Python sendgrid client should improve
        # sendgrid/helpers/mail/mail.py:164
        if not from_name:
            from_name = None
        mail.set_from(Email(from_email, from_name))
        mail.set_subject(email.subject)

        personalization = Personalization()
        for e in email.to:
            personalization.add_to(Email(e))
        for e in email.cc:
            personalization.add_cc(Email(e))
        for e in email.bcc:
            personalization.add_bcc(Email(e))
        personalization.set_subject(email.subject)
        mail.add_content(Content("text/plain", email.body))
        if isinstance(email, EmailMultiAlternatives):
            for alt in email.alternatives:
                if alt[1] == "text/html":
                    mail.add_content(Content(alt[1], alt[0]))
        elif email.content_subtype == "html":
            mail.contents = []
            mail.add_content(Content("text/plain", ' '))
            mail.add_content(Content("text/html", email.body))

        if hasattr(email, 'categories'):
            for c in email.categories:
                mail.add_category(Category(c))

        if hasattr(email, 'custom_args'):
            for k, v in email.custom_args.items():
                mail.add_custom_arg(CustomArg(k, v))

        if hasattr(email, 'template_id'):
            mail.set_template_id(email.template_id)
            if hasattr(email, 'substitutions'):
                for key, value in email.substitutions.items():
                    personalization.add_substitution(Substitution(key, value))

        # SendGrid does not support adding Reply-To as an extra
        # header, so it needs to be manually removed if it exists.
        reply_to_string = ""
        for key, value in email.extra_headers.items():
            if key.lower() == "reply-to":
                reply_to_string = value
            else:
                mail.add_header({key: value})
        # Note that if you set a "Reply-To" header *and* the reply_to
        # attribute, the header's value will be used.
        if not mail.reply_to and hasattr(email, "reply_to") and email.reply_to:
            # SendGrid only supports setting Reply-To to a single address.
            # See https://github.com/sendgrid/sendgrid-csharp/issues/339.
            reply_to_string = email.reply_to[0]
        # Determine whether reply_to contains a name and email address, or
        # just an email address.
        if reply_to_string:
            reply_to_name, reply_to_email = rfc822.parseaddr(reply_to_string)
            if reply_to_name and reply_to_email:
                mail.set_reply_to(Email(reply_to_email, reply_to_name))
            elif reply_to_email:
                mail.set_reply_to(Email(reply_to_email))

        for attachment in email.attachments:
            if isinstance(attachment, MIMEBase):
                attach = Attachment()
                attach.set_filename(attachment.get_filename())
                attach.set_content(base64.b64encode(attachment.get_payload()))
                mail.add_attachment(attach)
            elif isinstance(attachment, tuple):
                attach = Attachment()
                attach.set_filename(attachment[0])
                base64_attachment = base64.b64encode(attachment[1])
                if sys.version_info >= (3,):
                    attach.set_content(str(base64_attachment, 'utf-8'))
                else:
                    attach.set_content(base64_attachment)
                attach.set_type(attachment[2])
                mail.add_attachment(attach)

        mail.add_personalization(personalization)
        return mail.get()
Exemplo n.º 39
0
    def test_kitchenSink(self):
        self.maxDiff = None

        """All settings set"""
        mail = Mail()

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

        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
        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
        mail.add_personalization(personalization2)

        mail.add_content(Content("text/plain", "some text here"))
        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"
        mail.add_attachment(attachment)

        attachment2 = Attachment()
        attachment2.content = "BwdW"
        attachment2.type = "image/png"
        attachment2.filename = "banner.png"
        attachment2.disposition = "inline"
        attachment2.content_id = "Banner"
        mail.add_attachment(attachment2)

        mail.template_id = "13b8f94f-bcae-4ec6-b752-70d6cb59f932"

        mail.add_section(
            Section(
                "%section1%",
                "Substitution Text for Section 1"))
        mail.add_section(
            Section(
                "%section2%",
                "Substitution Text for Section 2"))

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

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

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

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

        mail.send_at = 1443636842

        mail.batch_id = "sendgrid_batch_id"

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

        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")
        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")
        mail.tracking_settings = tracking_settings

        mail.reply_to = Email("*****@*****.**")

        expected_result = {
            "asm": {
                "group_id": 99,
                "groups_to_display": [4, 5, 6, 7, 8]
            },
            "attachments": [
                {
                    "content": "TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQsIGNvbnNlY3"
                               "RldHVyIGFkaXBpc2NpbmcgZWxpdC4gQ3JhcyBwdW12",
                    "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"
                }
            }
        }
        self.assertEqual(
            json.dumps(mail.get(), sort_keys=True),
            json.dumps(expected_result, sort_keys=True)
        )