Example #1
0
def emergencia_mail(request):
    nombre = request.POST.get("nombre")
    telefono = request.POST.get("telefono")
    latitud = request.POST.get("latitud")
    longitud = request.POST.get("longitud")
    mapa = request.POST.get("mapa")
    gmap = "https://maps.google.com/maps?z=16&t=m&q="+latitud+","+longitud

    from_email = 'Medikus <[email protected]>'
    subject = 'Alerta de emergencia enviada desde Medikus'
    tos = ["[email protected]","[email protected]","[email protected]"]
    message = ('<h2>Reporte de emergencia</h2>'
                    '<p>Nombre: '+nombre+'</p>'
                    '<p>Telefono: '+telefono+'</p>'
                    '<p>Latitud: '+latitud+'</p>'
                    '<p>Longitud: '+longitud+'</p>'
                    '<p>'+mapa+'</p>'
                    '<p>Google Maps: '+gmap+'</p>'
                    '<br/><p>Este mensaje ha sido generado autom&aacute;ticamente por Medikus</p>'
    )

    msg = EmailMultiAlternatives(subject, "", from_email,tos)
    msg.attach_alternative(message, "text/html")
    msg.send()
    return HttpResponse("OK", content_type="text/plain")
Example #2
0
def notify_cart_to_admin(profile, action):
    """send message by email"""
    notification_email = getattr(settings, 'BALAFON_NOTIFICATION_EMAIL', '')
    if notification_email:
        from_email = getattr(settings, 'DEFAULT_FROM_EMAIL')
        subject = _(u"New cart purchased on store")
        data = {
            'profile': profile,
            'action': action,
            'subject': subject,
        }
        the_template = get_template('Store/cart_notification_email.html')
        html_text = the_template.render(Context(data))
        text = dehtml(html_text)

        email = EmailMultiAlternatives(
            subject,
            text,
            from_email,
            [notification_email],
            headers={'Reply-To': profile.contact.email}
        )
        email.attach_alternative(html_text, "text/html")

        try:
            email.send()
        except Exception:
            logger.exception("notify_cart_to_admin")
Example #3
0
def send_activation_email(
        user=None, request=None, from_email=None,
        subject_template='users/activation_email_subject.html',
        email_template='users/activation_email.html', html_email_template=None):

    if not user.is_active and settings.USERS_VERIFY_EMAIL:
        token_generator = EmailActivationTokenGenerator()

        current_site = get_current_site(request)

        context = {
            'email': user.email,
            'site': current_site,
            'expiration_days': settings.USERS_EMAIL_CONFIRMATION_TIMEOUT_DAYS,
            'user': user,
            'uid': urlsafe_base64_encode(force_bytes(user.pk)),
            'token': token_generator.make_token(user=user),
            'protocol': 'https' if request.is_secure() else 'http',
        }

        subject = render_to_string(subject_template, context)
        # email subject *must not* contain newlines
        subject = ''.join(subject.splitlines())
        body = render_to_string(email_template, context)

        email_message = EmailMultiAlternatives(subject, body, from_email, [user.email])
        if html_email_template is not None:
            html_email = render_to_string(html_email_template, context)
            email_message.attach_alternative(html_email, 'text/html')

        email_message.send()
Example #4
0
    def send_first_share_to_blurblog_email(self, force=False):
        from apps.social.models import MSocialProfile, MSharedStory
        
        if not self.user.email:
            return

        sent_email, created = MSentEmail.objects.get_or_create(receiver_user_id=self.user.pk,
                                                               email_type='first_share')
        
        if not created and not force:
            return
        
        social_profile = MSocialProfile.objects.get(user_id=self.user.pk)
        params = {
            'shared_stories': MSharedStory.objects.filter(user_id=self.user.pk).count(),
            'blurblog_url': social_profile.blurblog_url,
            'blurblog_rss': social_profile.blurblog_rss
        }
        user    = self.user
        text    = render_to_string('mail/email_first_share_to_blurblog.txt', params)
        html    = render_to_string('mail/email_first_share_to_blurblog.xhtml', params)
        subject = "Your shared stories on NewsBlur are available on your Blurblog"
        msg     = EmailMultiAlternatives(subject, text, 
                                         from_email='NewsBlur <%s>' % settings.HELLO_EMAIL,
                                         to=['%s <%s>' % (user, user.email)])
        msg.attach_alternative(html, "text/html")
        msg.send(fail_silently=True)
        
        logging.user(self.user, "~BB~FM~SBSending first share to blurblog email to: %s" % self.user.email)
Example #5
0
 def send_launch_social_email(self, force=False):
     if not self.user.email or not self.send_emails:
         logging.user(self.user, "~FM~SB~FRNot~FM sending launch social email for user, %s: %s" % (self.user.email and 'opt-out: ' or 'blank', self.user.email))
         return
     
     sent_email, created = MSentEmail.objects.get_or_create(receiver_user_id=self.user.pk,
                                                            email_type='launch_social')
     
     if not created and not force:
         logging.user(self.user, "~FM~SB~FRNot~FM sending launch social email for user, sent already: %s" % self.user.email)
         return
     
     delta      = datetime.datetime.now() - self.last_seen_on
     months_ago = delta.days / 30
     user    = self.user
     data    = dict(user=user, months_ago=months_ago)
     text    = render_to_string('mail/email_launch_social.txt', data)
     html    = render_to_string('mail/email_launch_social.xhtml', data)
     subject = "NewsBlur is now a social news reader"
     msg     = EmailMultiAlternatives(subject, text, 
                                      from_email='NewsBlur <%s>' % settings.HELLO_EMAIL,
                                      to=['%s <%s>' % (user, user.email)])
     msg.attach_alternative(html, "text/html")
     msg.send(fail_silently=True)
     
     logging.user(self.user, "~BB~FM~SBSending launch social email for user: %s months, %s" % (months_ago, self.user.email))
Example #6
0
def send_html_mail(
    subject,
    message,
    message_html,
    from_email,
    recipient_list,
    priority="medium",
    fail_silently=False,
    auth_user=None,
    auth_password=None,
):
    """
    Function to queue HTML e-mails
    """
    from django.utils.encoding import force_unicode
    from django.core.mail import EmailMultiAlternatives
    from mailer.models import make_message

    priority = PRIORITY_MAPPING[priority]

    # need to do this in case subject used lazy version of ugettext
    subject = force_unicode(subject)
    message = force_unicode(message)

    msg = make_message(subject=subject, body=message, from_email=from_email, to=recipient_list, priority=priority)
    email = msg.email
    email = EmailMultiAlternatives(email.subject, email.body, email.from_email, email.to)
    email.attach_alternative(message_html, "text/html")
    msg.email = email
    msg.save()
    return 1
Example #7
0
def email_about_suggested_event_comment(comment, base_url):
    base_url = fix_base_url(base_url)
    emails = _get_add_event_emails()
    event_title = comment.suggested_event.title
    if len(event_title) > 30:
        event_title = '%s...' % event_title[:27]
    subject = (
        '[Air Mozilla] New comment on suggested event: %s' % event_title
    )
    context = {
        'event': comment.suggested_event,
        'comment': comment,
        'base_url': base_url,
        'subject': subject,
    }
    html_body = render_to_string(
        'suggest/_email_comment.html',
        context
    )
    assert emails
    body = html2text(html_body)
    email = EmailMultiAlternatives(
        subject,
        body,
        settings.EMAIL_FROM_ADDRESS,
        emails
    )
    email.attach_alternative(html_body, "text/html")
    email.send()
Example #8
0
File: token.py Project: Renzo04/api
def enviar_mail_reiniciar_password(usuario):
    # Se genera token con email del usuario.
    token_link = generar_token(usuario.email, url=True)

    # Creación de URL de confirmación
    reset_url = FRONTEND_URL + 'reset-password/' + token_link

    # Obtención de templates html y txt de emails.
    htmly = loader.get_template('emails/html/reiniciar_password.html')
    text = loader.get_template('emails/txt/reiniciar_password.txt')

    # Definición de variables de contexto
    variables = {
        'usuario': usuario,
        'reset_url': reset_url,
    }
    html_content = htmly.render(variables)
    text_content = text.render(variables)

    # Creación y envío de email.
    msg = EmailMultiAlternatives(
        'Reiniciar contraseña',
        text_content,
        to=[usuario.email]
    )

    msg.attach_alternative(html_content, "text/html")
    msg.send()
Example #9
0
    def render_mail(self, template_prefix, email, context):
        """
        Renders an e-mail to `email`.  `template_prefix` identifies the
        e-mail that is to be sent, e.g. "account/email/email_confirmation"
        """
        subject = render_to_string('{0}_subject.txt'.format(template_prefix),
                                   context)
        # remove superfluous line breaks
        subject = " ".join(subject.splitlines()).strip()
        subject = self.format_email_subject(subject)

        bodies = {}
        for ext in ['html', 'txt']:
            try:
                template_name = '{0}_message.{1}'.format(template_prefix, ext)
                bodies[ext] = render_to_string(template_name,
                                               context).strip()
            except TemplateDoesNotExist:
                if ext == 'txt' and not bodies:
                    # We need at least one body
                    raise
        if 'txt' in bodies:
            msg = EmailMultiAlternatives(subject,
                                         bodies['txt'],
                                         settings.DEFAULT_FROM_EMAIL,
                                         [email])
            if 'html' in bodies:
                msg.attach_alternative(bodies['html'], 'text/html')
        else:
            msg = EmailMessage(subject,
                               bodies['html'],
                               settings.DEFAULT_FROM_EMAIL,
                               [email])
            msg.content_subtype = 'html'  # Main content is now text/html
        return msg
Example #10
0
 def handle(self, *args, **options):
     plaintext = get_template('email/weekly.txt')
     htmly = get_template('email/weekly.html')
     all_users = User.objects.exclude(extra__emails=False)
     for user in all_users:
         # start by finding the ideas posted by a user
         commented_on_ideas = user.get_profile().comments_on_owned_ideas(7)
         self.stdout.write("user %s\n" %user)
         for idea in commented_on_ideas:
             self.stdout.write("you've got new comments on: %s\n" % idea.idea)
         #new_slates = user.slates.all()
         new_slates = user.slates.filter(
                 date_created__gte = datetime.date.today()-datetime.timedelta(7)
                 )
         self.stdout.write("you've joined %i slates \n" % len(new_slates))
         
         d = Context({ 'user': user })
         #actually send the e-mail
         if new_slates and commented_on_ideas:
             subject, from_email, to = 'Weekly Digest', '[email protected]', user.email
             text_content = plaintext.render(d)
             html_content = htmly.render(d)
             msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
             msg.attach_alternative(html_content, "text/html")
             if "final" in args:
                 try:
                     msg.send()
                 except:
                     self.stdout.write("failed to send email")
             else:
                 self.stdout.write("test success")
Example #11
0
File: token.py Project: Renzo04/api
def enviar_mail_activacion(usuario):
    # Se genera token con email del usuario.
    token_link = generar_token(usuario.email, url=True)
    token_clave = generar_token(usuario.id)

    # Creación de URL de confirmación
    confirm_url = FRONTEND_URL + 'activar-cuenta/' + token_link

    # Obtención de templates html y txt de emails.
    htmly = loader.get_template('emails/html/confirmar_cuenta.html')
    text = loader.get_template('emails/txt/confirmar_cuenta.txt')

    # Definición de variables de contexto
    variables = {
        'usuario': usuario,
        'confirm_url': confirm_url,
        'clave': token_clave
    }
    html_content = htmly.render(variables)
    text_content = text.render(variables)

    # Creación y envío de email.
    msg = EmailMultiAlternatives(
        'Bienvenido a Manos por gotas',
        text_content,
        to=[usuario.email]
    )

    msg.attach_alternative(html_content, "text/html")
    msg.send()
Example #12
0
def register(request):
    if request.method == "POST":
        #Preparing the user to store in the database
        user = User(
            username=request.POST.get('username'),
            password=make_password(request.POST.get('password')),
            email=request.POST.get('email'),
            isWarned=False,
            isAdmin=False,
            activationLink="".join( [random.choice(string.letters) for i in xrange(32)] ),
            registrationDate=timezone.now()
        )

        #Preparing the response
        response_data = {}
        response_data['username_already_taken'] = 'false'
        response_data['invalid_email']='false'
        response_data['email_already_taken'] = 'false'
        response_data['result'] = 'success'

        #Checking if the username exists in the database
        try:
            User.objects.get(username=user.username)
            usernameTaken = True
        except User.DoesNotExist:
            usernameTaken = False

        if usernameTaken==False:
            try:
                validate_email(user.email)
                user.save()
                #Preparing the email to send
                subject, from_email, to = 'SurveyVor Activation', '[email protected]', user.email
                html_content = render_to_string('Account/activation_mail.html', {'activationLink':user.activationLink})
                text_content = """
Congratulations!

Your registration is almost complete. To be able to access your account, click on the activation link bellow:
http://www.okarrakchou.com/account/activate/%s

Regards,
The Surveyvor Team
""" % (user.activationLink)
                # create the email, and attach the HTML version as well.
                msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
                msg.attach_alternative(html_content, "text/html")
                msg.send()
            except ValidationError:
                response_data['result'] = 'failure'
                response_data['invalid_email']='true'
            except IntegrityError:
                response_data['result'] = 'failure'
                response_data['email_already_taken']='true'
        else:
            response_data['result'] = 'failure'
            response_data['username_already_taken']='true'

        return HttpResponse(json.dumps(response_data), mimetype="application/json")
    else:
        return HttpResponse(0)
Example #13
0
def send_raw_email(recipients, subject, text, html):
    """
    Sends and multi-part (text and optionally HTML) email to a list of users or email addresses
    """
    to_addresses = []
    for recipient in recipients:
        if isinstance(recipient, User):
            to_addresses.append(recipient.email)
        elif isinstance(recipient, six.string_types):
            to_addresses.append(recipient)
        else:  # pragma: no cover
            raise ValueError("Email recipients must users or email addresses")

    from_address = getattr(settings, 'DEFAULT_FROM_EMAIL', '[email protected]')

    if getattr(settings, 'SEND_EMAILS', False):
        # send individual messages so as to not leak users email addresses, but use bulk send operation for speed
        messages = []
        for to_address in to_addresses:
            message = EmailMultiAlternatives(subject, text, from_email=from_address, to=[to_address])
            if html:
                message.attach_alternative(html, "text/html")
            messages.append(message)

        get_connection().send_messages(messages)
    else:  # pragma: no cover
        print("FAKE SENDING this email to %s:" % ", ".join(to_addresses))
        print("--------------------------------------- text -----------------------------------------")
        print(text)
        if html:
            print("--------------------------------------- html -----------------------------------------")
            print(html)
Example #14
0
def send_mail(subject, message_plain, message_html, email_from, email_to,
              custom_headers={}, attachments=()):
    """
    Build the email as a multipart message containing
    a multipart alternative for text (plain, HTML) plus
    all the attached files.
    """
    if not message_plain and not message_html:
        raise ValueError(_("Either message_plain or message_html should be not None"))

    if not message_plain:
        message_plain = html2text(message_html)

    message = {}

    message['subject'] = subject
    message['body'] = message_plain
    message['from_email'] = email_from
    message['to'] = email_to
    if attachments:
        message['attachments'] = attachments
    if custom_headers:
        message['headers'] = custom_headers

    msg = EmailMultiAlternatives(**message)
    if message_html:
        msg.attach_alternative(message_html, "text/html")
    msg.send()
Example #15
0
def sendMailToContacts(name, html, text):
    # Get a list of all of the current contactees
    contacts = ContactEmail.objects.all()
    email_addresses = []
    # Build E-Mail
    subject = str(name) + " has requested a Quote on SCCS"
    text_message = text
    html_message = html
    from_addr = "[email protected]"

    # Create List of e-mail addresses
    for address in contacts:
        email_addresses.append(address.email)

    try:
        # Get django e-mail settings
        connection = mail.get_connection()
        # Open E-Mail server connection
        connection.open()
        # Append RAW Text
        email_message = EmailMultiAlternatives(subject, text_message,
                                               from_addr, email_addresses,
                                               connection=connection)
        # Append HTML
        email_message.attach_alternative(html_message, "text/html")
        # Send Message
        email_message.send()

        connection.close()
    except Exception as err:
        connection.close()
        log(err)
Example #16
0
def send_activation_email(request, user):
    username = user.username
    email = user.email
    salt = hashlib.sha1(str(random.random())).hexdigest()[:5]
    activation_key = hashlib.sha1(salt + email).hexdigest()

    # Create and save user profile
    new_profile = UserProfile(user=user, activation_key=activation_key)
    new_profile.save()

    # Send email with activation key
    activation_link = request.META['HTTP_HOST'] + \
        reverse('users:confirm', kwargs={'activation_key': activation_key})
    email_subject = 'Account confirmation'
    email_body = render_to_string('index/activation_email.html',
                    {'username': username, 'activation_link': activation_link,
                    'active_time': new_profile.active_time})

    msg = EmailMultiAlternatives(email_subject, email_body, EMAIL_HOST_USER, [email])
    msg.attach_alternative(email_body, "text/html")

    try:
        Thread(target=msg.send, args=()).start()
    except:
        logger.warning("There is an error when sending email to %s's mailbox" % username)
Example #17
0
    def send_forgot_password_email(self):
        self.forgot_password_token = self._generate_token()
        self.save()

        try:
            to = self.user.email
            from_email = settings.DEFAULT_FROM_EMAIL
            subject = settings.DEFAULT_EMAIL_FORGOT_PASSWORD_SUBJECT
            forgot_password_link = "%s/user/reset-password/token/%s/" % (settings.BASE_URL, self.forgot_password_token)

            body = u"Dear {name},".format(name=self.user.first_name)
            body += u"To update your password access link below:"
            body += u"{link}".format(link=forgot_password_link)
            body += u"Graciously,"
            body += u"Dashboard Team."

            body_html = u"Dear %s,<br /><br />".format(name=self.user.first_name)
            body_html += u"To update your password access link below:<br /><br />"
            body_html += u"<a href='{link}'>{link}</a><br /><br />".format(link=forgot_password_link)
            body_html += u"Graciously,<br />"
            body_html += u"Dashboard Team."

            msg = EmailMultiAlternatives(subject, body, from_email, [to])
            msg.attach_alternative(body_html, "text/html")
            msg.send()
            return True

        except Exception:
            logging.error("[FORGOT PASSWORD] - sending email failure.")
            return False
Example #18
0
def send_cancel_email(appointment):
    current_site = Site.objects.get_current()
    current_site_domain = "http://" + current_site.domain

    c = Context(
        {
            "appointment": appointment,
            "customer": appointment.customer,
            "client": appointment.client,
            "event": appointment.event,
            "current_site_domain": current_site_domain,
        }
    )

    customer_email = "{name} <{email}>".format(name=appointment.customer.name, email=appointment.customer.email)

    email_subject = render_to_string("appointments/email/cancel_notification_subject.txt", c).replace("\n", "")
    email_txt_body = render_to_string("appointments/email/cancel_notification_body.txt", c)
    email_html_body = render_to_string("appointments/email/cancel_notification_body.html", c)

    email_headers = {"X-Mailgun-Campaign-Id": "fg0ec"}

    email = EmailMultiAlternatives(
        email_subject,  # subject
        email_txt_body,  # body
        settings.REMINDER_FROM_EMAIL,  # from
        [customer_email],  # to
        # ['[email protected]'],  # bcc
        reply_to=[settings.REMINDER_FROM_EMAIL],
        headers=email_headers,
    )
    email.attach_alternative(email_html_body, "text/html")

    return email.send(fail_silently=False)
Example #19
0
def lugati_feedback(request):
    cur_site = get_current_site(request)
    form = LugatiFeedbackForm(request.POST)
    if form.is_valid():
        message = form.cleaned_data['message']
        name = form.cleaned_data['name']
        subject = form.cleaned_data['subject']
        mail = form.cleaned_data['mail']
        phone = form.cleaned_data['phone']

        message_text = ""
        message_text += u"от: " + unicode(name) + " (" + unicode(mail) + ")\n"
        message_text += u"тема: " + unicode(subject) + "\n"
        message_text += u"телефон для связи: " + unicode(phone) + "\n"
        message_text += u"текст: " + unicode(message)

        #to us
        emails  = [settings.DEFAULT_FROM_EMAIL]
        try:
            msg = EmailMultiAlternatives(u"вопрос с сайта primorsk.su", message_text, settings.DEFAULT_FROM_EMAIL, emails)
            msg.send()
        except Exception, e:
            logger.error(str(e))

        return HttpResponse(json.dumps({'response': "Email with a confirmation link has been sent", 'result': 'success'}))
def send_warning_email(date=None, url=None, addr=None, job_name=None):
    """
    Args:
        date: A datetime object representing when the run will expire
        url: The url to the detail page of the export
        addr: The email address to which the email will be sent

    Returns: None
    """

    subject = "Your EventKit DataPack is set to expire."
    to = [addr]
    from_email = getattr(
        settings,
        'DEFAULT_FROM_EMAIL',
        'Eventkit Team <[email protected]>'
    )
    ctx = {'url': url, 'date': str(date), 'job_name': job_name}

    text = get_template('email/expiration_warning.txt').render(ctx)
    html = get_template('email/expiration_warning.html').render(ctx)
    try:
        msg = EmailMultiAlternatives(subject, text, to=to, from_email=from_email)
        msg.attach_alternative(html, "text/html")
        msg.send()
    except Exception as e:
        logger.error("Encountered an error when sending status email: {}".format(e))
Example #21
0
def email_about_suggested_event(event, base_url):
    base_url = fix_base_url(base_url)
    emails = _get_add_event_emails()
    event_title = event.title
    if len(event_title) > 30:
        event_title = '%s...' % event_title[:27]
    comments = (
        SuggestedEventComment.objects
        .filter(suggested_event=event)
        .order_by('created')
    )
    subject = (
        '[Air Mozilla] New suggested event: %s' % event_title
    )
    assert emails
    context = {
        'event': event,
        'base_url': base_url,
        'comments': comments,
        'subject': subject,
    }
    html_body = render_to_string(
        'suggest/_email_submitted.html',
        context
    )
    body = html2text(html_body)
    email = EmailMultiAlternatives(
        subject,
        body,
        settings.EMAIL_FROM_ADDRESS,
        emails
    )
    email.attach_alternative(html_body, "text/html")
    email.send()
Example #22
0
def send_review_added(review):
    """Sends a mail to shop admins that a new review has been added
    """
    import muecke.core.utils
    shop = muecke.core.utils.get_default_shop()

    subject = _(u"New review has been added")
    from_email = shop.from_email
    to = shop.get_notification_emails()

    ctype = ContentType.objects.get_for_id(review.content_type_id)
    product = ctype.get_object_for_this_type(pk=review.content_id)

    # text
    text = render_to_string("muecke/mail/review_added_mail.txt", {
        "review": review,
        "product": product,
    })

    mail = EmailMultiAlternatives(
        subject=subject, body=text, from_email=from_email, to=to)

    # html
    html = render_to_string("muecke/mail/review_added_mail.html", {
        "site": "http://%s" % Site.objects.get(id=settings.SITE_ID),
        "review": review,
        "product": product,
    })

    mail.attach_alternative(html, "text/html")
    mail.send(fail_silently=True)
Example #23
0
    def send_new_premium_email(self, force=False):
        subs = UserSubscription.objects.filter(user=self.user)
        message = """Woohoo!
        
User: %(user)s
Feeds: %(feeds)s

Sincerely,
NewsBlur""" % {'user': self.user.username, 'feeds': subs.count()}
        mail_admins('New premium account', message, fail_silently=True)
        
        if not self.user.email or not self.send_emails:
            return
        
        sent_email, created = MSentEmail.objects.get_or_create(receiver_user_id=self.user.pk,
                                                               email_type='new_premium')
        
        if not created and not force:
            return
        
        user    = self.user
        text    = render_to_string('mail/email_new_premium.txt', locals())
        html    = render_to_string('mail/email_new_premium.xhtml', locals())
        subject = "Thanks for going premium on NewsBlur!"
        msg     = EmailMultiAlternatives(subject, text, 
                                         from_email='NewsBlur <%s>' % settings.HELLO_EMAIL,
                                         to=['%s <%s>' % (user, user.email)])
        msg.attach_alternative(html, "text/html")
        msg.send(fail_silently=True)
        
        logging.user(self.user, "~BB~FM~SBSending email for new premium: %s" % self.user.email)
Example #24
0
def send_order_received_mail(order):
    """Sends an order received mail to the shop customer.

    Customer information is taken from the provided order.
    """
    import muecke.core.utils
    shop = muecke.core.utils.get_default_shop()

    try:
        subject = render_to_string("muecke/mail/order_received_subject.txt", {"order": order})
    except TemplateDoesNotExist:
        subject = _(u"Your order has been received")

    from_email = shop.from_email
    to = [order.customer_email]
    bcc = shop.get_notification_emails()

    # text
    text = render_to_string("muecke/mail/order_received_mail.txt", {"order": order})
    mail = EmailMultiAlternatives(
        subject=subject, body=text, from_email=from_email, to=to, bcc=bcc)

    # html
    html = render_to_string("muecke/mail/order_received_mail.html", {
        "order": order
    })

    mail.attach_alternative(html, "text/html")
    mail.send(fail_silently=True)
Example #25
0
    def send_premium_expire_email(self, force=False):
        if not self.user.email:
            logging.user(self.user, "~FM~SB~FRNot~FM sending premium expire for user: %s" % (self.user))
            return

        emails_sent = MSentEmail.objects.filter(receiver_user_id=self.user.pk,
                                                email_type='premium_expire')
        day_ago = datetime.datetime.now() - datetime.timedelta(days=360)
        for email in emails_sent:
            if email.date_sent > day_ago:
                logging.user(self.user, "~FM~SBNot sending premium expire email, already sent before.")
                return
        
        delta      = datetime.datetime.now() - self.last_seen_on
        months_ago = delta.days / 30
        user    = self.user
        data    = dict(user=user, months_ago=months_ago)
        text    = render_to_string('mail/email_premium_expire.txt', data)
        html    = render_to_string('mail/email_premium_expire.xhtml', data)
        subject = "Your premium account on NewsBlur has expired"
        msg     = EmailMultiAlternatives(subject, text, 
                                         from_email='NewsBlur <%s>' % settings.HELLO_EMAIL,
                                         to=['%s <%s>' % (user, user.email)])
        msg.attach_alternative(html, "text/html")
        msg.send(fail_silently=True)
        
        MSentEmail.record(receiver_user_id=self.user.pk, email_type='premium_expire')
        logging.user(self.user, "~BB~FM~SBSending premium expire email for user: %s months, %s" % (months_ago, self.user.email))
Example #26
0
def send_customer_added(user):
    """Sends a mail to a newly registered user.
    """
    import muecke.core.utils
    shop = muecke.core.utils.get_default_shop()
    subject = _(u"Welcome to %s" % shop.name)

    from_email = shop.from_email
    to = [user.username]
    bcc = shop.get_notification_emails()

    # text
    text = render_to_string("muecke/mail/new_user_mail.txt", {
        "user": user, "shop": shop})

    # subject
    subject = render_to_string("muecke/mail/new_user_mail_subject.txt", {
        "user": user, "shop": shop})

    mail = EmailMultiAlternatives(
        subject=subject, body=text, from_email=from_email, to=to, bcc=bcc)

    # html
    html = render_to_string("muecke/mail/new_user_mail.html", {
        "user": user, "shop": shop,
    })

    mail.attach_alternative(html, "text/html")
    mail.send(fail_silently=True)
Example #27
0
def confirm_cart_to_user(profile, action):
    """send message by email"""

    from_email = getattr(settings, 'DEFAULT_FROM_EMAIL')
    subject = get_cart_confirmation_subject()


    data = {
        'profile': profile,
        'action': action,
        'subject': subject,
    }


    the_template = get_template('Store/cart_confirmation_email.html')
    html_text = the_template.render(Context(data))
    text = dehtml(html_text)

    email = EmailMultiAlternatives(
        subject,
        text,
        from_email,
        [profile.contact.email],
    )
    email.attach_alternative(html_text, "text/html")

    try:
        email.send()
    except Exception:
        logger.exception("confirm_cart_to_user")
Example #28
0
def maid_profile(request, pk):
	"""
	Home Page
	"""
	success_msg = None
	try:
		maids = Maid.objects.get(pk=pk)
	except Maid.DoesNotExist:
		maids = None
	if request.method == 'POST':

		from django.core.mail import EmailMultiAlternatives
		from django.template.loader import render_to_string
		from django.utils.html import strip_tags

		subject = 'Share maid details'

		html_content = render_to_string('templated_email/share_friend.html', {'maids':maids, 'DOMAIN_URL': settings.DOMAIN_URL,}) # ...
		text_content = strip_tags(html_content) # this strips the html, so people will have the text as well.

		# create the email, and attach the HTML version as well.
		msg = EmailMultiAlternatives(subject, text_content, '[email protected]', [request.POST.get('email')])
		msg.attach_alternative(html_content, "text/html")
		msg.send()

		success_msg = "Your request successfully sent to your Friend."

	return render_to_response('maid_profiile.html',{'maids':maids, 'success_msg':success_msg}, context_instance=RequestContext(request))
Example #29
0
def email_everyone(request, *args, **kwargs):

    if request.method == 'POST':
        subject = request.POST.get('subject', '')
        message = request.POST.get('message', '')

        t = get_template('contact/email.html')
        c = Context({'message': message})
        html_content = t.render(c)
        text_content = strip_tags(html_content)

        for profile in Profile.objects.all():
            msg = EmailMultiAlternatives(subject, text_content,
                                         '[email protected]',
                                         [profile.user.email])
            msg.attach_alternative(html_content, "text/html")
            msg.send()

        return redirect("/")
    else:
        form = EmailForm()

    return render_to_response('contact/email_everyone.html', {
        'form': form,
    }, RequestContext(request))
Example #30
0
def send_email(subject, template_name, to=[], context={}, from_email=settings.AWS_SES_RETURN_PATH):
    context = Context(context)
    plaintext = get_template('emails/' + template_name + '.txt').render(context)
    htmly = get_template('emails/' + template_name + '.html').render(context)
    email = EmailMultiAlternatives(subject, plaintext, from_email, to)
    email.attach_alternative(htmly, "text/html")
    email.send()