Example #1
0
def send_email_to_user (email_args):

	user_emails = [email_args['user'].email]
	subject = email_args['subject']
	content = email_args['content']
	html_content = email_args['html_content']

	msg = EmailMultiAlternatives(
		subject=subject,
		body=content,
		from_email= settings.EMAIL_SENDER_PREFIX + " <*****@*****.**>",
		to=user_emails,
		headers={'Reply-To': "Support <*****@*****.**>"} # optional extra headers
	)
	msg.attach_alternative(html_content, "text/html")
	# msg.mixed_subtype = 'related'

	# # Load the image you want to send at bytes
	# img_data = open(settings.SETTINGS_PATH + "/resources/resource_images/email_logo.jpg", 'rb').read()
	# # Now create the MIME container for the image
	# img = MIMEImage(img_data, 'jpg')
	# img.add_header('Content-Id', '<email_logo>')  # angle brackets are important
	# msg.attach(img)
	msg.send()

	# Optional Mandrill-specific extensions:
	#msg.tags = ["one tag", "two tag", "red tag", "blue tag"]
	msg.metadata = {'user_id': email_args['user'].pk, 'user_name': email_args['user'].username}

	# Send it:
	msg.send()
def initialise_email(bookmark, campaign_source):
    campaign_name = "monthly alert %s" % date.today().strftime("%Y-%m-%d")
    email_id = "/email/%s/%s/%s" % (campaign_name, campaign_source,
                                    bookmark.id)
    if isinstance(bookmark, NCSOConcessionBookmark):
        subject_prefix = "Your update about "
    else:
        subject_prefix = "Your monthly update about "
    msg = EmailMultiAlternatives(
        truncate_subject(subject_prefix, bookmark.name),
        "...placeholder...",
        settings.DEFAULT_FROM_EMAIL,
        [bookmark.user.email],
    )
    metadata = {
        "subject": msg.subject,
        "campaign_name": campaign_name,
        "campaign_source": campaign_source,
        "email_id": email_id,
    }
    msg.metadata = metadata
    msg.qs = ga_tracking_qs(metadata)
    # Set the message id now, so we can reuse it
    msg.extra_headers = {"message-id": msg.message()["message-id"]}
    return msg
Example #3
0
def sendMail(request):
    if request.method == 'GET':
        mail = Mail.objects.all()
        serializer = MailSerializer(mail, many=True)
        return Response(serializer.data)

    elif request.method == 'POST':
        serializer = MailSerializer(data=request.DATA)
        if serializer.is_valid():
            serializer.save()
            remitente = request.DATA['remitente']
            destinatario = request.DATA['destinatario']
            asunto = request.DATA['asunto']
            mensaje = request.DATA['mensaje']

            msg = EmailMultiAlternatives(
                subject="%s" % asunto,
                body="This is the text email body",
                from_email="<%s>" % remitente,
                to=["Recipient One <%s>" % destinatario],
                headers={'Reply-To': "Service <*****@*****.**>"
                         }  # optional extra headers
            )
            msg.attach_alternative("<p>%s</p>" % mensaje, "text/html")
            msg.tags = ["one tag", "two tag", "red tag", "blue tag"]
            msg.metadata = {'user_id': "8675309"}
            msg.send()
            return Response("Mail sent to: %s" % destinatario)
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        else:
            return Response(serializer.data,
                            status=status.HTTP_400_BAD_REQUEST)
Example #4
0
def send_confirmation_email(request, user):
    current_site = get_current_site(request)
    uid = urlsafe_base64_encode(force_bytes(user.pk))
    token = account_activation_token.make_token(user)
    html_message = loader.render_to_string(
        'account_activation_email.html', {
            'user': user,
            'domain': request.META['HTTP_HOST'],
            'uid': uid,
            'token': token,
            'referral_link': user.profile.referral.url
        })

    message = 'http://' + request.META['HTTP_HOST'] + '/activate/' + str(
        uid) + '/' + str(token)
    subject = 'Thank you for signing up! '
    from_email = 'Check My Keywords <*****@*****.**>'
    msg = EmailMultiAlternatives(
        subject=subject,
        body=message,
        from_email=from_email,
        to=[user.first_name + ' ' + user.last_name + '<' + user.email + '>'],
        reply_to=["Support <*****@*****.**>"])

    # Include an inline image in the html:

    html = html_message
    msg.attach_alternative(html, "text/html")

    # Optional Anymail extensions:
    msg.metadata = {"user_id": request.user.id}
    msg.tags = ["confirmation_email"]
    msg.track_clicks = True
    # Send it:
    msg.send()
Example #5
0
def send_trigger_email(
        subject_email,
        from_email,
        to_email,
        content_email,
        content_type,
    ):

    msg = EmailMultiAlternatives(
        subject=subject_email,
        from_email=from_email,
        to=to_email,
    )
    msg.attach_alternative(
        content_email,
        content_type,
    )
    msg.tags = []
    msg.metadata = {}
    msg.send()

    response_f = {}
    response_m = msg.mandrill_response[0]
    response_f = response_m
    if response_f['status'] == 'sent':
        print """as expected, the message was sent.
        """
    else:
        # msg.error(msg)
        print """
Example #6
0
def send_reset_email(request, user):
    current_site = get_current_site(request).domain
    reset_url = 'https://' + 'checkmykeywords.com' + '/user/change/password/' + str(
        user.profile.password_reset_token)
    message = reset_url
    subject = 'Reset your password'
    from_email = 'Check My Keywords <*****@*****.**>'
    html_message = loader.render_to_string('account_reset_email.html', {
        'user': user,
        'reset_url': reset_url
    })
    msg = EmailMultiAlternatives(
        subject=subject,
        body=message,
        from_email=from_email,
        to=[user.first_name + ' ' + user.last_name + '<' + user.email + '>'],
        reply_to=["Support <*****@*****.**>"])

    # Include an inline image in the html:

    html = html_message
    msg.attach_alternative(html, "text/html")

    # Optional Anymail extensions:
    msg.metadata = {"user_id": request.user.id}
    msg.tags = ["reset_email"]
    msg.track_clicks = True

    # Send it:
    msg.send()
Example #7
0
 def send_email(self,
                subject=None,
                body=None,
                sg_template_on=False,
                sg_template=None,
                template=None,
                campaign=None):
     from anymail.message import AnymailMessage
     from django.core.mail import send_mail, EmailMultiAlternatives
     from django.utils.html import strip_tags
     if template is not None:
         try:
             html_content = render_to_string(
                 f"contact_management/{template}", self.__dict__)
         except:
             html_content = None
         note = template
     else:
         html_content = None
         note = body
     if html_content is not None:
         plain_content = strip_tags(html_content)
     else:
         plain_content = body
     message = EmailMultiAlternatives(subject, plain_content,
                                      DEFAULT_FROM_EMAIL, [self.email])
     if sg_template_on == True:
         message.template_id = sg_template
         template = sg_template
     message.metadata = {
         "account_id": self.account_name,
         "contact_id": self.id,
         "template": template,
         "campaign": campaign,
         "email_source": "VCM",
         "contact_type": "LEAD",
         "FIRST_NAME": self.first_name,
         "LAST_NAME": self.last_name,
         "ACCOUNT_NAME": self.account_name,
         'DATETIME': datetime.now().isoformat()
     }
     if html_content is not None:
         message.attach_alternative(html_content, "text/html")
     message.track_clicks = True
     message.track_opens = True
     try:
         message.send()
         status = message.anymail_status
         status.message_id
         n = Note(lead=self,
                  date=datetime.now(),
                  note=note,
                  follow_up_date=datetime.now() + timedelta(days=14),
                  contact_type='EMAIL')
         n.save()
         print(f"email sent to {self}")
     except:
         print('message did not send to', self)
Example #8
0
def send_email(subject,
               email,
               template,
               context,
               tags=list(),
               metadata=list(),
               request=None,
               reply_to=settings.DEFAULT_FROM_EMAIL,
               send_at=None):
    """
    Renders template blocks and sends an email.

    :param subject:
    :param email:
    :param template:
    :param context:
    :param tags:
    :param metadata:
    :param request:
    :param reply_to:
    :param send_at:
    :return:
    """
    context.update({
        'STATIC_URL': settings.STATIC_URL,
        'domain': settings.HOSTNAME
    })
    if request:
        context = RequestContext(request, context)

    template = get_template(template)
    html_content = template.render(Context(context))

    text_content = strip_tags(html_content)
    kwargs = dict(
        subject=subject,
        body=text_content.strip(),
        from_email=settings.DEFAULT_FROM_EMAIL,
        to=[email],
        reply_to=[reply_to],
    )
    message = EmailMultiAlternatives(**kwargs)
    message.attach_alternative(html_content, 'text/html')

    # Email tags
    message.tags = tags
    # Email metadata
    message.metadata = metadata

    # datetime.now(utc) + timedelta(hours=1)
    if send_at:
        message.send_at = send_at

    message. async = settings.EMAIL_ASYNC
    message.track_clicks = True
    message.track_opens = True

    message.send(fail_silently=True)
Example #9
0
def send_mail(to, subject, plain_text, html, tags=[], metadata={}):
    print to
    msg = EmailMultiAlternatives(
        subject=subject,
        body=plain_text,
        to=[to],
    )
    msg.attach_alternative(html, 'text/html')

    msg.tag = tags
    msg.metadata = {}

    msg.send()
Example #10
0
    def send_email(self, context={}):
        (html_email, txt_email) = self.render_email(**context)

        msg = EmailMultiAlternatives(
            subject=self.email_subject,
            body=txt_email,
            to=self.get_recipients(**context),
        )
        msg.attach_alternative(html_email, "text/html")

        msg.tags = self.get_tags(**context)

        msg.metadata = self.get_metadata(**context)

        msg.send()
Example #11
0
def send(emailentry):
    """
    Sends the email entry through the configured email backend.
    @type emailentry: EmailEntry
    """
    plain_body = render_plain(emailentry.kind, emailentry.context)
    rich_body = render_html(emailentry.kind, emailentry.context)

    email = EmailMultiAlternatives(subject=emailentry.subject,
                                   body=plain_body,
                                   to=emailentry.recipients.split(','),
                                   from_email=emailentry.sender,
                                   reply_to=emailentry.reply_to.split(','))
    email.encoding = 'utf-8'

    # Attach HTML alternative
    if rich_body:
        email.attach_alternative(rich_body, 'text/html')

    # Attach already embedded images. Only the actually used ones.
    for img in emailentry.kind.iter_all_images():
        content_id = img.content_id[1:-1]
        if content_id in rich_body:
            image = MIMEImage(img.image.read())
            image.add_header('Content-ID', content_id)
            email.attach(image)

    # Attach regular files
    for att in emailentry.attachments.all():
        email.attach(filename=att.name,
                     content=att.attached_file.read(),
                     mimetype=att.content_type)
        increment(settings.METRIC['SEND_ATTACHS'])

    # Attach fixed metadata and extras provided by the entry
    email.metadata = {
        'customer_id': emailentry.customer_id,
        'kind': str(emailentry.kind),
        'email_id': emailentry.id
    }
    if len(emailentry.metadata) > 0:
        email.metadata.update(emailentry.metadata)

    sent = send_with_backend(email, emailentry)
    if not sent:
        return None
    return email
Example #12
0
def make_email_with_campaign(bookmark, campaign_source):
    campaign_name = "monthly alert %s" % date.today().strftime("%Y-%m-%d")
    email_id = "/email/%s/%s/%s" % (campaign_name, campaign_source,
                                    bookmark.id)
    subject_prefix = 'Your monthly update about '
    msg = EmailMultiAlternatives(
        truncate_subject(subject_prefix, bookmark.name),
        "This email is only available in HTML", settings.SUPPORT_EMAIL,
        [bookmark.user.email])
    metadata = {
        "subject": msg.subject,
        "campaign_name": campaign_name,
        "campaign_source": campaign_source,
        "email_id": email_id
    }
    msg.metadata = metadata
    msg.qs = ga_tracking_qs(metadata)
    return msg
def make_email_with_campaign(bookmark, campaign_source):
    campaign_name = "monthly alert %s" % date.today().strftime("%Y-%m-%d")
    email_id = "/email/%s/%s/%s" % (
        campaign_name,
        campaign_source,
        bookmark.id)
    subject_prefix = 'Your monthly update about '
    msg = EmailMultiAlternatives(
        truncate_subject(subject_prefix, bookmark.name),
        "This email is only available in HTML",
        settings.SUPPORT_EMAIL,
        [bookmark.user.email])
    metadata = {"subject": msg.subject,
                "campaign_name": campaign_name,
                "campaign_source": campaign_source,
                "email_id": email_id}
    msg.metadata = metadata
    msg.qs = ga_tracking_qs(metadata)
    return msg
Example #14
0
    def send(self,
             to,
             text_body,
             html_body=None,
             subject=None,
             tags=None,
             metadata=None):
        """Send the e-mail.

        :param to: Recipient of the e-mail.
        :param text_body: Plain text e-mail body.
        :param html_body: Rich HTML e-mail body.
        :param subject:
            Subject. If not provided, the class instance variable will be used.
        """

        from_combined = '%s <%s>' % (
            self.from_name,
            self.from_email
        ) if self.from_name else self.from_email

        message = EmailMultiAlternatives(subject or self.subject,
                                         text_body,
                                         from_combined,
                                         [to])

        if html_body:
            message.attach_alternative(html_body, "text/html")

        # Attach any files.
        for filename, (data, mime_type) in self.attachments.items():
            message.attach(filename, data, mime_type)

        # Optional Mandrill-specific extensions:
        if tags:
            message.tags = tags
        if metadata:
            message.metadata = metadata

        # Send the message.
        message.send()
Example #15
0
def send_email(subject,
               to_address,
               text_email='',
               html_email='',
               tags=None,
               metadata=None):
    # to=["New User <*****@*****.**>", "*****@*****.**"]
    from_email = "emondo <{0}>".format(settings.DEFAULT_FROM_EMAIL)
    msg = EmailMultiAlternatives(subject=subject,
                                 body=text_email,
                                 from_email=from_email,
                                 to=to_address,
                                 reply_to=[from_email])

    msg.attach_alternative(html_email, "text/html")

    # Optional Anymail extensions:
    msg.metadata = metadata
    msg.tags = tags
    msg.track_clicks = True

    # Send it:
    msg.send()
Example #16
0
    def send_email(self,
                   subject=None,
                   body=None,
                   sg_template_on=False,
                   sg_template=None,
                   template=None,
                   campaign=None):
        from anymail.message import AnymailMessage
        from django.core.mail import send_mail, EmailMultiAlternatives
        from django.utils.html import strip_tags
        if template is not None:
            try:
                html_content = render_to_string(
                    f"contact_management/{template}", self.__dict__)
            except:
                html_content = None
            note = template
        else:
            html_content = None
            note = body
        if html_content is not None:
            plain_content = strip_tags(html_content)
        else:
            plain_content = body

        message = EmailMultiAlternatives(subject, plain_content,
                                         DEFAULT_FROM_EMAIL, [self.email])

        if sg_template_on == True:
            message.template_id = sg_template
            template = sg_template
            note = f"SENDGRID TEMPLATE {sg_template}"

        message.metadata = {
            "account_id": self.account.id,
            "contact_id": self.id,
            "template": template,
            "campaign": campaign,
            "email_source": "VCM",
            "contact_type": "CONTACT",
            "FIRST_NAME": self.first_name,
            "LAST_NAME": self.last_name,
            "ACCOUNT_NAME": self.account.name,
            'DATETIME': datetime.now().isoformat(),
        }

        if html_content is not None:
            message.attach_alternative(html_content, "text/html")
        message.track_clicks = True
        message.track_opens = True
        try:
            print('we are here')
            print(template)
            message.send()
            print('we just sent??')
            status = message.anymail_status
            status.message_id
            print(status.message_id, 'MID!!')

            n = Note(contact=self,
                     date=datetime.now(),
                     note=note,
                     follow_up_date=datetime.now() + timedelta(days=14),
                     contact_type='EMAIL')
            print(n, 'NOTE')
            n.save()
            print(n.follow_up_date, 'NOTE SAVED')
        except Exception as errors:
            print(errors, 'this is the erro!')
            print('message did not send to', self)
Example #17
0
    def send_confirmation_email(self, registration):
        import os

        # create context 
        d = ConfirmationEmailView.get_extra_context(registration)
        c = Context(d)

        # create html/txt
        msg_plaintext = render_to_string('registration/confirmation_email.txt', c)
        msg_html      = render_to_string('registration/confirmation_email.html', c)

        # email settings
        subject = _('Thanks for signing up!')
        from_email = "WearHacks Montreal <%s>" % settings.DEFAULT_FROM_EMAIL
        to = [registration.email]
        headers = {'Reply-To': _("WearHacks Montreal Team <*****@*****.**>")}

        # mandrill settings
        tags = ['registration confirmation']
        if settings.DEBUG:
            tags.append('test')
        if registration.is_early_bird:
            tags.append('early bird')
        else:
            tags.append('student')
        metadata = {'order_id': registration.order_id}

        # ticket
        ticket_file_path = os.path.join(settings.SITE_ROOT, registration.ticket_file.path)

        # try:
        #     fn = ''
        #     directory = os.path.join(settings.SITE_ROOT, 'media', 'orders')
        #     if not os.path.exists(directory):
        #         os.makedirs(directory)
        #     fn = os.path.join(directory, registration.order_id + '.html')
        #     with open(fn, 'w') as f:
        #         f.write(msg_html)
        # except Exception, e:
        #     if fn:
        #         print "Could not write to %s" % (fn)
        #     print 'ERROR: %s' % (str(e))

        msg = EmailMultiAlternatives(
            subject=subject,
            body=msg_plaintext,
            from_email=from_email,
            to=to,
            reply_to=[from_email],
            headers=headers # optional extra headers
        )
        msg.attach_alternative(msg_html, "text/html")
        msg.attach_file(ticket_file_path)
        msg.tags = tags
        msg.metadata = metadata

        if not settings.DEBUG and not ( 
            hasattr(settings, 'FAKE_SEND_EMAIL') and settings.FAKE_SEND_EMAIL):
            msg.send()
        else:
            print 'Registration email at: %s ' % (
                reverse('confirmation_email', kwargs={'order_id' : registration.order_id}))
Example #18
0
    def send(self,
             to,
             text_body,
             html_body=None,
             subject=None,
             tags=None,
             metadata=None,
             cc=None,
             bcc=None,
             headers=None,
             important=None):
        """Send the e-mail.

        :param to: Recipient of the e-mail.
        :param text_body: Plain text e-mail body.
        :param html_body: Rich HTML e-mail body.
        :param subject:
            Subject. If not provided, the class instance variable will be used.
        :param tags: list of mandrill tags
        :param metadata: dict of mandrill metadata
        :param cc: list of emails this message should be CC'd to
        :param bcc: list of emails this message should be BCC'd to
        """

        from_combined = '%s <%s>' % (
            self.from_name,
            self.from_email
        ) if self.from_name else self.from_email

        cc = cc if cc is not None else self.cc
        bcc = bcc if bcc is not None else self.bcc
        headers = headers if headers is not None else self.headers

        message = EmailMultiAlternatives(subject or self.subject,
                                         text_body,
                                         from_combined,
                                         [to],
                                         cc=cc,
                                         bcc=bcc,
                                         headers=headers)

        if html_body:
            message.attach_alternative(html_body, "text/html")

        # Attach any files.
        for filename, (data, mime_type) in self.attachments.items():
            message.attach(filename, data, mime_type)

        # Optional Mandrill-specific extensions:
        if tags:
            message.tags = tags
        if metadata:
            message.metadata = metadata

        if important is None:
            important = self.important
        if important is not None:
            message.important = important

        # Send the message.
        message.send()
Example #19
0
    def save(self):

        data = self.cleaned_data
        
        u = User.objects.create(
            email = data.get("primary_email"),
            first_name = data.get("first_name"),
            last_name = data.get("last_name"),
            username = data.get("primary_email").split("@")[0][:30],
        )
        password = User.objects.make_random_password()
        u.set_password(password)
        u.save()

        m = Member.objects.create(
            user = u,
            bio = data.get('bio'),
            phone = data.get('phone'),
            role = data.get('role'),
            status = 'pending',
            photo = data.get('photo')
        )

        #import ipdb; ipdb.set_trace()
        groups = data.get("groups")

        for g in groups:
            g = Group.objects.get(name = g)
            m.groups.add(g)

        emails = data.get('secondary_emails');
        if emails:
            for e in emails.split(','):
                e, created = Email.objects.get_or_create(email = e.strip())
                m.secondary_emails.add(e)

        linkedin = data.get('linkedin')
        l, created = Profile.objects.get_or_create(url = linkedin, network = 'linkedin')
        m.profiles.add(l)

        twitter = data.get('twitter')
        t, created = Profile.objects.get_or_create(url = twitter, network = 'twitter')
        m.profiles.add(t)

        # Send mail to user
        #import ipdb; ipdb.set_trace()
        mail_to = settings.ADMIN_EMAIL if settings.DEBUG else data.get("primary_email")

        msg = EmailMultiAlternatives(
            subject = "Solicitud de alta",
            from_email = settings.FROM_EMAIL,
            to = [mail_to]
        )
        msg.tags = ["iniciador", "alta"]
        msg.metadata = {'user_id': m.id}
        msg.template_name = "alta-iniciador"
        msg.global_merge_vars = {
            'NAME': data.get("first_name"),
            'PASSWORD': password,
            'USERNAME': data.get("primary_email").split("@")[0][:30],
            #'WEBSITE': "<a href='" + data.get('linkedin') + "/*|TRACKINGNO|*'>Linkedin</a>"
        }
        print "Mail sent to:" + mail_to
        msg.send()

        # Send mail to iniciador
        mail_to = settings.ADMIN_EMAIL if settings.DEBUG else settings.FROM_EMAIL

        msg = EmailMultiAlternatives(
            subject = "Nueva solicitud de alta",
            from_email = settings.FROM_EMAIL,
            to = [mail_to]
        )
        msg.tags = ["iniciador", "alta", "gerencia", "user-" + str(m.id)]
        msg.metadata = {'user_id': m.id}
        msg.template_name = "aviso-a-gerencia-alta"
        msg.global_merge_vars = {
            'NAME': data.get("first_name"),
            'LASTNAME': data.get("last_name"),
            'UID': m.id,
            'SERVER': settings.SERVER,
            #'WEBSITE': "<a href='" + data.get('linkedin') + "/*|TRACKINGNO|*'>Linkedin</a>"
        }
        print "Mail sent to:" + mail_to
        msg.send()