Пример #1
0
def send_registration_mail(attendee: Attendee, event: Event):
    qr_data = gen_qrcode(data=str(attendee.uuid)).read()
    template = templates['REGISTRATION']

    mail = Mail()
    mail.from_email = Email(template['FROM_EMAIL'], template['FROM_NAME'])
    mail.template_id = template['ID']
    mail.add_category(Category(template['CATEGORY']))

    attachment1 = Attachment()
    attachment1.content = base64.b64encode(qr_data).decode('ascii')
    attachment1.filename = template['FILENAME']
    mail.add_attachment(attachment1)

    personalization = Personalization()
    personalization.add_substitution(
        Substitution("%first_name%",
                     attendee.name.split()[0]))
    personalization.add_substitution(Substitution("%event_name%", event.name))
    personalization.add_to(Email(attendee.email, attendee.name))
    mail.add_personalization(personalization)

    try:
        sg.client.mail.send.post(request_body=mail.get())
        return qr_data
    except Exception as e:
        raise e
Пример #2
0
def get_mock_personalization_dict():
    """Get a dict of personalization mock."""
    mock_pers = dict()

    mock_pers['to_list'] = [Email("*****@*****.**",
                                  "Example User"),
                            Email("*****@*****.**",
                                  "Example User")]

    mock_pers['cc_list'] = [Email("*****@*****.**",
                                  "Example User"),
                            Email("*****@*****.**",
                                  "Example User")]

    mock_pers['bcc_list'] = [Email("*****@*****.**"),
                             Email("*****@*****.**")]

    mock_pers['subject'] = ("Hello World from the Personalized "
                            "SendGrid Python Library")

    mock_pers['headers'] = [Header("X-Test", "test"),
                            Header("X-Mock", "true")]

    mock_pers['substitutions'] = [Substitution("%name%", "Example User"),
                                  Substitution("%city%", "Denver")]

    mock_pers['custom_args'] = [CustomArg("user_id", "343"),
                                CustomArg("type", "marketing")]

    mock_pers['send_at'] = 1443636843
    return mock_pers
def sendTests(email, assignment, assignment_type, event_list):
    from_email = Email("*****@*****.**")
    subject = "{} {}s".format(assignment, assignment_type)
    to_email = Email(email)
    content = Content("text/html", "Good Luck!")
    mail = Mail(from_email, subject, to_email, content)
    user = User.query.filter_by(email=email).first()
    mail.personalizations[0].add_substitution(Substitution("-name-", user.firstname.capitalize()))
    mail.personalizations[0].add_substitution(Substitution("-assignment-", assignment))
    mail.personalizations[0].add_substitution(Substitution("-assignment_types-", assignment_type+'s'))
    eventNum = len(event_list)
    for c in range(eventNum):
        mail.personalizations[0].add_substitution(Substitution("-Event{}name-".format(c+1), event_list[c][0]))
        mail.personalizations[0].add_substitution(Substitution("-Event{}Link-".format(c+1), event_list[c][1]))
    if eventNum == 1:
        mail.template_id = "8238dc2b-2da6-4006-90c4-9129416f9bba"
    elif eventNum == 2:
        mail.template_id = "21ad7fc8-3183-4a77-8509-bb06973f763f"
    elif eventNum == 3:
        mail.template_id = "ad7f080f-bffd-4314-a2ed-da86971b0cfb"
    elif eventNum == 4:
        mail.template_id = "19df88b3-25ef-4a16-bf51-519169cf70ab"
    response = sg.client.mail.send.post(request_body=mail.get())
    print(response.status_code)
    print(response.body)
    print(response.headers)
Пример #4
0
def send_certificate_mail(name, email, event, cpf=None):
    template = templates['CERTIFICATE_EMITTED']

    mail = Mail()
    mail.from_email = Email(template['FROM_EMAIL'], template['FROM_NAME'])
    mail.template_id = template['ID']
    mail.add_category(Category(template['CATEGORY']))

    attachment1 = Attachment()

    if isinstance(event, Event):
        event_place = event.place
        event_duration = event.formated_duration
        event_date = event.formated_dates
        event_min_percent = event.certificate_minimum_time
    else:
        event_place = event.event_day.event.place
        event_duration = event.event_day.event.formated_duration
        event_date = event.event_day.event.formated_dates
        event_min_percent = event.event_day.event.certificate_minimum_time

    cpf_text = _(', bearer of the registry number %(cpf)s,') % {
        'cpf': cpf
    } if cpf else ''
    data = {
        'name': name,
        'event': event.name,
        'cpf': cpf_text,
        'event_date': event_date,
        'event_place': event_place,
        'event_duration': event_duration,
        'event_min_percent': event_min_percent
    }

    certificate_data = event.certificate_model.generate_certificate(data)

    attachment1.content = base64.b64encode(
        certificate_data.read()).decode('ascii')
    attachment1.filename = template['FILENAME']
    mail.add_attachment(attachment1)

    personalization = Personalization()
    personalization.add_substitution(
        Substitution("%first_name%",
                     name.split()[0]))
    personalization.add_substitution(Substitution("%event_name%", event.name))
    personalization.add_to(Email(email, name))
    mail.add_personalization(personalization)

    try:
        response = sg.client.mail.send.post(request_body=mail.get())
        return True
    except Exception as e:
        print(response.body)
        raise e
Пример #5
0
    def post(self, request, *args, **kwargs):
        my_profile = get_object_or_404(Profile, user=self.request.user)
        other_id = int(self.kwargs['profile_id'])
        other_profile = get_object_or_404(Profile, id=other_id)
        message_body = request.data['body']

        #Find associated thread, or create new thread
        query = Thread.getProfileQuery(my_profile, other_profile)
        thread = Thread.objects.filter(query).first()

        if thread is None:
            new_thread = Thread(
                profile_1=my_profile,
                profile_2=other_profile,
            )

            new_thread.save()
            thread = new_thread

            #Send email to recipient of message
            sender_name = my_profile.user.first_name + ' ' + my_profile.user.last_name
            message_url = 'bquest.ucladevx.com/messages/' + str(
                other_profile.id) + '/'
            recipient_email = other_profile.user.email

            from_email = Email('*****@*****.**')
            to_email = Email(recipient_email)
            subject = 'New Message from BQuest'
            content = Content('text/html', 'N/A')
            mail = Mail(from_email, subject, to_email, content)
            mail.personalizations[0].add_substitution(
                Substitution('mentee_name', sender_name))
            mail.personalizations[0].add_substitution(
                Substitution('user_message', message_body))
            mail.personalizations[0].add_substitution(
                Substitution('user_message_address', message_url))
            mail.template_id = MESSAGING_TEMPLATE
            sg = sendgrid.SendGridAPIClient(apikey=settings.SENDGRID_API_KEY)
            response = sg.client.mail.send.post(request_body=mail.get())
            if not (200 <= response.status_code < 300):
                raise ValidationError({'status_code': response.status_code})

        new_message = Message(
            thread=thread,
            sender=my_profile,
            body=message_body,
            unread=True,
        )

        new_message.save()

        other_user = new_message.thread.get_other_user(my_profile)
        websockets_notify_user(other_user)

        return Response(MessageSerializer(new_message).data)
Пример #6
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")
Пример #7
0
def send_report(user, report):
    substitutions = [
        Substitution('-post-', report.post.id),
        Substitution('-type-', report.get_type_display()),
        Substitution('-post_message-', report.post.description.encode('utf-8'))
    ]
    mails = [Email(email=admin[1], name=admin[0]) for admin in settings.ADMINS]
    sendgrid_api(
        obtain_mail(personalization=obtain_personalization(user,
                                                           substitutions,
                                                           to_mails=mails),
                    template=settings.SENDGRID_REPORT))
def sendReceivedSubmission(email, assignment, link):
    from_email = Email("*****@*****.**")
    subject = "{} Received Submission".format(assignment)
    to_email = Email(email)
    content = Content("text/html", "Good Luck!")
    mail = Mail(from_email, subject, to_email, content)
    user = User.query.filter_by(email=email).first()
    mail.personalizations[0].add_substitution(Substitution("-name-", user.firstname))
    mail.personalizations[0].add_substitution(Substitution("-assignmentLink-", link))
    mail.template_id = "89c4a861-283c-4ec5-8cef-3a3198e31b95"
    response = sg.client.mail.send.post(request_body=mail.get())
    print(response.status_code)
    print(response.body)
    print(response.headers)
def sendCheckFilename(email, assignment, link, errors):
    from_email = Email("*****@*****.**")
    subject = "{} Submission Errors".format(assignment)
    to_email = Email(email)

    content = Content("text/html", "<br/>".join(errors))
    mail = Mail(from_email, subject, to_email, content)
    user = User.query.filter_by(email=email).first()
    mail.personalizations[0].add_substitution(Substitution("-name-", user.firstname))
    mail.personalizations[0].add_substitution(Substitution("-assignmentLink-", link))
    mail.template_id = "c837c4d6-91d8-415a-bbf3-076889b13bd2"
    response = sg.client.mail.send.post(request_body=mail.get())
    print(response.status_code)
    print(response.body)
    print(response.headers)
Пример #10
0
def send_email(user: User, subject: str, from_email: str, substitutions: [Dict[Any, Any]], content: str='text') -> Dict[
    str, str]:
    """
    This function sends an email using the SendGrid API
    Args:
       from_email: the email from which the email is sent
       user: the USer object containing the name and email address of the intended recipient
       subject: subject of email
       content: content

    Returns:
       Dict[str, str]: Dictionary containing HTTP response

    """
    content = Content("text/html", content)
    sendgrid_api = os.getenv("SENDGRID_API")
    sg = sendgrid.SendGridAPIClient(apikey=sendgrid_api)
    from_email = Email(from_email, name="Service Admin")
    to_email = Email(user.email, user.first_name)
    m = Mail(from_email, subject, to_email, content)
    for key, value in substitutions.items():
        m.personalizations[0].add_substitution(Substitution(key, value))
    if os.environ.get('ENV') == 'test':
        settings = MailSettings()
        settings.sandbox_mode = SandBoxMode(enable=True)
        m.mail_settings = settings
    m.template_id = '5a1b969f-77c5-4d27-8b6e-e77c9c237a8e'
    try:
        response = sg.client.mail.send.post(request_body=m.get())
    except exceptions.BadRequestsError as e:
        exit()
    return response
Пример #11
0
    def post(self, request):
        email = request.data['username']
        user = User.objects.get(username=email)

        profile_id = user.profile.id
        profile = Profile.objects.get(id=profile_id)
        profile.password_reset_code = Profile.generate_password_reset_code()
        profile.save()
        url = 'https://bquest.ucladevx.com/password'
        if settings.DEBUG:
            url = 'http://*****:*****@bquest.ucladevx.com')
        to_email = Email(email)
        subject = 'BQuest User Password Reset'
        reset_link = "{}?code={}&userid={}".format(url,
                                                   profile.password_reset_code,
                                                   user.id)
        content = Content('text/html', 'N/A')
        mail = Mail(from_email, subject, to_email, content)
        mail.personalizations[0].add_substitution(
            Substitution('password_reset_link', reset_link))
        mail.template_id = PASSWORD_RESET_TEMPLATE

        sg = sendgrid.SendGridAPIClient(apikey=settings.SENDGRID_API_KEY)
        response = sg.client.mail.send.post(request_body=mail.get())
        if not (200 <= response.status_code < 300):
            raise ValidationError(
                {'sendgrid_status_code': response.status_code})
        return HttpResponse(status=200)
Пример #12
0
def send_mfa_code_email(mfa_instance, mfa_code):
    """
    Sends the MFA Code text message to the user.

    :param mfa_instance: :class:`MultiFactorAuth` instance to use.
    :param mfa_code: MFA code in the form of a string.

    :raises deux.exceptions.EmailError: To tell system that the email failed to send.
    """
    sid = mfa_settings.SENDGRID_API_KEY
    template_id = mfa_settings.SENDGRID_TEMPLATE_ID
    sender_email = mfa_settings.SENDGRID_SENDER_EMAIL
    subject = mfa_settings.SENDGRID_MAIL_SUBJECT
    mfa_text = strings.MFA_CODE_TEXT_MESSAGE.format(code=mfa_code)

    sg = sendgrid.SendGridAPIClient(api_key=sid)
    from_email = Email(sender_email)
    to_email = Email(mfa_instance.email)
    content = Content("text/html", mfa_text)

    mail = Mail(from_email=from_email,
                subject=subject,
                to_email=to_email,
                content=content)

    if template_id:
        mail.personalizations[0].add_substitution(
            Substitution('%mfa_text%', mfa_text))
        mail.template_id = template_id

    # Todo: add code to deal with incorrect email recipient
    try:
        sg.client.mail.send.post(request_body=mail.get())
    except urllib.HTTPError:
        raise EmailError()
Пример #13
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()
Пример #14
0
def send_feedback(user, message):
    substitutions = [Substitution('-message-', message.encode('utf-8'))]
    mails = [Email(email=admin[1], name=admin[0]) for admin in settings.ADMINS]
    sendgrid_api(
        obtain_mail(personalization=obtain_personalization(user,
                                                           substitutions,
                                                           to_mails=mails),
                    template=settings.SENDGRID_FEEDBACK))
Пример #15
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)
        )
Пример #16
0
    def create_mail(self):
        """
        Creates email to send to this user
        """

        to_email = Email(self.email)
        from_email = Email("*****@*****.**")
        subject = User.template_dict[self.template]['subject']
        template_id = User.template_dict[self.template]['template_id']
        content = Content("text/plain", "text")
        mail = Mail(from_email, subject, to_email, content)
        mail.personalizations[0].add_substitution(
            Substitution("-name-", self.name))
        mail.personalizations[0].add_substitution(
            Substitution("-city-", "Denver"))
        mail.template_id = template_id

        return mail
Пример #17
0
def send_sg_mail(message_id, sender_name, body, to_email):
    sg = sendgrid.SendGridAPIClient(apikey=settings.SENDGRID_API_KEY)

    from_email = Email("*****@*****.**")
    to_email = Email(to_email)
    body = Content("text/html", body)
    subject = "I'm replacing the subject tag"
    mail = Mail(from_email, subject, to_email, body)
    mail.personalizations[0].add_substitution(
        Substitution("%pal_name%", sender_name))
    mail.personalizations[0].add_substitution(
        Substitution("<%url%>",
                     "https://persice.com/messages/{}".format(message_id)))
    mail.set_template_id(settings.SENDGRID_TEMPLATE_ID)
    try:
        response = sg.client.mail.send.post(request_body=mail.get())
    except urllib.HTTPError as e:
        print e.read()
    print(response.status_code, str(response.body), str(response.headers))
Пример #18
0
    def post(self, request, *args, **kwargs):
        
        mentor_id = int(self.kwargs['mentor_id'])
        mentor = get_object_or_404(Mentor, id=mentor_id)
        mentor_email = mentor.profile.user.email

        phone_num = request.data.get('phone', '')
        preferred_mentee_email = request.data.get('preferred_mentee_email', '')
        user_message = request.data.get('message', 'No message entered')

        mentee_user=self.request.user
        mentee_profile = get_object_or_404(Profile, user=mentee_user)
        mentee_name = mentee_user.first_name + ' ' + mentee_user.last_name
        phone_html = '' if phone_num=='' else ('<b>Phone Number:</b> ' + phone_num)
        email_html = '<b>Email:</b> ' + preferred_mentee_email

        if mentor.profile.notifications_enabled is True:
            from_email =  Email('*****@*****.**')
            to_email = Email(mentor_email)
            subject = 'New Request from BQuest'
            content = Content('text/html', 'N/A')
            mail = Mail(from_email, subject, to_email, content)
            mail.personalizations[0].add_substitution(Substitution('mentee_name', mentee_name))
            mail.personalizations[0].add_substitution(Substitution('user_message', user_message))
            mail.personalizations[0].add_substitution(Substitution('email_html', email_html))
            mail.personalizations[0].add_substitution(Substitution('phone_html', phone_html))
            mail.template_id = REQUEST_TEMPLATE
            sg = sendgrid.SendGridAPIClient(apikey=settings.SENDGRID_API_KEY)
            response = sg.client.mail.send.post(request_body=mail.get())
            if not (200 <= response.status_code < 300):
                raise ValidationError({'sendgrid_status_code': response.status_code})

        new_request = Request(
            mentee=mentee_profile,
            mentor=mentor,
            email_body=user_message,
            preferred_mentee_email=preferred_mentee_email,
            phone=phone_num,
        )

        new_request.save()

        return Response(RequestSerializer(new_request).data)
Пример #19
0
    def send_new_host_email_to_vacayo(cls, host):
        try:
            from_email = cls.from_email
            to_email = cls.from_email
            subject = 'Vacayo Superhost Registration'
            content = Content("text/html", 'TESTING')

            mail = Mail(from_email, subject, to_email, content)
            mail.template_id = '7404049e-36da-4eb6-99ca-417017fb2289'
            personalization = mail.personalizations[0]
            personalization.add_substitution(
                Substitution("-first_name-", host.user.first_name))
            personalization.add_substitution(
                Substitution("-last_name-", host.user.last_name))

            cls.sg.client.mail.send.post(request_body=mail.get())
            return True
        except (Exception, ) as e:
            return False
Пример #20
0
    def send_new_property_email_to_vacayo(cls, address):
        try:
            from_email = cls.from_email
            to_email = cls.from_email
            subject = 'Vacayo Rental Offer'
            content = Content("text/html", 'TESTING')

            mail = Mail(from_email, subject, to_email, content)
            mail.template_id = '5e8cabc6-aa9f-49fb-b4c1-effe3e00cf84'
            personalization = mail.personalizations[0]
            personalization.add_substitution(
                Substitution("-first_name-", 'Vacayo'))
            personalization.add_substitution(Substitution(
                "-address-", address))

            cls.sg.client.mail.send.post(request_body=mail.get())
            return True
        except (Exception, ) as e:
            return False
Пример #21
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()
Пример #22
0
    def test_personalizations_resolution(self):
        """
        Tests that adding a Personalization() object directly to an EmailMessage object
        works as expected.

        Written to test functionality introduced in the PR:
        https://github.com/sklarsa/django-sendgrid-v5/pull/90
        """
        msg = EmailMessage(
            subject="Hello, World!",
            body="Hello, World!",
            from_email="Sam Smith <*****@*****.**>",
            to=["John Doe <*****@*****.**>", "*****@*****.**"],
            cc=["Stephanie Smith <*****@*****.**>"],
            bcc=["Sarah Smith <*****@*****.**>"],
            reply_to=["Sam Smith <*****@*****.**>"],
        )

        # Tests that personalizations take priority
        test_str = "*****@*****.**"
        test_key_str = "my key"
        test_val_str = "my val"
        personalization = Personalization()

        if SENDGRID_5:
            personalization.add_to(Email(test_str))
            personalization.add_cc(Email(test_str))
            personalization.add_bcc(Email(test_str))
        else:
            personalization.add_to(To(test_str))
            personalization.add_cc(Cc(test_str))
            personalization.add_bcc(Bcc(test_str))

        personalization.add_custom_arg(CustomArg(test_key_str, test_val_str))
        personalization.add_header(Header(test_key_str, test_val_str))
        personalization.add_substitution(
            Substitution(test_key_str, test_val_str))

        msg.personalizations = [personalization]

        result = self.backend._build_sg_mail(msg)

        personalization = result["personalizations"][0]

        for field in ("to", "cc", "bcc"):
            data = personalization[field]
            self.assertEqual(len(data), 1)
            self.assertEqual(data[0]["email"], test_str)

        for field in ("custom_args", "headers", "substitutions"):
            data = personalization[field]
            self.assertEqual(len(data), 1)
            self.assertIn(test_key_str, data)
            self.assertEqual(test_val_str, data[test_key_str])
Пример #23
0
def obtain_personalization(user,
                           substitutions=None,
                           to_mails=None,
                           to_mail=None):
    personalization = Personalization()

    if to_mail:
        personalization.add_to(Email(to_mail))
    else:
        personalization.add_to(Email(user.email))

    personalization.add_substitution(Substitution('-name-', user.full_name))
    personalization.add_substitution(Substitution('-username-', user.username))
    personalization.add_substitution(Substitution('-email-', user.email))
    if substitutions:
        for substitution in substitutions:
            personalization.add_substitution(substitution)
    if to_mails:
        for mail in to_mails:
            personalization.add_to(mail)
    return personalization
def sendSignupEmail(user):  # parameter is user object
    from_email = Email("*****@*****.**")
    subject = "Welcome {}!".format(user.firstname)
    to_email = Email(user.email)
    content = Content("text/html", "This year, the club will be utilizing this website to provide a variety of resources to improve our team's performance. Self made worksheets and tests will be submitted and graded through this site and rosters/other results will be easily available here.")
    mail = Mail(from_email, subject, to_email, content)
    mail.personalizations[0].add_substitution(Substitution("-name-", user.firstname))
    mail.template_id = "5dd8916f-1ed5-43ea-af23-65b5911fd63b"
    response = sg.client.mail.send.post(request_body=mail.get())
    print(response.status_code)
    print(response.body)
    print(response.headers)
Пример #25
0
def send_mail(recipient, confirm_url, template_id='494a8322-4f93-4a71-b8e1-6afb8dfa6ba6'):
    # Create a text/plain message
    me = '*****@*****.**'
    subject = 'Bienvenue à Forum Organisation!'
    sg = sendgrid.SendGridAPIClient(apikey=os.environ.get('SENDGRID_API_KEY'))
    # Creating mail
    mail = Mail()
    mail.from_email = Email(me)
    mail.template_id = template_id
    personalization = Personalization()
    personalization.add_to(Email(recipient))
    mail.add_personalization(personalization)
    mail.personalizations[0].add_substitution(Substitution('-registration_link-', confirm_url))
    mail.personalizations[0].add_substitution(Substitution('-subject-', subject))

    # Sending email
    try:
        response = sg.client.mail.send.post(request_body=mail.get())
        return f'Email sent. {response}'
    except:
        return 'Email not sent.'
Пример #26
0
def send_no_certificate_mail(name, email, event):
    template = templates['CERTIFICATE_NOT_EMITTED']

    mail = Mail()
    mail.from_email = Email(template['FROM_EMAIL'], template['FROM_NAME'])
    mail.template_id = template['ID']
    mail.add_category(Category(template['CATEGORY']))

    personalization = Personalization()
    personalization.add_substitution(
        Substitution("%first_name%",
                     name.split()[0]))
    personalization.add_substitution(Substitution("%event_name%", event.name))
    personalization.add_to(Email(email, name))
    mail.add_personalization(personalization)

    try:
        response = sg.client.mail.send.post(request_body=mail.get())
        return True
    except Exception as e:
        print(response.body)
        raise e
Пример #27
0
def send_mail(recipient, subject, body):
    # Create a text/plain message
    me = '*****@*****.**'
    sg = sendgrid.SendGridAPIClient(apikey=os.environ.get('SENDGRID_API_KEY'))
    # Creating mail
    mail = Mail()
    mail.from_email = Email(me, 'Cinq minutes de pause')
    mail.template_id = 'c871e900-fc06-45b5-b037-7ec58821ce27'
    # Substitutes
    personalization = Personalization()
    personalization.add_to(Email(recipient))
    mail.add_personalization(personalization)
    mail.personalizations[0].add_substitution(Substitution('-body-', body))
    mail.personalizations[0].add_substitution(
        Substitution('-subject-', subject))

    # Sending email
    try:
        sg.client.mail.send.post(request_body=mail.get())
    except Exception as error:
        print(
            f'Email not sent for {recipient}. Following error has occured:\n{error}'
        )
Пример #28
0
def send_email(to_email, certificateLink):
    from_email = Email(app.config.get('FROM_EMAIL'))
    to_email = Email(to_email)
    content = Content('text/html', ' ')
    mail = Mail(from_email, ' ', to_email, content)
    mail.personalizations[0].add_substitution(
        Substitution("-certificateLink-", certificateLink)
    )
    mail.template_id = app.config.get('SENDGRID_TEMPLATE_ID')

    try:
        sendgrid.client.mail.send.post(request_body=mail.get())
    except Exception:
        pass
    def send_email(receivers,
                   subject,
                   content,
                   template_id=None,
                   text_replacements=None,
                   sender_name=None,
                   sender_email=None,
                   attachments=None,
                   cc_list=None,
                   bcc_list=None):
        print(os.environ.get('SENDGRID_API_KEY'), '   is the sendgrid api key')
        sendgrid_client = sendgrid.SendGridAPIClient(
            api_key=os.environ.get('SENDGRID_API_KEY'))
        sender = sendgrid.Email(name=sender_name, email=sender_email)
        mail = Mail(from_email=sender, subject=subject, content=content)

        personalization = Personalization()

        if len(receivers) == 0:
            error = Error({'detail': 'Please enter receiver mailId'},
                          status=status.HTTP_400_BAD_REQUEST)
            return error, None
        else:
            for receiver in receivers:
                personalization.add_to(receiver)
        personalization.add_to(receivers[0])

        for cc in cc_list and cc_list is not None:
            personalization.add_cc(cc)

        for bcc in bcc_list and bcc_list is not None:
            personalization.add_bcc(bcc)

        mail.add_personalization(personalization)

        if text_replacements is not None:
            for text_replacement in text_replacements:
                for key, value in text_replacement.items():
                    mail.personalizations[0].add_substitution(
                        Substitution(key, value))
        mail.template_id = template_id

        if attachments is not None:
            for attachment in attachments:
                mail.add_attachment(attachment)

        response = sendgrid_client.client.mail.send.post(
            request_body=mail.get())
        return {'status': True, 'response': response.body.decode().strip()}
def get_text_cordinate_substituitions(a):
    b = a.imagetextcordinate_set.all()
    embed_image = []
    for any in b:
        top = str(any.top)
        right = str(any.right)
        bottom = str(any.bottom)
        left = str(any.left)
        link = str(any.link)
        true = '<area shape="rect" coords="' + top + ',' + right + ',' + bottom + ',' + left + '"' + ' ' + 'href="' + link + '"' + 'alt="Compunet" / >'
        embed_image.append(true)

    links = ''.join(embed_image)
    sub = Substitution('--textlink--', links)

    return sub