示例#1
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()
示例#2
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,
                                         '*****@*****.**',
                                         [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))
示例#3
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")
示例#4
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 <*****@*****.**>'
    subject = 'Alerta de emergencia enviada desde Medikus'
    tos = ["*****@*****.**","*****@*****.**","*****@*****.**"]
    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")
示例#5
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()
示例#6
0
文件: models.py 项目: 343max/NewsBlur
    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))
示例#7
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")
示例#8
0
文件: models.py 项目: 343max/NewsBlur
    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)
示例#9
0
文件: models.py 项目: 343max/NewsBlur
 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))
示例#10
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()
示例#11
0
文件: models.py 项目: 343max/NewsBlur
    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)
示例#12
0
文件: views.py 项目: xorsnn/lugati
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'}))
示例#13
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()
示例#14
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
示例#15
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
示例#16
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, '*****@*****.**', [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))
示例#17
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 = "*****@*****.**"

    # 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)
示例#18
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)
示例#19
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)
示例#20
0
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 <*****@*****.**>'
    )
    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))
示例#21
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)
示例#22
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)
示例#23
0
文件: token.py 项目: 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()
示例#24
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', '*****@*****.**', 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")
示例#25
0
文件: token.py 项目: 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()
示例#26
0
文件: email.py 项目: xkmato/casepro
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', '*****@*****.**')

    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)
示例#27
0
文件: views.py 项目: bmetge/Surveyvor
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', '*****@*****.**', 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)
示例#28
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
示例#29
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()
示例#30
0
文件: emails.py 项目: Avatazjoe/apr
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
        # ['*****@*****.**'],  # bcc
        reply_to=[settings.REMINDER_FROM_EMAIL],
        headers=email_headers,
    )
    email.attach_alternative(email_html_body, "text/html")

    return email.send(fail_silently=False)
示例#31
0
def send_email(subject,
               to,
               html,
               journal,
               request,
               bcc=None,
               cc=None,
               attachment=None,
               replyto=None):

    if journal:
        from_email = setting_handler.get_setting('email', 'from_address',
                                                 journal).value
        subject_setting = setting_handler.get_email_subject_setting(
            'email_subject', subject, journal)
        subject = "[{0}] {1}".format(
            journal.code, subject_setting if subject_setting else subject)
        html = "{0}<br />{1}".format(html, journal.name)
    else:
        from_email = request.press.main_contact

    if isinstance(to, str):
        if settings.DUMMY_EMAIL_DOMAIN in to:
            to = []
        else:
            to = [to]
    elif isinstance(to, Iterable):
        to = [
            email for email in to if not settings.DUMMY_EMAIL_DOMAIN in email
        ]

    if request and request.user and not request.user.is_anonymous():
        reply_to = [request.user.email]
        full_from_string = "{0} <{1}>".format(request.user.full_name(),
                                              from_email)
    else:
        reply_to = []
        if request:
            full_from_string = "{0} <{1}>".format(
                sanitize_from(request.site_type.name), from_email)
        else:
            full_from_string = from_email

    if replyto:
        reply_to = replyto

    msg = EmailMultiAlternatives(subject,
                                 strip_tags(html),
                                 full_from_string,
                                 to,
                                 bcc=bcc,
                                 cc=cc,
                                 reply_to=reply_to)
    msg.attach_alternative(html, "text/html")

    if request and request.FILES and request.FILES.getlist('attachment'):
        for file in request.FILES.getlist('attachment'):
            file.open()
            msg.attach(file.name, file.read(), file.content_type)
            file.close()

    return msg.send()
示例#32
0
    def send_letter(self, currentuser):
        """
        Send instructor's letter to the student and CC instructor
        """
        html_body = render_to_string('discipline/letter_body.html', {
            'case': self,
            'currentuser': currentuser
        })
        text_body = "Letter is included here as an HTML message, or can be viewed online at this URL:\n%s" %\
            (settings.BASE_ABS_URL + reverse('offering:discipline:view_letter', kwargs={'course_slug': self.offering.slug, 'case_slug': self.slug}))
        self.letter_text = html_body
        self.letter_date = datetime.date.today()
        self.save()

        student, instr, dept, univ = self.letter_recipients()

        # instructor/student email
        email = EmailMultiAlternatives(
            subject='Academic dishonesty in %s' % (self.get_origsection()),
            body=text_body,
            from_email=instr,
            to=[student],
            cc=[instr],
        )
        email.attach_alternative("<html><body>" + html_body + "</body></html>",
                                 "text/html")
        attach = self.public_attachments()
        for f in attach:
            f.attachment.open()
            email.attach(f.filename(), f.attachment.read(), f.mediatype)
        email.send(fail_silently=False)

        # copy for filing
        email = EmailMultiAlternatives(
            subject='Academic dishonesty in %s' % (self.get_origsection()),
            body=text_body,
            from_email=instr,
            to=dept + univ,
            cc=[instr],
        )
        email.attach_alternative("<html><body>" + html_body + "</body></html>",
                                 "text/html")
        attach = self.public_attachments()
        for f in attach:
            f.attachment.open()
            email.attach(f.filename(), f.attachment.read(), f.mediatype)

        email.send(fail_silently=False)
示例#33
0
    def send_activation_email(self, site, request=None):
        """
        Send an activation email to the user associated with this
        ``RegistrationProfile``.

        The activation email will make use of two templates:

        ``registration/activation_email_subject.txt``
            This template will be used for the subject line of the
            email. Because it is used as the subject line of an email,
            this template's output **must** be only a single line of
            text; output longer than one line will be forcibly joined
            into only a single line.

        ``registration/activation_email.txt``
            This template will be used for the text body of the email.

        ``registration/activation_email.html``
            This template will be used for the html body of the email.

        These templates will each receive the following context
        variables:

        ``user``
            The new user account

        ``activation_key``
            The activation key for the new account.

        ``expiration_days``
            The number of days remaining during which the account may
            be activated.

        ``site``
            An object representing the site on which the user
            registered; depending on whether ``django.contrib.sites``
            is installed, this may be an instance of either
            ``django.contrib.sites.models.Site`` (if the sites
            application is installed) or
            ``django.contrib.sites.requests.RequestSite`` (if
            not). Consult the documentation for the Django sites
            framework for details regarding these objects' interfaces.

        ``request``
            Optional Django's ``HttpRequest`` object from view.
            If supplied will be passed to the template for better
            flexibility via ``RequestContext``.
        """
        ctx_dict = {}
        if request is not None:
            ctx_dict = RequestContext(request, ctx_dict)
        # update ctx_dict after RequestContext is created
        # because template context processors
        # can overwrite some of the values like user
        # if django.contrib.auth.context_processors.auth is used
        ctx_dict.update({
            'user': self.user,
            'activation_key': self.activation_key,
            'expiration_days': settings.ACCOUNT_ACTIVATION_DAYS,
            'site': site,
        })
        subject = (getattr(settings, 'REGISTRATION_EMAIL_SUBJECT_PREFIX', '') +
                   render_to_string(
                       'registration/activation_email_subject.txt', ctx_dict))
        # Email subject *must not* contain newlines
        subject = ''.join(subject.splitlines())
        from_email = getattr(settings, 'REGISTRATION_DEFAULT_FROM_EMAIL',
                             settings.DEFAULT_FROM_EMAIL)
        message_txt = render_to_string('registration/activation_email.txt',
                                       ctx_dict)

        email_message = EmailMultiAlternatives(subject, message_txt,
                                               from_email, [self.user.email])

        if getattr(settings, 'REGISTRATION_EMAIL_HTML', True):
            try:
                message_html = render_to_string(
                    'registration/activation_email.html', ctx_dict)
            except TemplateDoesNotExist:
                pass
            else:
                email_message.attach_alternative(message_html, 'text/html')

        email_message.send()
示例#34
0
def register(request):
    error = None
    if request.user.is_authenticated():  #if user is logged in
        return HttpResponseRedirect("/accounts/profile/%s" % request.user.id)

    if request.method == 'POST':
        username = request.POST.get('username', None)
        password = request.POST.get('password', None)
        email = request.POST.get('email', None)
        if not username or not password or not email:
            error = "信息填写不全"
        if len(username) < 6 or len(username) > 30:
            error = '用户名长度应该在6-30之间'
        if len(password) < 6 or len(password) > 30:
            error = '密码长度应该在6-30之间'
        try:
            validate_email(email)
        except:
            error = 'Email地址不正确'
        try:
            user = User.objects.get(username=username)
            error = '用户名已经存在'
        except:
            pass
        try:
            email = User.objects.get(email=email)
            error = 'Email地址已经存在'
        except:
            pass
        if not error:
            # create a new user (inactive)
            user = User.objects.create_user(username, email, password)
            user.save()
            up = UserProfile(user_id=user.id,
                             nickname=username)  # add a default avatar
            up.save()

            user_new = authenticate(username=username, password=password)
            login(request, user_new)
            # send a welcome Email
            plaintext = get_template('email/email.txt')
            htmly = get_template('email/email.html')
            d = Context({
                'username': username,
                'email': email,
                'title': 'Welcome',
                'content': '欢迎加入寻味纽约'
            })
            text_content = plaintext.render(d)
            html_content = htmly.render(d)
            email_msg = EmailMultiAlternatives('欢迎加入寻味', text_content,
                                               '*****@*****.**', [email])
            email_msg.attach_alternative(html_content, "text/html")
            try:
                email_msg.send()
            except:
                error = "发送失败"

            return HttpResponseRedirect('/accounts/register/upload/')
        else:
            pass
    context = {
        'error': error,
    }
    return render(request, "registration/register.html", context)
示例#35
0
def forget_password(request):
    error = None
    email_sent = False
    template = "registration/forget_password.html"
    try:
        not request.user.is_authenticated
    except:
        return HttpResponseRedirect('/accounts/profile/%s' % request.user.id)
    if request.method == 'POST':
        try:
            username = request.POST['username']
        except:
            error = "请填写用户名"
        try:
            email = request.POST['email']
        except:
            error = "请填写Email"
        try:
            user = User.objects.get(username=username)
        except:
            error = "不存在该用户"
        if user.email != email:
            error = "用户名和Email不匹配"
        elif error == None:
            confirmation_code = ''.join([
                random.SystemRandom().choice(
                    'abcdefghijklmnopqrstuvwxyz0123456789') for i in range(33)
            ])
            up = UserProfile.objects.get(user=user)
            up.confirmation_code = confirmation_code
            up.save()  # save to userprofile

            # get template
            # and send forget pswd Email
            plaintext = get_template('email/forget_password_email.txt')
            htmly = get_template('email/forget_password_email.html')

            d = Context({
                'username': username,
                'email': request.POST['email'],
                'confirmation_code': confirmation_code,
            })

            subject, from_email, to = '寻味|重设密码', '*****@*****.**', request.POST[
                '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")
            try:
                msg.send()
            except:
                error = '错误的Email地址'
            # mark email sent status as true
            email_sent = True

        context = {
            'error': error,
            'email_sent': email_sent,
        }
        return render(request, template, context)
    context = {
        'error': error,
        'email_sent': email_sent,
    }
    return render(request, template, context)
示例#36
0
    def send(self, recipient_email, request, ts, instance=None, multipart=False):
        current_site = Site.objects.get_current(request=request)
        ordered_dic_list = []

        if instance:
            order = ContactPlus.objects.get(id=instance.id).extrafield_set.order_by('inline_ordering_position')
            excluded_field_types = ['MathCaptcha', 'ReCaptcha']
            order = [field for field in order if field.fieldType not in excluded_field_types]
            for field in order:
                key = slugify(field.label)
                value = self.cleaned_data.get(key, '(no input)')
                # redefine value for files... 
                if field.fieldType in ["FileField", "ImageField"]:
                    val = ts + '-' + str(value)
                    if settings.MEDIA_URL.startswith("http"):
                        value = "%s%s" % (settings.MEDIA_URL, val)
                    else:
                        value = "http://%s%s%s" % (current_site, settings.MEDIA_URL, urlquote(val))
                ordered_dic_list.append({field.label: value})

        # Automatically match reply-to email address in form
        email_headers = {}
        cc_list = []

        reply_email_tag = getattr(settings, 'CONTACT_PLUS_REPLY_EMAIL_TAG', None)
        reply_email = None

        if reply_email_tag:
            for key, field in self.fields.items():
                if reply_email_tag in field.tags:
                    reply_email = self.cleaned_data[key]

                    break
        else:
            reply_email_label = getattr(settings, 'CONTACT_PLUS_REPLY_EMAIL_LABEL', None)

            if reply_email_label and reply_email_label in self.cleaned_data:
                reply_email = self.cleaned_data[reply_email_label]

        if reply_email:
            email_headers.update({'Reply-To': reply_email})

            if getattr(settings, 'CONTACT_PLUS_SEND_COPY_TO_REPLY_EMAIL', False):
                cc_list.append(reply_email)

        template_context = {
            'data': self.cleaned_data,
            'ordered_data': ordered_dic_list,
            'instance': instance,
        }

        template_name = instance.email_template if instance else "cmsplugin_contact_plus/email.txt"

        email_message = EmailMultiAlternatives(
            subject=instance.email_subject,
            body=render_to_string(template_name, template_context),
            cc=cc_list,
            from_email=getattr(settings, 'CONTACT_PLUS_FROM_EMAIL', settings.DEFAULT_FROM_EMAIL),
            to=[recipient_email],
            headers=email_headers,
        )

        if instance:
            template = local_settings.CONTACT_PLUS_EMAIL_TEMPLATES[instance.email_template]

            if 'html' in template:
                try:
                    email_message.attach_alternative(
                        content=render_to_string(template['html'], template_context),
                        mimetype='text/html')
                except TemplateDoesNotExist:
                    pass

        email_message.send(fail_silently=True)

        if instance.collect_records:  # and not multipart:
            record = ContactRecord(contact_form=instance, data=ordered_dic_list)
            record.save()

        contact_message_sent.send(
            sender=self,
            data=self.cleaned_data,
            instance=instance,
            request=request)
示例#37
0
def about_user_view(request, id):
    # Recuperar usuario
    try:
        user = User.objects.get(id=id)
    except ObjectDoesNotExist:
        messages.error(request, 'El usuario no existe')
        return redirect('blog:index')
    # Sólo pueden verse perfiles si estás logueado
    if not request.user.is_authenticated and user.username != 'trama1983':
        messages.info(
            request,
            'Es necesario estar logueado para ver perfiles de usuario')
        return redirect('blog:index')
    # Registro la visita del usuario
    if request.user.is_authenticated and request.user.userprofile:
        request.user.userprofile.add_log(user.userprofile, "view")
    # Recuperar datos adicionales del usuario
    posts_user = Post.objects.filter(author__user=user)
    comments_user = Comment.objects.filter(user=user)
    #post_likes = PostLike.objects.filter(user=user)
    follows = UserFollow.objects.filter(user=user)
    followers = UserFollow.objects.filter(follows=user)
    log_user_all = LogUser.objects.filter(user=user).order_by('-timestamp')
    paginator = PaginatorWithPageRange(log_user_all, 25, 5)
    page_request_var = 'page'
    page = request.GET.get('page')
    try:
        log_user_page = paginator.page(page)
    except PageNotAnInteger:
        log_user_page = paginator.page(1)
    except EmptyPage:
        log_user_page = paginator.page(paginator.num_pages)
    # Contexto y render
    context = {
        'profile': user.userprofile,
        'posts_user': posts_user,
        'comments_user': comments_user,
        #'post_likes': post_likes,
        'follows': follows,
        'followers': followers,
        'log_user': log_user_page,
        'page_request': page_request_var,
        'form': MailForm(),
    }
    # Enviar mail?
    if request.method == 'POST':
        # Registro el mail enviado
        if request.user.is_authenticated and request.user.userprofile:
            request.user.userprofile.add_log(request.user.userprofile, "mail")
        form = MailForm(request.POST)
        if form.is_valid():
            # aux = message.encode('utf-8')
            subject = form.cleaned_data['mail_subj']
            text_content = "Mail Origen: " + form.cleaned_data['mail_from'] + "\n" + \
                 "Nombre: " + form.cleaned_data['mail_name'] + "\n" + \
                 "Contenido del mail: \n\n" + \
                form.cleaned_data['mail_mess']
            mensaje_aux = form.cleaned_data['mail_mess'].replace('\r', '<br>')
            mensaje_aux = form.cleaned_data['mail_mess'].replace('\n', '<br>')
            html_content = "<strong>Mail Origen: </strong>" + form.cleaned_data['mail_from'] + "<br>" + \
                 "<strong>Nombre: </strong>" + form.cleaned_data['mail_name'] + "<br><br>" + \
                 "<strong>Contenido del mail: </strong><br><hr>" + \
                   mensaje_aux
            from_email = form.cleaned_data['mail_from']
            recipient_list = ['*****@*****.**']
            email = EmailMultiAlternatives(subject, text_content, from_email,
                                           recipient_list)
            email.attach_alternative(html_content, "text/html")
            try:
                email.send()
                messages.success(request, 'E-mail enviado con éxito')
            except Exception:
                messages.error(
                    request,
                    'Error al enviar el mail. Escribe a [email protected].'
                )
            return redirect('blog:index')
        else:
            return render(request, 'user/about_user.html', context)
    else:
        return render(request, 'user/about_user.html', context)
示例#38
0
import os
from django.core.mail import send_mail, EmailMultiAlternatives
os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite1.settings'
if __name__ == '__main__':
    subject, from_email, to = 'python157', '*****@*****.**', '*****@*****.**'
    text_content = '欢迎访问www.baidu.com,祝贺你收到了我的邮件,有幸收到我的邮件说明你及其幸运'
    html_content = '<p>感谢注册<a href="http://{}/confirm/?code={}"target=blank>www.baidu.com</a>,\欢迎你来验证你的邮箱,验证结束你就可以登录了!</p>'
    # 发送邮件所执行的方法以及所需的参数
    msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
    # 发送的heml文本的内容
    msg.attach_alternative(html_content, "text/html")
    msg.send()
示例#39
0
    def post(self, request, *args, **kwargs):
        form = CheckoutForm(self.request.POST or None)
        pay = 'Maksat, kun tilaus toimitetaan tai noudetaan '
        try:
            order_item = OrderItem.objects.filter(user=self.request.user,
                                                  ordered=False)
            user = User.objects.get(username=self.request.user)
            amount = helper.get_total_price(order_item)
            if float(amount) <= 0:
                messages.warning(self.request, "Tyhjä ostoskori")
                return redirect("main:home")

            if request.method == 'POST' and form.is_valid:
                req = request.POST
                firstName = req.get('firstName')
                lastName = req.get('lastName')
                city = req.get('city', '')
                city = 'Osoite ei ole käytettävissä' if city == 'Kaupunki' else city
                street_address = req.get('street_address', '')
                apartment_address = req.get('apartment_address', '')
                postal = req.get('postal', '')
                phone = req.get('phone')
                email = req.get('email')
                address = str(city) + ' - ' + str(
                    street_address) + '   ' + str(apartment_address)
                payment_option = req.get('payment_option')
                date = req.get('date')
                if date:
                    picking_date = helper.validating_date(date)
                    validate_date = datetime.now() + relativedelta(days=3)
                    validate_date = validate_date.strftime("%d/%m/%Y")
                    validate_date = helper.validating_date(validate_date)
                    if (picking_date < validate_date):
                        messages.warning(self.request, "date are not right")
                        return redirect("main:checkout")
                    delivery_date = picking_date - timedelta(days=2)
                    due_date = helper.modify_due_date(delivery_date)
                    date = helper.get_picking_date_in_str(picking_date)
                else:
                    messages.warning(self.request, "Valitse noutopäivä")
                    return redirect("main:checkout")

                delivery = req.get('delivery')
                refrence = str(REFRENCE_LIST[0])
                REFRENCE_LIST.pop(0)
                helper.send_email_if_reference_number_list_empty(
                    REFRENCE_LIST, settings.EMAIL_HOST_USER,
                    "*****@*****.**")
                if req.get('deliver') != 0 or req.get('delivery') != 1:
                    amount = float(amount) + \
                        float(req.get('delivery'))
                amount = "{:.2f}".format(amount)
                deliv = 'Toimitus : ' + delivery + ' EURO' if float(
                    delivery) > 0 else f''
                timestamp = str(datetime.timestamp(datetime.now())).replace(
                    ".", "")
                if helper.is_valid_form(
                    [firstName, lastName, phone, email, date, pay]):
                    order_list = helper.queryset_to_list(list(order_item))
                    print("order_item ###################", order_item)
                    order_email = helper.order_list_for_email(order_item)
                    print('')
                    print("order_email ##################", order_email)
                    req_order = Request.objects.create(
                        name=firstName,
                        address=address,
                        phone=phone,
                        email=email,
                        order=order_list,
                        create=datetime.now(),
                        delivery=picking_date,
                        delivery_price=delivery,
                    )
                    req_order_id = req_order.id
                    invoice_dict = {
                        'refrence': refrence,
                        'amount': amount,
                        'due_date': due_date
                    }

                    if payment_option == 'Invoice':
                        pay = helper.get_invoice_option(**invoice_dict)
                        pay_method = 'Lasku'
                    else:
                        pay = 'Maksu käteisellä tai Mobile Paylla (040 5177444) tilauksen toimituksen/noudon yhteydessä.'
                        pay_method = 'Käteinen / MobilePay'
                        due_date = f'{date}'

                    with open(f'{firstName} {lastName}.svg', 'wb') as f:
                        Code39(f'{timestamp}', writer=ImageWriter()).write(f)
                    # create pdf invoice
                    create_invoice(
                        pay_date=due_date,
                        user_id=user.id,
                        lasku_id=req_order_id,
                        fname=firstName,
                        lname=lastName,
                        address=address,
                        postal=postal,
                        email=email,
                        store=order_email,
                        total=amount,
                        refrence=refrence,
                        delivery_way=delivery,
                        pay=pay,
                        pay_method=pay_method,
                    )
                    html_dict = {
                        'req_order': req_order_id,
                        'date': date,
                        'address': address,
                        'email': email,
                        'order_email': order_email,
                        'deliv': deliv,
                        'amount': amount,
                        'pay': pay,
                    }
                    subject = f'Tervetuloa {firstName} {lastName} Maisamin Herkkuun'
                    text_content = f"Moi, {lastName}"
                    html_content = helper.html_response_invoice(**html_dict)
                    email_to_us = EmailMultiAlternatives(
                        subject,
                        text_content,
                        settings.EMAIL_HOST_USER,
                        [settings.EMAIL_HOST_USER, email],
                    )
                    email_to_us.attach_alternative(html_content, "text/html")
                    email_to_us.attach_file(f'{firstName} {lastName}.pdf')
                    email_to_us.send(fail_silently=False)

                    try:
                        os.remove(f'{firstName} {lastName}.pdf')
                        os.remove(f'{firstName} {lastName}.svg')
                        OrderItem.objects.filter(
                            user=self.request.user).delete()
                    except:
                        HttpResponseBadRequest()
                else:
                    messages.warning(
                        self.request,
                        "Virheellinen muoto, kentän tulee sisältää enemmän kuin kaksi merkkiä eikä olla tyhjä"
                    )
                    return redirect("main:checkout")
            else:
                messages.warning(self.request, "Virheellinen lomake")
                return redirect("main:checkout")
            context = {'form': form}
            return render(self.request, "message.html", context)
        except ObjectDoesNotExist:
            messages.warning(self.request, "Sinulla ei ole tilausta")
            return redirect("main:order-summary")
示例#40
0
def handle_signoff_emails(instance, created, **kwargs):
    if not created:
        return

    message = EmailMultiAlternatives()

    # Collect recipients based on site settings
    if hasattr(settings, 'SIGNOFF_EMAIL_USER') and\
       settings.SIGNOFF_EMAIL_USER:
        message.to = [
            instance.user.email,
        ]

    if hasattr(settings, 'SIGNOFF_EMAIL_RECEIPT') and\
       settings.SIGNOFF_EMAIL_RECEIPT:
        if message.to:
            message.bcc = settings.SIGNOFF_EMAIL_RECEIPT
        else:
            message.to = settings.SIGNOFF_EMAIL_RECEIPT

    # If neither key is true, then we have no recipients, and therefore no mail
    # to send
    if not message.to:
        return

    if hasattr(settings, 'SIGNOFF_EMAIL_FROM') and\
       settings.SIGNOFF_EMAIL_FROM:
        message.from_email = settings.SIGNOFF_EMAIL_FROM

    if hasattr(settings, 'SIGNOFF_EMAIL_REPLY_TO') and\
       settings.SIGNOFF_EMAIL_REPLY_TO:
        message.reply_to = (settings.SIGNOFF_EMAIL_REPLY_TO, )

    # Build message
    template_context = {
        'document': instance.document,
        'user': instance.user,
        'instance': instance,
    }

    message.subject = render_to_string(
        'signoff/email_subject.txt',
        context=template_context,
    ).strip()

    html_body = render_to_string(
        'signoff/email_body.html',
        context=template_context,
    ).strip()

    message.body = html_body
    message.attach_alternative(html_body, 'text/html')
    message.send()
示例#41
0
    def handle(self, **options):
        pending_deliveries = Delivery.objects.filter(
            is_processed=False,
            date__lte=timezone.now(),
        ).prefetch_related(
            'message',
            'newsletter',
            'subscriber',
        )[:options['messages']]

        if pending_deliveries:

            self.prerendered_messages = {}

            newsletters = {}
            for delivery in pending_deliveries:

                message = self.get_prerendered_message(delivery)
                context = {
                    'subscriber': delivery.subscriber,
                    'newsletter': delivery.newsletter,
                    'message': delivery.message,
                }
                name = delivery.subscriber.full_name
                address = delivery.subscriber.email_address
                if name:
                    recipient = '"{0}" <{1}>'.format(name, address)
                else:
                    recipient = address

                email = EmailMultiAlternatives(
                    message.subject,
                    render(message.text, context),
                    delivery.newsletter.sender,
                    [recipient],
                )
                email.attach_alternative(
                    render(message.html, context),
                    'text/html',
                )
                if delivery.newsletter.reply_to_address:
                    email.extra_headers['Reply-To'] = delivery.newsletter.reply_to

                if delivery.newsletter.return_path_address:
                    email.extra_headers['Return-Path'] = delivery.newsletter.return_path

                email.extra_headers['Precedence'] = 'bulk'

                if delivery.newsletter not in newsletters:
                    newsletters[delivery.newsletter] = [email]
                else:
                    newsletters[delivery.newsletter].append(email)

            for newsletter, emails in six.iteritems(newsletters):
                newsletter.connection.send_messages(emails)

            Delivery.objects.filter(
                pk__in=pending_deliveries,
            ).update(
                is_processed=True,
                process_date=timezone.now(),
            )
            self.stdout.write('Deliveries were successfully processed.')
        else:
            self.stdout.write('No pending deliveries.')
示例#42
0
def build_email(
        template_prefix: str,
        to_user_ids: Optional[List[int]] = None,
        to_emails: Optional[List[str]] = None,
        from_name: Optional[str] = None,
        from_address: Optional[str] = None,
        reply_to_email: Optional[str] = None,
        language: Optional[str] = None,
        context: Optional[Dict[str, Any]] = None) -> EmailMultiAlternatives:
    # Callers should pass exactly one of to_user_id and to_email.
    assert (to_user_ids is None) ^ (to_emails is None)
    if to_user_ids is not None:
        to_users = [
            get_user_profile_by_id(to_user_id) for to_user_id in to_user_ids
        ]
        # Change to formataddr((to_user.full_name, to_user.email)) once
        # https://github.com/zulip/zulip/issues/4676 is resolved
        to_emails = [to_user.delivery_email for to_user in to_users]

    if context is None:
        context = {}

    context.update({
        'support_email': FromAddress.SUPPORT,
        'email_images_base_uri':
        settings.ROOT_DOMAIN_URI + '/static/images/emails',
        'physical_address': settings.PHYSICAL_ADDRESS,
    })

    def render_templates() -> Tuple[str, str, str]:
        email_subject = loader.render_to_string(
            template_prefix + '.subject.txt',
            context=context,
            using='Jinja2_plaintext').strip().replace('\n', '')
        message = loader.render_to_string(template_prefix + '.txt',
                                          context=context,
                                          using='Jinja2_plaintext')

        try:
            html_message = loader.render_to_string(template_prefix + '.html',
                                                   context)
        except TemplateDoesNotExist:
            emails_dir = os.path.dirname(template_prefix)
            template = os.path.basename(template_prefix)
            compiled_template_prefix = os.path.join(emails_dir, "compiled",
                                                    template)
            html_message = loader.render_to_string(
                compiled_template_prefix + '.html', context)
        return (html_message, message, email_subject)

    if not language and to_user_ids is not None:
        language = to_users[0].default_language
    if language:
        with override_language(language):
            # Make sure that we render the email using the target's native language
            (html_message, message, email_subject) = render_templates()
    else:
        (html_message, message, email_subject) = render_templates()
        logger.warning(
            "Missing language for email template '{}'".format(template_prefix))

    if from_name is None:
        from_name = "Zulip"
    if from_address is None:
        from_address = FromAddress.NOREPLY
    from_email = formataddr((from_name, from_address))
    reply_to = None
    if reply_to_email is not None:
        reply_to = [reply_to_email]
    # Remove the from_name in the reply-to for noreply emails, so that users
    # see "noreply@..." rather than "Zulip" or whatever the from_name is
    # when they reply in their email client.
    elif from_address == FromAddress.NOREPLY:
        reply_to = [FromAddress.NOREPLY]

    mail = EmailMultiAlternatives(email_subject,
                                  message,
                                  from_email,
                                  to_emails,
                                  reply_to=reply_to)
    if html_message is not None:
        mail.attach_alternative(html_message, 'text/html')
    return mail
示例#43
0
def email_notification(to, subject, html_content):
    from_email = settings.EMAIL_HOST_USER
    msg = EmailMultiAlternatives(subject, html_content, from_email, [to])
    msg.attach_alternative(html_content, "text/html")
    msg.send()
示例#44
0
def add_directory_member(request):
    perm =general_methods.control_access(request)

    if not perm:
        logout(request)
        return redirect('accounts:login')
    user_form = UserForm()
    person_form = PersonForm()
    communication_form = CommunicationForm()
    member_form = DirectoryForm()

    if request.method == 'POST':

        user_form = UserForm(request.POST)
        person_form = PersonForm(request.POST, request.FILES)
        communication_form = CommunicationForm(request.POST)
        member_form = DirectoryForm(request.POST)

        if user_form.is_valid() and person_form.is_valid() and communication_form.is_valid() and member_form.is_valid():
            user = User()
            user.username = user_form.cleaned_data['email']
            user.first_name = user_form.cleaned_data['first_name']
            user.last_name = user_form.cleaned_data['last_name']
            user.email = user_form.cleaned_data['email']
            group = Group.objects.get(name='Yonetim')
            password = User.objects.make_random_password()
            user.set_password(password)
            user.save()
            user.groups.add(group)
            user.save()

            person = person_form.save(commit=False)
            communication = communication_form.save(commit=False)
            person.save()
            communication.save()

            directoryMember = DirectoryMember(user=user, person=person, communication=communication)
            directoryMember.role = member_form.cleaned_data['role']
            directoryMember.commission = member_form.cleaned_data['commission']

            directoryMember.save()

            subject, from_email, to = 'WUSHU - Yönetim/Federasyon Bilgi Sistemi Kullanıcı Giriş Bilgileri', '*****@*****.**', user.email
            text_content = 'Aşağıda ki bilgileri kullanarak sisteme giriş yapabilirsiniz.'
            html_content = '<p> <strong>Site adresi: </strong> <a href="http://sbs.twf.gov.tr/"></a>sbs.twf.gov.tr</p>'
            html_content = html_content + '<p><strong>Kullanıcı Adı:  </strong>' + user.username + '</p>'
            html_content = html_content + '<p><strong>Şifre: </strong>' + password + '</p>'
            msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
            msg.attach_alternative(html_content, "text/html")
            msg.send()

            messages.success(request, 'Yönetim Kurulu Üyesi Başarıyla Kayıt Edilmiştir.')

            return redirect('wushu:kurul-uyeleri')

        else:

            for x in user_form.errors.as_data():
                messages.warning(request, user_form.errors[x][0])

    return render(request, 'yonetim/kurul-uyesi-ekle.html',
                  {'user_form': user_form, 'person_form': person_form, 'communication_form': communication_form, 'member_form':member_form})
def check_subscription():
    print('Run Check Subscription')
    accounts = AccountNumber.objects.all()
    for account in accounts:
        print('account', account)
        # if subscription is expire today (send mail to primary user and calgary)
        if account.is_registered and account.exp_date and account.exp_date < datetime.date.today(
        ):
            # get user profile object
            try:
                user_profile = UserProfile.objects.get(
                    user__user_type='primary', account_number=account)
            except UserProfile.DoesNotExist:
                print('*' * 80)
                print('if', account)
                print('*' * 80)
            else:
                # get user object
                user_access = user_profile.user.useraccess
                # set paid services off
                if user_access.key_finder and user_access.door_finder:
                    user_access.key_finder = False
                    user_access.door_finder = False
                    user_access.save()
                    print('parent', user_profile.user)
                    off_for_children_users(user_profile.user)
                    # send mail to customer
                    subject_customer = 'Calgary Lock and Safe'
                    message_customer = 'Calgary services expire today'

                    msg = EmailMultiAlternatives(
                        subject_customer,
                        render_to_string(
                            'email/service_expire_today.html', {
                                'full_name': user_profile.user.full_name(),
                                'account_number': account.account_number,
                                'first_name': user_profile.user.first_name,
                                'last_name': user_profile.user.last_name,
                                'phone': user_profile.user.phone,
                                'file_numbers':
                                user_profile.file_numbers.all()
                            }), EMAIL_HOST_USER, [user_profile.user.email])
                    msg.content_subtype = 'html'  # Main content is text/html
                    msg.mixed_subtype = 'related'  # This is critical, otherwise images will be displayed as attachments
                    with open(settings.STATIC_DIR + '/images/logo.png',
                              'rb') as f:
                        file = f.read()
                    image = MIMEImage(file)
                    image.add_header('Content-ID', '<logo.png>')
                    msg.attach(image)
                    msg.send()

                    # send mail to calgary
                    subject_calgary = f"{account.account_number} - {user_profile.user.full_name()}"
                    message_calgary = f"{account.account_number} expire today"
                    send_mail(
                        subject_calgary,
                        message_calgary,
                        EMAIL_HOST_USER, [settings.EMAIL_TO_CALGARY],
                        html_message=render_to_string(
                            'email/service_expire_today_to_calgary.html', {
                                'account_number': account.account_number,
                                'first_name': user_profile.user.first_name,
                                'last_name': user_profile.user.last_name,
                                'phone': user_profile.user.phone,
                                'file_numbers':
                                user_profile.file_numbers.all()
                            }))

        # 7 days before expiration of subscription (send mail to primary user and calgary)
        elif account.is_registered and account.exp_date - datetime.timedelta(
                days=7) == datetime.datetime.today():
            try:
                user_profile = UserProfile.objects.get(
                    user__user_type='primary', account_number=account)
            except UserProfile.DoesNotExist:
                print('*' * 80)
                print('else', account)
                print('*' * 80)

            # send mail to customer
            subject_customer = 'Calgary Lock and Safe'
            message_customer = 'Calgary services expire after 7 days'

            msg = EmailMultiAlternatives(
                subject_customer,
                render_to_string(
                    'email/service_expire_after_7_days.html', {
                        'full_name': user_profile.user.full_name(),
                        'account_number': account.account_number,
                        'expire_date': account.exp_date,
                        'first_name': user_profile.user.first_name,
                        'last_name': user_profile.user.last_name,
                        'phone': user_profile.user.phone,
                        'file_numbers': user_profile.file_numbers.all()
                    }),
                EMAIL_HOST_USER,
                [user_profile.user.email],
            )
            msg.content_subtype = 'html'  # Main content is text/html
            msg.mixed_subtype = 'related'  # This is critical, otherwise images will be displayed as attachments
            with open(settings.STATIC_DIR + '/images/logo.png', 'rb') as f:
                file = f.read()
            image = MIMEImage(file)
            image.add_header('Content-ID', '<logo.png>')
            msg.attach(image)
            msg.send()

            # send mail to calgary
            subject_calgary = f"{account.account_number} - {user_profile.user.full_name()}"
            message_calgary = f"{account.account_number} expires at {account.exp_date}"
            send_mail(subject_calgary,
                      message_calgary,
                      EMAIL_HOST_USER, [settings.EMAIL_TO_CALGARY],
                      html_message=render_to_string(
                          'email/service_expire_after_7_days_to_calgary.html',
                          {
                              'account_number': account.account_number,
                              'expire_date': account.exp_date,
                              'first_name': user_profile.user.first_name,
                              'last_name': user_profile.user.last_name,
                              'phone': user_profile.user.phone,
                              'file_numbers': user_profile.file_numbers.all()
                          }))
示例#46
0
def my_send_mail(ctx,
                 send_to,
                 title,
                 template_path,
                 username,
                 password,
                 smtp_host,
                 sender,
                 is_ssl=False):
    logger.debug('Enter my_send_mail function.')
    t = loader.get_template(template_path)
    html_content = t.render(Context(ctx))

    if is_ssl:
        logger.debug('Using SSL')
        import smtplib
        from email.mime.text import MIMEText

        msg = MIMEText(html_content, _subtype='html')
        msg['Subject'] = title
        msg['From'] = sender
        msg['To'] = send_to
        try:
            s = smtplib.SMTP_SSL(smtp_host, 465)
            s.login(username, password)
            s.sendmail(username, send_to, msg.as_string())
            s.quit()
        except Exception as err:
            logger.error('Mail send error: %s' % err)
        finally:
            if s:
                try:
                    s.quit()
                except:
                    pass
    else:
        try:
            logger.debug('Not Using SSL')
            conn = get_connection()  # 返回当前使用的邮件后端的实例
            conn.username = username  # 更改用户名
            conn.password = password  # 更改密码
            conn.host = smtp_host  # 设置邮件服务器
            conn.open()  # 打开连接

            mail_list = [
                send_to,
            ]
            EMAIL_HOST_USER = sender
            subject, from_email, to = title, EMAIL_HOST_USER, mail_list

            msg = EmailMultiAlternatives(subject, html_content, from_email, to)
            msg.attach_alternative(html_content, "text/html")
            conn.send_messages([
                msg,
            ])  # 我们用send_messages发送邮件
        except Exception as err:
            logger.error('Mail send error:' + str(err))
        finally:
            try:
                if conn:
                    logger.info('Close connection:' + str(conn))
                    conn.close()  # 发送完毕记得关闭连接
            except:
                pass
    def handle(*args, **options):
        last_seven_days()
        #text_content = yesterday_pendingtask_report()
        current_month()
        tasks_report()
        csvfile = BASE_DIR + file_name
        tod = datetime.today()
        sub = 'Task Report for the day : ' + tod.strftime('%d-%B-%Y')
        d = {}
        d1 = {}
        dd = date.today()
        dd1 = dd - timedelta(days=1)
        obj = User.objects.filter(is_active=True, is_staff=True)
        for i in obj:
            try:
                obj1 = Task.objects.filter(st_date=dd1, created__id=i.id)
                if not obj1:
                    objn = Project.objects.filter(user__id=i.id)
                    proj_list = []
                    for k in objn:
                        kk = smart_str(k.name)
                        proj_list.append(kk)
                    st = ''
                    for ss in proj_list:
                        st = st + str(ss) + ','
                    d1[i.username] = st
            except:
                pass
        ddm = dd.replace(day=1)
        dd1 = dd - timedelta(days=1)
        obj = User.objects.all()
        for i in obj:
            kk = i.username
            total_tasks = Task.objects.filter(st_date=dd1,
                                              user__id=i.id).count()
            try:
                inreview_tasks = Task.objects.filter(st_date=dd1,
                                                     status__label="In Review",
                                                     user__id=i.id).count()
                pending_tasks = Task.objects.filter(st_date=dd1,
                                                    status__label="Open",
                                                    user__id=i.id).count()
                d[kk] = {}
                d[kk]['task_yesterday'] = total_tasks
                d[kk]['In review'] = inreview_tasks
                d[kk]['Open'] = pending_tasks
                overdue_tasks = Task.objects.filter(
                    st_date__range=[ddm, dd],
                    user__id=i.id,
                    status__label="Open").count()
                d[kk]['Overdue_tasks'] = overdue_tasks
                if not total_tasks:
                    del d[kk]
            except:
                pass
        st = ''
        for ky in d.keys():
            st = st + str(ky) + ','
        msg1 = "hi"
        html_content = render_to_string('sendtable_template.html', {
            'msg1': msg1,
            'd11': d1,
            'lst_usrs': st,
            'dates': dd1
        })
        text_content = strip_tags(html_content)
        body = text_content
        print body
        email = EmailMultiAlternatives(sub, body, EMAIL_HOST_USER, \
                                user_mail_list, \
                            )
        email.attach_alternative(html_content, "text/html")
        attachment = open(csvfile, 'rb')
        email.attach(email_file_name, attachment.read(), 'application/csv')
        email.send()

        print('success')
示例#48
0
def email(request, type_of_leave, leave_from, leave_to, leave_days, other_reason, to, subject, html_content):
    from_email = settings.EMAIL_HOST_USER
    msg = EmailMultiAlternatives(subject, html_content, from_email, [to])
    msg.attach_alternative(html_content, "text/html")
    msg.send()
示例#49
0
def send_notification_email(language,
                            email,
                            notification,
                            translation_obj=None,
                            context=None,
                            headers=None,
                            user=None,
                            info=None):
    '''
    Renders and sends notification email.
    '''
    cur_language = django_translation.get_language()
    context = context or {}
    headers = headers or {}
    try:
        if info is None:
            info = translation_obj.__unicode__()
        weblate.logger.info('sending notification %s on %s to %s',
                            notification, info, email)

        # Load user language
        if language is not None:
            django_translation.activate(language)

        # Template name
        context['subject_template'] = 'mail/{}_subject.txt'.format(
            notification)

        # Adjust context
        context['current_site_url'] = get_site_url()
        if translation_obj is not None:
            context['translation'] = translation_obj
            context['translation_url'] = get_site_url(
                translation_obj.get_absolute_url())
        context['site_title'] = SITE_TITLE

        # Render subject
        subject = render_to_string(context['subject_template'],
                                   context).strip()

        # Render body
        body = render_to_string('mail/{}.txt'.format(notification), context)
        html_body = render_to_string('mail/{}.html'.format(notification),
                                     context)

        # Define headers
        headers['Auto-Submitted'] = 'auto-generated'
        headers['X-AutoGenerated'] = 'yes'
        headers['Precedence'] = 'bulk'
        headers['X-Mailer'] = 'Weblate {}'.format(weblate.VERSION)

        # Reply to header
        if user is not None:
            headers['Reply-To'] = user.email

        # List of recipients
        if email == 'ADMINS':
            emails = [a[1] for a in settings.ADMINS]
        else:
            emails = [email]

        # Create message
        email = EmailMultiAlternatives(
            settings.EMAIL_SUBJECT_PREFIX + subject,
            body,
            to=emails,
            headers=headers,
        )
        email.attach_alternative(html_body, 'text/html')

        # Send it out
        email.send(fail_silently=False)
    except SMTPException as error:
        weblate.logger.error('Failed to send email: %s', error)
    finally:
        django_translation.activate(cur_language)
示例#50
0
def send_templated_mail(template_name,
                        context,
                        recipients,
                        sender=None,
                        bcc=None,
                        fail_silently=False,
                        files=None):
    """
    send_templated_mail() is a wrapper around Django's e-mail routines that
    allows us to easily send multipart (text/plain & text/html) e-mails using
    templates that are stored in the database. This lets the admin provide
    both a text and a HTML template for each message.

    template_name is the slug of the template to use for this message (see
        models.EmailTemplate)

    context is a dictionary to be used when rendering the template

    recipients can be either a string, eg '*****@*****.**', or a list of strings.

    sender should contain a string, eg 'My Site <*****@*****.**>'. If you leave it
        blank, it'll use settings.DEFAULT_FROM_EMAIL as a fallback.

    bcc is an optional list of addresses that will receive this message as a
        blind carbon copy.

    fail_silently is passed to Django's mail routine. Set to 'True' to ignore
        any errors at send time.

    files can be a list of tuples. Each tuple should be a filename to attach,
        along with the File objects to be read. files can be blank.

    """
    from django.core.mail import EmailMultiAlternatives
    from django.template import engines
    from_string = engines['django'].from_string

    from helpdesk.models import EmailTemplate
    from helpdesk.settings import HELPDESK_EMAIL_SUBJECT_TEMPLATE, \
        HELPDESK_EMAIL_FALLBACK_LOCALE

    locale = context['queue'].get('locale') or HELPDESK_EMAIL_FALLBACK_LOCALE

    try:
        t = EmailTemplate.objects.get(template_name__iexact=template_name, locale=locale)
    except EmailTemplate.DoesNotExist:
        try:
            t = EmailTemplate.objects.get(template_name__iexact=template_name, locale__isnull=True)
        except EmailTemplate.DoesNotExist:
            logger.warning('template "%s" does not exist, no mail sent', template_name)
            return  # just ignore if template doesn't exist

    subject_part = from_string(
        HELPDESK_EMAIL_SUBJECT_TEMPLATE % {
            "subject": t.subject
        }).render(context).replace('\n', '').replace('\r', '')

    footer_file = os.path.join('helpdesk', locale, 'email_text_footer.txt')

    text_part = from_string(
        "%s{%% include '%s' %%}" % (t.plain_text, footer_file)
    ).render(context)

    email_html_base_file = os.path.join('helpdesk', locale, 'email_html_base.html')
    # keep new lines in html emails
    if 'comment' in context:
        context['comment'] = mark_safe(context['comment'].replace('\r\n', '<br>'))

    html_part = from_string(
        "{%% extends '%s' %%}{%% block title %%}"
        "%s"
        "{%% endblock %%}{%% block content %%}%s{%% endblock %%}" %
        (email_html_base_file, t.heading, t.html)
    ).render(context)

    if isinstance(recipients, str):
        if recipients.find(','):
            recipients = recipients.split(',')
    elif type(recipients) != list:
        recipients = [recipients]

    msg = EmailMultiAlternatives(subject_part, text_part,
                                 sender or settings.DEFAULT_FROM_EMAIL,
                                 recipients, bcc=bcc)
    msg.attach_alternative(html_part, "text/html")

    if files:
        for filename, filefield in files:
            mime = mimetypes.guess_type(filename)
            if mime[0] is not None and mime[0] == "text/plain":
                with open(filefield.path, 'r') as attachedfile:
                    content = attachedfile.read()
                    msg.attach(filename, content)
            else:
                if six.PY3:
                    msg.attach_file(filefield.path)
                else:
                    with open(filefield.path, 'rb') as attachedfile:
                        content = attachedfile.read()
                        msg.attach(filename, content)

    logger.debug('Sending email to: {!r}'.format(recipients))

    try:
        return msg.send()
    except SMTPException as e:
        logger.exception('SMTPException raised while sending email to {}'.format(recipients))
        if not fail_silently:
            raise e
        return 0
示例#51
0
def send_email_encoding(video_to_encode):
    if DEBUG:
        print("SEND EMAIL ON ENCODING COMPLETION")
    url_scheme = "https" if SECURE_SSL_REDIRECT else "http"
    content_url = "%s:%s" % (url_scheme, video_to_encode.get_full_url())
    subject = "[%s] %s" % (TITLE_SITE,
                           _(u"Encoding #%(content_id)s completed") % {
                               'content_id': video_to_encode.id
                           })
    message = "%s\n%s\n\n%s\n%s\n%s\n" % (
        _("Hello"),
        _(u"The content “%(content_title)s” has been encoded to Web " +
          "formats, and is now available on %(site_title)s.") % {
              'content_title': video_to_encode.title,
              'site_title': TITLE_SITE
          }, _(u"You will find it here:"), content_url, _("Regards"))
    full_message = message + "\n%s:%s\n%s:%s" % (
        _("Post by"), video_to_encode.owner, _("the"),
        video_to_encode.date_added)
    from_email = DEFAULT_FROM_EMAIL
    to_email = []
    to_email.append(video_to_encode.owner.email)
    html_message = ""

    html_message = '<p>%s</p><p>%s</p><p>%s<br><a href="%s"><i>%s</i></a>\
                </p><p>%s</p>' % (
        _("Hello"),
        _(u"The content “%(content_title)s” has been encoded to Web " +
          "formats, and is now available on %(site_title)s.") % {
              'content_title': '<b>%s</b>' % video_to_encode.title,
              'site_title': TITLE_SITE
          }, _(u"You will find it here:"), content_url, content_url,
        _("Regards"))
    full_html_message = html_message + "<br/>%s:%s<br/>%s:%s" % (
        _("Post by"), video_to_encode.owner, _("the"),
        video_to_encode.date_added)

    if (USE_ESTABLISHMENT and MANAGERS
            and video_to_encode.owner.owner.establishment.lower()
            in dict(MANAGERS)):
        bcc_email = []
        video_estab = video_to_encode.owner.owner.establishment.lower()
        manager = dict(MANAGERS)[video_estab]
        if type(manager) in (list, tuple):
            bcc_email = manager
        elif type(manager) == str:
            bcc_email.append(manager)
        msg = EmailMultiAlternatives(subject,
                                     message,
                                     from_email,
                                     to_email,
                                     bcc=bcc_email)
        msg.attach_alternative(html_message, "text/html")
        msg.send()
    else:
        mail_managers(subject,
                      full_message,
                      fail_silently=False,
                      html_message=full_html_message)
        if not DEBUG:
            send_mail(
                subject,
                message,
                from_email,
                to_email,
                fail_silently=False,
                html_message=html_message,
            )
示例#52
0
def render_to_email(
    text_template,
    html_template,
    to,
    subject=None,
    subject_template=None,
    context=None,
    send=True,
    opt_out=True
):
    """
    Send a multipart email using the three given templates. Note that to should
    be either User objects or email addresses as strings.

    The context gets augmented with:

     * recipients -- whatever you passed in to (use .is_authenticated() to see
       if it's a User)
     * subject -- whatever was passed or rendered (except for rendering the
       subject)
     * site_name -- the name of the site, according to the django.contrib.sites
       framework
     * domain -- the domain, according to the django.contrib.sites framework
     * protocol -- either "http" or "https" based on settings.SECURE_SSL_REDIRECT

    Note that we aren't using a RequestContext, so context processors won't run.
    Add your stuff in directly using the context parameter.

    subject preferred over subject_template if both are given.
    """

    if context is None:
        context = {}

    def active_user(user_or_email):
        try:
            return user_or_email.is_active
        except AttributeError:
            return False

    if opt_out:
        to = filter(active_user, to)
    if not to:
        return None

    context['recipients'] = to

    site = Site.objects.get_current()
    context['site_name'] = site.name
    context['domain'] = site.domain
    context['protocol'] = settings.SECURE_SSL_REDIRECT and 'https' or 'http'

    def as_email_address(user_or_email):
        try:
            return user_or_email.email
        except AttributeError:
            return user_or_email

    to_addresses = map(as_email_address, to)

    if subject is None:
        subject = render_to_string_with_autoescape_off([subject_template], context).strip()
    context['subject'] = subject

    # Rewrite all recipients to a default recipient in debug mode. Prepends to
    # the subject a debug message indicating original recipients.
    if settings.DEBUG:
        subject = '[DEBUG to:{0}] {1}'.format(','.join(to_addresses), subject)
        to_addresses = settings.DEFAULT_TO_EMAIL

    text = render_to_string_with_autoescape_off([text_template], context)
    html = render_to_string([html_template], context)

    msg = EmailMultiAlternatives(subject, text, to=to_addresses)
    msg.attach_alternative(html, 'text/html')
    if send:
        msg.send()
    return msg
示例#53
0
    def send_mail(subject,
                  html_content,
                  text_content,
                  recipients,
                  expert_request=None,
                  attach_tor=False,
                  attach_letter=False):
        # control of execution
        if email_is_off():
            return

        # control of environment
        if env_is_local():
            # local env email only to secondments mail list
            recipients = SECONDMENTS_MAIL_LIST
        # test indicator to render PDF as test sample
        test = test_is_on()
        if test:
            # subject with TEST
            subject = "This is a TEST email! " + subject

        msg = EmailMultiAlternatives(subject,
                                     text_content,
                                     EMAIL_HOST_USER,
                                     recipients,
                                     bcc=SECONDMENTS_MAIL_LIST)
        msg.attach_alternative(html_content, "text/html")
        msg.mixed_subtype = 'related'

        # attachments stuff
        if attach_letter or attach_tor:
            context = {
                'expert_request': expert_request,
                'pagesize': 'A4',
                'BASE_DIR': os.path.join(BASE_DIR, 'crppdmt/static/'),
                'test_env': test,
            }
            try:
                tor_pdf = render_to_pdf('crppdmt/pdf/tor.html', context)
                letter_pdf = render_to_pdf(
                    'crppdmt/pdf/letter_of_request.html', context)
                msg.attach('ToR.pdf', tor_pdf, 'application/pdf')
                msg.attach('LetterOfRequest.pdf', letter_pdf,
                           'application/pdf')
            except:
                print("Error attaching ToR and Letter to Email. Request: " +
                      expert_request.name)
                print("Error: " + str(sys.exc_info()))

        msg.send()
示例#54
0
def contactFormView(request):
    if request.method == "POST":
        query_dict = request.POST #request.data doesnt work for some reason

        customer_name = query_dict['name']
        email = query_dict['email']
        phone_number = query_dict['phone_number']
        website = query_dict['website']
        message = query_dict['message']

        if request.user.is_authenticated: #if user is logged in as shipper or trucker
            out_message = "Hi, " + customer_name + " has contacted the team with the following message: \n \n"
            out_message += message + "\n \n"
            out_message += "Get back to him at " + email + ". \n \n \n"

            user = request.user
            user_type = str(user.profile.user_type)
            out_message += "Additional user info:  \n \n"
            out_message += "username: "******"\n"
            out_message += "user type: " + str(user.profile.user_type) + "\n"
            out_message += "registered email: " + user_type + "\n"
            if len(website) > 0:
                out_message += "given website: " + website + "\n"
            if len(phone_number) > 0:
                out_message += "given phone number: " + phone_number + "\n"
            send_mail(
            customer_name + ' HAS A NEW HELP REQUEST!', #email subject
            out_message, #email content
            '*****@*****.**',
            ['*****@*****.**'],
            fail_silently = False,
            )

            #send another mail confirming help is on the way
            send_mail(
            'Help is on the way!', #email subject
            """Dear """ + customer_name + """, \n
    Thank you for reaching out to the Cargoful team! \n
    We will review your message and get back to you soon. \n \n
    Never alone with Cargoful! \n
    Your Cargoful team \n \n
    Here your request: \n""" + message, #email content
            '*****@*****.**',
            [email],
            fail_silently = False,
            )

            subject, from_email, to = 'La ayuda va en camino', settings.EMAIL_HOST_USER, email
            text_content = render_to_string('emails/help_otw/help_otw_ES_txt.html', {
            'name': customer_name,
            'message':message
            })
            msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
            html_template = get_template("emails/help_otw/help_otw_ES.html").render({
                                        'name': customer_name,
                                        'message':message
                                        })
            msg.attach_alternative(html_template, "text/html")
            msg.send()

            messages.info(request, "Thanks "+ str(customer_name)
            + "! We have received your message and will get back to you shortly at " + email)
            if user_type == "Shipper":
                return HttpResponseRedirect('/shipper')
            else:
                return HttpResponseRedirect('/trucker')
        else:
            out_message = """Hi, an unauthenticated user named """ + customer_name
            out_message += """has contacted the team with the following message: \n \n """
            out_message += message + "\n \n"
            out_message += "Get back to him at " + email + ". \n \n \n"
            if len(website) > 0:
                out_message += "given website: " + website + "\n"
            if len(phone_number) > 0:
                out_message += "given phone number: " + phone_number + "\n"
            send_mail(
            customer_name + ' HAS A NEW HELP REQUEST!', #email subject
            out_message, #email content
            '*****@*****.**',
            ['*****@*****.**'],
            fail_silently = False,
            )

            #send another mail confirming help is on the way
            send_mail(
            'Help is on the way!', #email subject
            """Dear """ + customer_name + """, \n
Thank you for reaching out to the Cargoful team! \n
We will review your message and get back to you soon. \n \n
Never alone with Cargoful! \n
Your Cargoful team \n \n
Here your request: \n""" + message, #email content
            '*****@*****.**',
            [email],
            fail_silently = False,
            )


            return HttpResponseRedirect('/accounts/login')
    else:
        return render(request, 'contact_form.html')
示例#55
0
def send_templated_mail(template_name, email_context, recipients, sender=None, bcc=None, fail_silently=False, files=None):
    """
    send_templated_mail() is a warpper around Django's e-mail routines that
    allows us to easily send multipart (text/plain & text/html) e-mails using
    templates that are stored in the database. This lets the admin provide
    both a text and a HTML template for each message.

    template_name is the slug of the template to use for this message (see
        models.EmailTemplate)

    email_context is a dictionary to be used when rendering the template

    recipients can be either a string, eg '*****@*****.**', or a list of strings.

    sender should contain a string, eg 'My Site <*****@*****.**>'. If you leave it
        blank, it'll use settings.DEFAULT_FROM_EMAIL as a fallback.

    bcc is an optional list of addresses that will receive this message as a
        blind carbon copy.

    fail_silently is passed to Django's mail routine. Set to 'True' to ignore
        any errors at send time.

    files can be a list of tuple. Each tuple should be a filename to attach, 
        along with the File objects to be read. files can be blank.

    """
    from django.conf import settings
    from django.core.mail import EmailMultiAlternatives
    from django.template import Context, engines

    from helpdesk.models import EmailTemplate
    from helpdesk.settings import HELPDESK_EMAIL_SUBJECT_TEMPLATE
    import os

    context = Context(email_context)

    if hasattr(context['queue'], 'locale'):
        locale = getattr(context['queue'], 'locale', '')
    else:
        locale = context['queue'].get('locale', 'en')
    if not locale:
        locale = 'en'

    t = None
    print template_name
    try:
        t = EmailTemplate.objects.get(template_name__iexact=template_name, locale=locale)
    except EmailTemplate.DoesNotExist:
        pass

    if not t:
        try:
            t = EmailTemplate.objects.get(template_name__iexact=template_name, locale__isnull=True)
        except EmailTemplate.DoesNotExist:
            logger.warning('template "%s" does not exist, no mail sent' %
			   template_name)
            return # just ignore if template doesn't exist

    if not sender:
        sender = settings.DEFAULT_FROM_EMAIL

    footer_file = os.path.join('helpdesk', locale, 'email_text_footer.txt')

    text_part = engines['django'].from_string(
        "%s{%% include '%s' %%}" % (t.plain_text, footer_file)
        ).render(context)

    email_html_base_file = os.path.join('helpdesk', locale, 'email_html_base.html')


    ''' keep new lines in html emails '''
    from django.utils.safestring import mark_safe

    if context.has_key('comment'):
        html_txt = context['comment']
        html_txt = html_txt.replace('\r\n', '<br>')
        context['comment'] = mark_safe(html_txt)

    html_part = engines['django'].from_string(
        "{%% extends '%s' %%}{%% block title %%}%s{%% endblock %%}{%% block content %%}%s{%% endblock %%}" % (email_html_base_file, t.heading, t.html)
        ).render(context)

    subject_part = engines['django'].from_string(
        HELPDESK_EMAIL_SUBJECT_TEMPLATE % {
            "subject": t.subject,
        }).render(context)

    if isinstance(recipients,(str,unicode)):
        if recipients.find(','):
            recipients = recipients.split(',')
    elif type(recipients) != list:
        recipients = [recipients,]

    msg = EmailMultiAlternatives(   subject_part.replace('\n', '').replace('\r', ''),
                                    text_part,
                                    sender,
                                    recipients,
                                    bcc=bcc)
    msg.attach_alternative(html_part, "text/html")

    if files:
        for attachment in files:
            file_to_attach = attachment[1]
            file_to_attach.open()
            msg.attach(filename=attachment[0], content=file_to_attach.read())
            file_to_attach.close()

    return msg.send(fail_silently)
示例#56
0
文件: views.py 项目: wilbys/gestion
def send_amonestacion(request, mes, ano, dia):
    info = {}
    contenido = ""
    fecha2 = datetime(int(ano), int(mes), int(dia))
    info["fecha"] = "%s/%s/%s" % (dia, mes, ano)
    lista_alumnos = set(
        Amonestaciones.objects.filter(Fecha=fecha2).values_list("IdAlumno"))

    info["amonestaciones"] = Amonestaciones.objects.filter(Fecha=fecha2)

    info["enviados"] = []
    info["noemail"] = []
    info["yaenviados"] = []
    for i in info["amonestaciones"]:
        info2 = {}
        info2["amonestacion"] = i
        info2["num_amon"] = len(
            Amonestaciones.objects.filter(IdAlumno_id=i.IdAlumno.id))
        template = get_template("pdf_contenido_carta_amonestacion.html")
        contenido = template.render(Context(info2))
        asunto = "IES Gonzalo Nazareno. Amonestación: " + i.IdAlumno.Nombre.encode(
            "utf-8") + " - Hora:" + i.Hora.encode("utf-8")
        # 8/4/2021
        correos = Correos.objects.filter(Fecha=fecha2).filter(Asunto=asunto)
        # Se envía el correo
        if len(i.IdAlumno.email) > 0 and len(correos) == 0:
            try:
                msg = ""
                msg = EmailMultiAlternatives(
                    asunto, contenido, '*****@*****.**',
                    [i.IdAlumno.email])

                msg.attach_alternative(contenido, "text/html")
                msg.send(fail_silently=False)
                # 8/4/2021
                f = datetime.strptime(info["fecha"], '%d/%m/%Y')
                new_correo = Correos(Fecha=f.strftime("%Y-%m-%d"),
                                     Asunto=asunto,
                                     Contenido=contenido)
                new_correo.save()
                info["enviados"].append({
                    'Nombre': i.IdAlumno.Nombre,
                    'email': i.IdAlumno.email
                })

            except:
                pass
        # Ya se ha enviado
        elif len(i.IdAlumno.email) > 0 and len(correos) > 0:
            info["yaenviados"].append({
                'Nombre': i.IdAlumno.Nombre,
                'email': i.IdAlumno.email
            })
        elif len(i.IdAlumno.email) == 0:
            info["noemail"].append({
                'Nombre': i.IdAlumno.Nombre,
                'email': i.IdAlumno.email
            })
    print info
    context = {
        "info":
        info,
        "url":
        "/convivencia/show/amonestacion/" + str(mes) + "/" + str(ano) + "/" +
        str(dia)
    }
    return render(request, "send_amonestacion.html", context)
示例#57
0
文件: mail.py 项目: pajowu/pretix
def mail_send_task(self, *args, to: List[str], subject: str, body: str, html: str, sender: str,
                   event: int=None, position: int=None, headers: dict=None, bcc: List[str]=None,
                   invoices: List[int]=None, order: int=None, attach_tickets=False, user=None) -> bool:
    email = EmailMultiAlternatives(subject, body, sender, to=to, bcc=bcc, headers=headers)
    if html is not None:
        html_with_cid, cid_images = replace_images_with_cid_paths(html)
        email = attach_cid_images(email, cid_images, verify_ssl=True)
        email.attach_alternative(html_with_cid, "text/html")

    if user:
        user = User.objects.get(pk=user)

    if event:
        with scopes_disabled():
            event = Event.objects.get(id=event)
        backend = event.get_mail_backend()
        cm = lambda: scope(organizer=event.organizer)  # noqa
    else:
        backend = get_connection(fail_silently=False)
        cm = lambda: scopes_disabled()  # noqa

    with cm():
        if invoices:
            invoices = Invoice.objects.filter(pk__in=invoices)
            for inv in invoices:
                if inv.file:
                    try:
                        email.attach(
                            '{}.pdf'.format(inv.number),
                            inv.file.file.read(),
                            'application/pdf'
                        )
                    except:
                        logger.exception('Could not attach invoice to email')
                        pass
        if event:
            if order:
                try:
                    order = event.orders.get(pk=order)
                except Order.DoesNotExist:
                    order = None
                else:
                    if position:
                        try:
                            position = order.positions.get(pk=position)
                        except OrderPosition.DoesNotExist:
                            attach_tickets = False
                    if attach_tickets:
                        args = []
                        attach_size = 0
                        for name, ct in get_tickets_for_order(order, base_position=position):
                            content = ct.file.read()
                            args.append((name, content, ct.type))
                            attach_size += len(content)

                        if attach_size < 4 * 1024 * 1024:
                            # Do not attach more than 4MB, it will bounce way to often.
                            for a in args:
                                try:
                                    email.attach(*a)
                                except:
                                    pass
                        else:
                            order.log_action(
                                'pretix.event.order.email.attachments.skipped',
                                data={
                                    'subject': 'Attachments skipped',
                                    'message': 'Attachment have not been send because {} bytes are likely too large to arrive.'.format(attach_size),
                                    'recipient': '',
                                    'invoices': [],
                                }
                            )

            email = email_filter.send_chained(event, 'message', message=email, order=order, user=user)

        email = global_email_filter.send_chained(event, 'message', message=email, user=user, order=order)

        try:
            backend.send_messages([email])
        except smtplib.SMTPResponseException as e:
            if e.smtp_code in (101, 111, 421, 422, 431, 442, 447, 452):
                self.retry(max_retries=5, countdown=2 ** (self.request.retries * 2))
            logger.exception('Error sending email')

            if order:
                order.log_action(
                    'pretix.event.order.email.error',
                    data={
                        'subject': 'SMTP code {}'.format(e.smtp_code),
                        'message': e.smtp_error.decode() if isinstance(e.smtp_error, bytes) else str(e.smtp_error),
                        'recipient': '',
                        'invoices': [],
                    }
                )

            raise SendMailException('Failed to send an email to {}.'.format(to))
        except Exception as e:
            if order:
                order.log_action(
                    'pretix.event.order.email.error',
                    data={
                        'subject': 'Internal error',
                        'message': str(e),
                        'recipient': '',
                        'invoices': [],
                    }
                )
            logger.exception('Error sending email')
            raise SendMailException('Failed to send an email to {}.'.format(to))
示例#58
0
文件: email.py 项目: hb9kns/NEMO
def send_broadcast_email(request):
    if not get_media_file_contents('generic_email.html'):
        return HttpResponseBadRequest(
            'Generic email template not defined. Visit the NEMO customizable_key_values page to upload a template.'
        )
    form = EmailBroadcastForm(request.POST)
    if not form.is_valid():
        return render(request, 'email/compose_email.html', {'form': form})
    dictionary = {
        'title': form.cleaned_data['title'],
        'greeting': form.cleaned_data['greeting'],
        'contents': form.cleaned_data['contents'],
        'template_color': form.cleaned_data['color'],
    }
    content = get_media_file_contents('generic_email.html')
    content = Template(content).render(Context(dictionary))
    users = None
    audience = form.cleaned_data['audience']
    selection = form.cleaned_data['selection']
    active_choice = form.cleaned_data['only_active_users']
    try:
        if audience == 'tool':
            users = User.objects.filter(qualifications__id=selection)
        elif audience == 'project':
            users = User.objects.filter(projects__id=selection)
        elif audience == 'account':
            users = User.objects.filter(projects__account__id=selection)
        elif audience == 'all':
            users = User.objects.all()
        if active_choice:
            users = users.filter(is_active=True)
    except:
        dictionary = {
            'error':
            'Your email was not sent. There was a problem finding the users to send the email to.'
        }
        return render(request, 'email/compose_email.html', dictionary)
    if not users:
        dictionary = {
            'error':
            'The audience you specified is empty. You must send the email to at least one person.'
        }
        return render(request, 'email/compose_email.html', dictionary)
    if audience == 'tool':
        t = Tool.objects.filter(id=selection)
        subject = t[0].name + ': ' + form.cleaned_data['subject']
    else:
        subject = form.cleaned_data['subject']
    users = [x.email for x in users]
    if form.cleaned_data['copy_me']:
        users += [request.user.email]
    try:
        email = EmailMultiAlternatives(subject,
                                       from_email=request.user.email,
                                       bcc=set(users))
        email.attach_alternative(content, 'text/html')
        email.send()
    except SMTPException as e:
        dictionary = {
            'title':
            'Email not sent',
            'heading':
            'There was a problem sending your email',
            'content':
            'NEMO was unable to send the email through the email server. The error message that NEMO received is: '
            + str(e),
        }
        return render(request, 'acknowledgement.html', dictionary)
    dictionary = {
        'title': 'Email sent',
        'heading': 'Your email was sent',
    }
    return render(request, 'acknowledgement.html', dictionary)
示例#59
0
    def prepare_email_message(self):
        """
        Returns a django ``EmailMessage`` or ``EmailMultiAlternatives`` object,
        depending on whether html_message is empty.
        """
        if get_override_recipients():
            self.to = get_override_recipients()

        if self.template is not None:
            engine = get_template_engine()
            subject = engine.from_string(self.template.subject).render(
                self.context)
            plaintext_message = engine.from_string(
                self.template.content).render(self.context)
            multipart_template = engine.from_string(self.template.html_content)
            html_message = multipart_template.render(self.context)

        else:
            subject = smart_str(self.subject)
            plaintext_message = self.message
            multipart_template = None
            html_message = self.html_message

        connection = connections[self.backend_alias or 'default']

        if html_message:
            if plaintext_message:
                msg = EmailMultiAlternatives(subject=subject,
                                             body=plaintext_message,
                                             from_email=self.from_email,
                                             to=self.to,
                                             bcc=self.bcc,
                                             cc=self.cc,
                                             headers=self.headers,
                                             connection=connection)
                msg.attach_alternative(html_message, "text/html")
            else:
                msg = EmailMultiAlternatives(subject=subject,
                                             body=html_message,
                                             from_email=self.from_email,
                                             to=self.to,
                                             bcc=self.bcc,
                                             cc=self.cc,
                                             headers=self.headers,
                                             connection=connection)
                msg.content_subtype = 'html'
            if hasattr(multipart_template, 'attach_related'):
                multipart_template.attach_related(msg)

        else:
            msg = EmailMessage(subject=subject,
                               body=plaintext_message,
                               from_email=self.from_email,
                               to=self.to,
                               bcc=self.bcc,
                               cc=self.cc,
                               headers=self.headers,
                               connection=connection)

        for attachment in self.attachments.all():
            if attachment.headers:
                mime_part = MIMENonMultipart(*attachment.mimetype.split('/'))
                mime_part.set_payload(attachment.file.read())
                for key, val in attachment.headers.items():
                    try:
                        mime_part.replace_header(key, val)
                    except KeyError:
                        mime_part.add_header(key, val)
                msg.attach(mime_part)
            else:
                msg.attach(attachment.name,
                           attachment.file.read(),
                           mimetype=attachment.mimetype or None)
            attachment.file.close()

        self._cached_email_message = msg
        return msg
 def handle(self, *args, **options):
     bills = Bill.objects.filter(status='published')
     domain = Site.objects.get_current().domain + settings.FORCE_SCRIPT_NAME
     for bill in bills:
         segment_amendments = defaultdict(list)
         amendment_comments = defaultdict(list)
         top_amendments = []
         segment_ctype = ContentType.objects.get_for_model(BillSegment)
         for segment in bill.segments.filter(original=True):
             up_votes_segment = UpDownVote.objects.filter(
                 content_type=segment_ctype,
                 object_id=segment.id,
                 vote=True).count()
             down_votes_segment = UpDownVote.objects.filter(
                 content_type=segment_ctype,
                 object_id=segment.id,
                 vote=False).count()
             score_segment = up_votes_segment - down_votes_segment
             for amendment in segment.substitutes.all():
                 votes_amendment = UpDownVote.objects.filter(
                     content_type=segment_ctype, object_id=amendment.pk)
                 try:
                     last_email = HistoryNotification.objects.get(
                         amendment=amendment)
                     if votes_amendment:
                         up_votes_amendment = votes_amendment.filter(
                             vote=True).count()
                         down_votes_amendment = votes_amendment.filter(
                             vote=False).count()
                         score_amendment = up_votes_amendment - down_votes_amendment
                         last_vote = votes_amendment.latest('modified')
                         if last_email.hour < last_vote.modified:
                             if score_amendment > score_segment:
                                 top_amendments.append(amendment.id)
                     comments = Comment.objects.filter(
                         object_pk=amendment.pk,
                         content_type=segment_ctype,
                         submit_date__gte=last_email.hour)
                     if comments:
                         for comment in comments:
                             amendment_comments[amendment].append(comment)
                         last_email.hour = datetime.now()
                         last_email.save()
                 except HistoryNotification.DoesNotExist:
                     segment_amendments[segment].append(amendment)
                     comments = Comment.objects.filter(
                         object_pk=amendment.pk, content_type=segment_ctype)
                     history = HistoryNotification()
                     history.amendment = amendment
                     history.hour = datetime.now()
                     if comments:
                         for comment in comments:
                             amendment_comments[amendment].append(comment)
                             history.hour = datetime.now()
                     history.save()
                     if votes_amendment:
                         up_votes_amendment = votes_amendment.filter(
                             vote=True).count()
                         down_votes_amendment = votes_amendment.filter(
                             vote=False).count()
                         score_amendment = up_votes_amendment - down_votes_amendment
                         if score_amendment > score_segment:
                             top_amendments.append(amendment.id)
         if segment_amendments or amendment_comments or top_amendments:
             try:
                 proposition = bill.proposition_set.all(
                 )[0].name_proposition
             except:
                 proposition = ''
             html = render_to_string(
                 'notification/notification_email.html', {
                     'domain':
                     domain,
                     'bill':
                     bill.title,
                     'amendments':
                     dict(segment_amendments),
                     'comments':
                     dict(amendment_comments),
                     'proposition':
                     proposition,
                     'top_amendments':
                     BillSegment.objects.filter(id__in=top_amendments)
                 })
             email_list = ['*****@*****.**']
             subject = u'[Wikilegis] Atualizações ao %s %s' % (bill.title,
                                                               proposition)
             for editor in bill.editors.all():
                 for user in editor.user_set.all():
                     email_list.append(user.email)
             mail = EmailMultiAlternatives(subject,
                                           '',
                                           '',
                                           '',
                                           bcc=email_list)
             mail.attach_alternative(html, 'text/html')
             mail.send()