Beispiel #1
0
def send_mail_to(req, emails, attachments, subject, body): # Переписать attach как список имен файлов
    '''Отправка письма с кодировкой'''
    import base64

    #sample_data = data['sample_data'].copy()
    manager_mail = req['manager_mail']
    if manager_mail == '*****@*****.**':
        manager_mail = '*****@*****.**'
    try:
        user = MailPass.objects.get(email=manager_mail)
    except:
        logging.debug('Не удалось найти данные почтового адреса менеджера для отправки письма')
        return None
    
    manager_mail_pass = base64.b64decode(user.password.encode()).decode('utf-8')
    em = EmailMessage(subject=subject, body=body,
                      to=emails, from_email=manager_mail
    )
    em.content_subtype = 'html'
    for attach in attachments:
        em.attach_file(attach) 
    EmailBackend(
        host = 'mail.stardustpaints.ru',
        username = manager_mail,
        password = manager_mail_pass,
        #use_ssl = True,
        use_tls = True,
        port = 587
    ).send_messages([em])    
def admin_password_reset(email):
    user_data = User.objects.get(email=email)
    slug = (email.split('@')[0])
    password = '******'.format(slug)
    # print("++++++++,",password,",+++++++")
    user_data.set_password(password)
    user_data.save()
    var = {
        'password':password,
        'username': user_data.username,
    }

    sub = "Password Reset Successfully"
    to = [email]

    edata = email_configuration.objects.get(id=1)

    backend = EmailBackend(host=edata.email_host,port=edata.email_port,username=edata.email_username,password=edata.email_password,
                    use_tls=edata.use_tls,use_ssl=edata.use_ssl,fail_silently=edata.fail_silently)

    html_body = render_to_string('email/password_reset.html',{'var':var})
    text_body = strip_tags(html_body)

    email = EmailMultiAlternatives(
        sub,
        text_body,
        '*****@*****.**',
        to,
        connection=backend
    )
    email.attach_alternative(html_body,"text/html")
    # email.attach_file('Document.pdf')
    email.send()
    return True
Beispiel #3
0
def newsletter_send(request):
    if request.method == "POST":
        form = SendNewsletterForm(request.POST)
        if form.is_valid() and request.user.is_authenticated and len(
                Email.objects.values_list('smtp', flat=True)) > 0:
            data = form.cleaned_data
            text = data['text']
            title = data['title']
            message = Message(text=text, title=title)
            message.save()
            config = instance = Email.objects.get(pk=1)
            recipients = Newsletter.objects.filter(confirmed=True)
            for recipient in recipients:
                url = request.build_absolute_uri('?')[:-len(
                    'newsletter-send')] + "newsletter-remove/" + recipient.code
                send_mail(subject=title,
                          message="Aby odczytać wiadomość włącz obsługę html.",
                          html_message=text + " " +
                          unsubscribe_text.replace("{@url}", url),
                          from_email=config.email,
                          recipient_list=[recipient.email],
                          auth_user=config.email,
                          auth_password=config.password,
                          connection=EmailBackend(host=config.smtp,
                                                  port=config.sslPort,
                                                  username=config.email,
                                                  password=config.password,
                                                  use_tls=False,
                                                  use_ssl=True))
            return redirect('post_list')
    else:
        form = SendNewsletterForm()
    return render(request, 'blog/newsletter_send.html', {'form': form})
Beispiel #4
0
def newsletter_add(request):
    if request.method == "POST":
        form = NewsletterForm(request.POST)
        if form.is_valid() and len(Email.objects.values_list('smtp',
                                                             flat=True)) > 0:
            data = form.cleaned_data
            code = ''.join(
                random.choices(string.ascii_letters + string.digits, k=40))
            url = request.build_absolute_uri(
                '?')[:-len('newsletter-add')] + "newsletter-confirm/" + code
            email = data['email']
            config = instance = Email.objects.get(pk=1)
            Newsletter.objects.filter(email=email).delete()
            newsletter = Newsletter(email=email, code=code)
            newsletter.add()
            send_mail(subject=activation_title,
                      message=activation_text.replace("{@url}", url),
                      from_email=config.email,
                      recipient_list=[email],
                      auth_user=config.email,
                      auth_password=config.password,
                      connection=EmailBackend(host=config.smtp,
                                              port=config.sslPort,
                                              username=config.email,
                                              password=config.password,
                                              use_tls=False,
                                              use_ssl=True))
            return redirect('post_list')
    else:
        form = NewsletterForm()
    return render(request, 'blog/newsletter_add.html', {'form': form})
def enviarpedido(request):
    if "is_auth" not in request.session and "user_id" not in request.session:
        return render(request, 'index.html', None)
    else:
        customer = Customer.objects.get(pk=request.session['user_id'])

        response = {'status': 'success'}
        if request.is_ajax():
            jsondata = json.loads(request.body)

            productos = jsondata['productos']

            for prod in productos:
                producto = Products.objects.get(pk=prod['id'])
                prod['total'] = producto.price * prod['cantidad']
                prod['name'] = producto.name
                prod['price'] = producto.price

            numeroOrden = util.generarOrder(customer)
            newPedido = Orders(number=numeroOrden,
                               customer=customer,
                               send=0,
                               date=now)
            newPedido.save()

            nombreFichero = excel.generaExcelPedido(productos, customer,
                                                    newPedido)

            ficheroExcel = 'media/pedidos/' + str(
                customer.pk) + '/' + numeroOrden + "/" + nombreFichero

            conexionSMTP = EmailBackend(host='smtp.bernini.es',
                                        port='587',
                                        username='******',
                                        password='******',
                                        use_tls='True')

            try:
                emails = {'from_email': '*****@*****.**'}
                contenidoEmail = {
                    'titulo':
                    customer.name + ' ' + customer.lastname +
                    ' - Resumen de pedido'
                }
                contenidoEmail['productos'] = productos
                util.enviarEmailAdjuntos(customer, 'envio-pedido.html',
                                         conexionSMTP, emails, ficheroExcel,
                                         contenidoEmail)

                newPedido.send = 1
                newPedido.save()

                response = {'status': 'success'}
            except Exception as e:
                print(e)

                response = {'status': 'error'}

        return HttpResponse(json.dumps(response),
                            content_type="application/json")
Beispiel #6
0
    def send_mail(self, subject, body):

        if not self.email_is_configured:
            return False

        try:
            backend = EmailBackend(
                host=self.smtp_host,
                port=self.smtp_port,
                username=self.smtp_host_user,
                password=self.smtp_host_password,
                use_tls=self.smtp_use_tls,
                fail_silently=False,
            )

            email = EmailMessage(
                subject=subject,
                body=body,
                from_email=self.smtp_host_user,
                to=self.email_alert_recipients,
                connection=backend,
            )

            email.send()
        except Exception as e:
            logger.error(f"Sending email failed with error: {e}")
Beispiel #7
0
 def soc_send_email(self, title, content, host, username, password, use_tls, use_ssl, send_address, to):
     """
     :param title:  标题
     :param content:     内容
     :param host:    服务器
     :param username:    用户名
     :param password:    密码
     :param use_tls:     tls加密
     :param use_ssl:     ssl加密
     :param send_address:    发件人 一般和用户名一致
     :param to:  收件人
     :return: 
     构造一个smtp 然后发送邮件
     返回的status不为0则为成功
     """
     try:
         port = 25
         if int(use_ssl):
             port = 465
         smtp = EmailBackend(host=host, username=username,
                             password=password, use_ssl=bool(int(use_ssl)), use_tls=bool(int(use_tls)), port=port)
         status = send_mail(title, content, send_address,
                            [to], fail_silently=False, auth_user=username,
                            auth_password=password, connection=smtp)
         logger.info("send email success  to %s content=%s" % (to, content))
         return status, 'ok'
     except Exception, e:
         logger.warning("send email error  to %s content=%s, errors=%s" % (to, content, str(e)))
         return 0, '发送错误'
Beispiel #8
0
def send_email(
    recipient,
    subject,
    body_text,
    user_email,
    user_password,
    host,
    port,
    use_tls,
    fail_silently=False,
    body_html=None,
):
    # Create custom backend
    backend = EmailBackend(
        host=host,
        port=port,
        username=user_email,
        password=user_password,
        use_tls=use_tls,
        fail_silently=fail_silently,
    )

    # Create email object
    email = EmailMultiAlternatives(
        subject,  # email subject
        body_text,  # the body txt
        user_email,  # send from
        [recipient],  # the recipient
        connection=backend,  # use the custom backend
    )
    if body_html:
        # Attach html body
        email.attach_alternative(body_html, "text/html")
    # Send the email
    email.send()
Beispiel #9
0
def enviar_email_mp(assunto, mensagem, csv):
    try:
        config = DynamicEmailConfiguration.get_solo()
        email_mp = EmailMercadoPago.objects.first()
        email_novo = None
        email_ja_enviado = LogEmailMercadoPago.objects.filter(
            enviar_para=email_mp.email,
            assunto=assunto,
            enviado=False,
            csv=csv)
        if not email_ja_enviado:
            email_novo = LogEmailMercadoPago.objects.create(
                enviar_para=email_mp.email,
                assunto=assunto,
                mensagem=mensagem,
                csv=csv)
        msg = EmailMessage(subject=assunto,
                           body=mensagem,
                           from_email=config.from_email or None,
                           bcc=(email_mp.email, ),
                           connection=EmailBackend(**config.__dict__))
        msg.send()
        if email_ja_enviado.exists():
            email_ja_enviado.update(enviado=True)
        elif email_novo:
            email_novo.enviado = True
            email_novo.save()
    except Exception as err:
        logger.error(str(err))
Beispiel #10
0
def send_custom_email_to_admins(request):
    user_data = User.objects.all()
    var = {
        'u':udata,
    }
    to = ['*****@*****.**']

    edata = email_configuration.objects.get(id=1)
    print("Before Backend")
    backend = EmailBackend(host=edata.email_host,port=edata.email_port,username=edata.email_username,password=edata.email_password,
                    use_tls=edata.use_tls,use_ssl=edata.use_ssl,fail_silently=edata.fail_silently)
    print("After Backend")
    html_body = render_to_string('email/contact_us.html',{'var':var})
    text_body = strip_tags(html_body)

    email = EmailMultiAlternatives(
        "Just for Testing - 2",
        text_body,
        'bharatlvora814',
        to,
        connection=backend
    )
    email.attach_alternative(html_body,"text/html")
    # email.attach_file('Document.pdf')
    email.send()
    return True
Beispiel #11
0
def postcommentsmtp(request):
    if request.is_ajax():
        data = request.body
        jsondata = json.loads(data)
        userlist = jsondata.get('userlist')
        toemails = []
        usrlist = User.objects.filter(id__in=userlist)
        for usr in usrlist:
            toemails.append(usr.email)

        comments = jsondata.get('comments')
        orgid = jsondata.get('orgid')
        smtpdtl = SMTPDetails.objects.get(organizationid=orgid)
        print('toemails-->', toemails)
        print('comments-->', comments)
        print('smtpdtl-->', smtpdtl)
        if len(toemails) >= 1:
            backend = EmailBackend(host=smtpdtl.host,
                                   port=smtpdtl.port,
                                   username=smtpdtl.username,
                                   password=smtpdtl.passwrd,
                                   use_tls=True,
                                   fail_silently=False)
            # backend = EmailBackend(host='smtp.gmail.com', port=587, username='******',
            #             password='******', use_tls=True , fail_silently=False)

            email = EmailMessage(subject='CDASH - Post Comments message !',
                                 body=comments,
                                 from_email=smtpdtl.username,
                                 to=toemails,
                                 connection=backend)
            email.send()

    return HttpResponse(json.dumps(json_response),
                        content_type='application/json')
Beispiel #12
0
def get_smtp_connection(campaign):
    """Get SMTP connection.

    :param campaign: `.models.Campaign`
    :return: SMTP connection
    """
    if not campaign.smtp_host:
        return None

    options = {}
    for attr in dir(campaign):
        # get smtp infos
        if attr.startswith('smtp_'):
            index = attr.replace('smtp_', '')
            value = getattr(campaign, attr)

            # if port in host: extract port
            if index == 'host' and ':' in value:
                options['port'] = int(value.split(':')[-1])
                value = value.split(':')[0]

            # add value
            if value:
                options[index] = value

    return EmailBackend(**options)
Beispiel #13
0
def send(email_from, email_to, subject, body, attachment=None):
    """ Sends an email using the outgoing email settings. """
    email_settings = EmailSettings.get_solo()

    logger.debug('Email: Preparing to send email using mail server %s:%s',
                 email_settings.host, email_settings.port)
    email_backend = EmailBackend(host=email_settings.host,
                                 port=email_settings.port,
                                 username=email_settings.username,
                                 password=email_settings.password,
                                 use_tls=email_settings.use_tls,
                                 use_ssl=email_settings.use_ssl)

    # Force translations.
    message = mail.EmailMessage(
        subject=subject,
        body=body,
        from_email=email_from,
        to=[email_to],
        connection=email_backend,
    )

    if attachment:
        message.attach_file(attachment)

    logger.debug('Email backup: Sending an email to %s (%s)', email_to,
                 subject)
    message.send()
Beispiel #14
0
def send_email(title,
               content,
               notify_level,
               to_list,
               fail_silently=False,
               attachment=None,
               cc_recipient=None,
               template='email_template.html'):
    notification_rule = NotificationRule.objects.get_active_notification_rule()
    if notification_rule:
        backend = EmailBackend(host=notification_rule.email_host,
                               port=notification_rule.email_port,
                               username=notification_rule.email_host_user,
                               password=notification_rule.email_host_password,
                               use_tls=notification_rule.email_user_ssl,
                               fail_silently=fail_silently)
        if template:
            html_content = loader.render_to_string(template, content)
        else:
            html_content = content
        subject = f'({notify_level}) {title}'
        send_html_email = SendHtmlEmail(subject, html_content, to_list,
                                        fail_silently, attachment,
                                        cc_recipient, backend)
        send_html_email.run()
        return True
    else:
        return False
Beispiel #15
0
def send(email_from: str,
         email_to: str,
         subject: str,
         body: str,
         attachment: str = None) -> None:
    """ Sends an email using the outgoing email settings. """
    email_settings = EmailSettings.get_solo()

    logger.debug('Email: Preparing to send email using mail server %s:%s',
                 email_settings.host, email_settings.port)
    email_backend = EmailBackend(host=email_settings.host,
                                 port=email_settings.port,
                                 username=email_settings.username,
                                 password=email_settings.password,
                                 use_tls=email_settings.use_tls,
                                 use_ssl=email_settings.use_ssl)

    # Prevent hanging processes, ensure there is always a timeout set.
    email_backend.timeout = email_backend.timeout if email_backend.timeout is not None else 30

    message = mail.EmailMessage(
        subject=subject,
        body=body,
        from_email=email_from,
        to=[email_to],
        connection=email_backend,
    )

    if attachment:
        message.attach_file(attachment)

    logger.debug('Email backup: Sending an email to %s (%s)', email_to,
                 subject)
    message.send()
Beispiel #16
0
def on_answer_to_answer_create(sender, instance, created, **kwargs):
    if not created or not instance.reply_to:
        return
    try:
        answer = ReviewAnswer.objects.get(pk=instance.reply_to.pk,
                                          get_notification=True)
    except ObjectDoesNotExist:
        return
    to_email = answer.email or answer.user.email
    conf = Site.objects.get(pk=instance.site.pk).config
    backend = EmailBackend(host=conf.email_host,
                           port=conf.email_port,
                           username=conf.email_username,
                           password=conf.email_password,
                           use_tls=conf.email_use_tls,
                           fail_silently=True)
    message = 'Кто-то оставил коментарий на ваш отзыв. Что бы просмотреть этот коментарий ' \
              'перейдите, пожалуйста, по ссылке http://{0}/{1}'.format(
        instance.site.domain, instance.reply_to.review.product.get_absolute_url())
    email = EmailMessage(subject='Оповещение об ответе на ваш отзыв',
                         body=message,
                         from_email=settings.DEFAULT_FROM_EMAIL,
                         to=[to_email],
                         connection=backend)
    email.send()
Beispiel #17
0
def getEmailConfiguration(user):
    from accounts.models import DatabaseUser
    from django.core.mail.backends.smtp import EmailBackend
    import database.GPGPass as GPGPass

    _row = DatabaseUser.objects.get(username = user)

    if _row.email_host:
        if _row.email_host_pass[0:23] == "§ENCRYPTED_ONECORPSEC¤=":
            _gh = GPGPass.GPGPass()
            _password = _gh.decrypt(_row.email_host_pass[23:])
        else:
            _password = _row.email_host_pass

        return EmailBackend(
            host = _row.email_host,
            port = _row.email_port,
            username = _row.email_host_user,
            password = _password,
            use_tls  = _row.email_tls,
        )

    # we return False instead of None
    # so that we flag that we have already checked and the user has no custom email host
    return False
Beispiel #18
0
    def get_smtp_connection(self):
        """Get SMTP connection.
        :return: SMTP connection
        """
        if not self.smtp_host:
            return None

        options = {
            'use_ssl': self.smtp_use_ssl
        }

        # add host / port infos
        if ':' in self.smtp_host:
            host, port = self.smtp_host.split(':')
            options['host'] = host
            options['port'] = int(port)

        else:
            options['host'] = self.smtp_host

        # add cred infos
        if self.smtp_username:
            options['username'] = self.smtp_username

        if self.smtp_password:
            options['password'] = self.smtp_password

        return EmailBackend(**options)
Beispiel #19
0
def save_user(form, client):

    list_mail = dict()

    name = form.cleaned_data['name']
    email = form.cleaned_data['email']
    user = form.cleaned_data['user'].upper()
    groups = form.cleaned_data['groups']
    user_ldap = form.cleaned_data['ldap_user'] if form.cleaned_data[
        'is_ldap'] else None

    list_mail['nome'] = name
    list_mail['user'] = user

    password = make_random_password()
    list_mail['pass'] = password

    new_user = client.create_usuario().inserir(user, password, name, email,
                                               user_ldap)

    for group in groups:
        client.create_usuario_grupo().inserir(
            new_user.get('usuario')['id'], group)

    if user_ldap is None:
        connection = EmailBackend(username=EMAIL_HOST_USER,
                                  password=EMAIL_HOST_PASSWORD)
        send_email = EmailMessage('Novo Usuário CadVlan-Globo.com',
                                  loader.render_to_string(
                                      MAIL_NEW_USER, list_mail),
                                  EMAIL_FROM, [email],
                                  connection=connection)
        send_email.content_subtype = "html"
        send_email.send()
Beispiel #20
0
def send_email_using_settings(subject, message, recipient_list):
    """Send an email using the SAEF email server settings."""
    settings = Settings.objects.get()

    # Use the email information in the SAEF settings, if specified.
    if settings.email_host_user:
        email_backend = EmailBackend(host=settings.email_host,
                                     port=settings.email_port,
                                     use_tls=settings.email_use_tls,
                                     username=settings.email_host_user,
                                     password=settings.email_host_password)

        send_mail(subject=subject,
                  message=message,
                  from_email=settings.email_host_user,
                  recipient_list=recipient_list,
                  auth_user=settings.email_host_user,
                  auth_password=settings.email_host_password,
                  connection=email_backend)
    # If not specified in the SAEF settings, use the default email information from the django settings.
    else:
        send_mail(subject=subject,
                  message=message,
                  from_email=settings.email_host_user,
                  recipient_list=recipient_list)
Beispiel #21
0
def soc_send_email(title, content, host, username, password, use_tls, use_ssl,
                   send_address, to):
    """
    :param title:  标题
    :param content:     内容
    :param host:    服务器
    :param username:    用户名
    :param password:    密码
    :param use_tls:     tls加密
    :param use_ssl:     ssl加密
    :param send_address:    发件人 一般和用户名一致
    :param to:  收件人
    :return: 
    构造一个smtp 然后发送邮件
    返回的status不为0则为成功
    """
    try:
        smtp = EmailBackend(host=host,
                            username=username,
                            password=password,
                            use_ssl=bool(int(use_ssl)),
                            use_tls=bool(int(use_tls)))
        status = send_mail(title,
                           content,
                           send_address, [to],
                           fail_silently=False,
                           auth_user=username,
                           auth_password=password,
                           connection=smtp)
        return status, 'ok'
    except Exception, e:
        return 0, str(e)
Beispiel #22
0
def test_smtp_connection(request):
    """ Tests smtp connection """
    mail_backend = EmailBackend(
        host=request.user.email_settings.smtp_host,
        port=request.user.email_settings.smtp_port,
        password=request.user.email_settings.smtp_password,
        username=request.user.email_settings.smtp_username,
        use_tls=True,
        timeout=10,
    )
    try:
        mail_backend.open()
        mail_backend.close()
        messages.success(
            request,
            _("SMTP settings are correct. Now you are using it for email sending"
              ),
        )
    except SMTPException:
        messages.warning(
            request,
            _("SMTP settings are not correct. Please provide correct credentials \
                and make sure that your smtp is running"),
        )
    return redirect("email_settings")
Beispiel #23
0
	def post(self, request, *args, **kwargs):
		form = self.get_form()

		if form.is_valid():
			email = form.cleaned_data['email']

			users = User.objects.filter(email = email)

			if users.exists():
				for user in users:
					uid = urlsafe_base64_encode(force_bytes(user.pk))
					token = default_token_generator.make_token(user)

					c = {
						'request': request,
						'title': _('Recover Password'),
						'email': user.email,
						'domain': request.build_absolute_uri(reverse("users:reset_password_confirm", kwargs = {'uidb64': uid, 'token':token})), #or your domain
						'site_name': 'Amadeus',
						'user': user,
						'protocol': 'http',
					}

					subject_template_name = 'registration/password_reset_subject.txt'
					email_template_name = 'recover_pass_email_template.html'

					subject = loader.render_to_string(subject_template_name, c)
	                # Email subject *must not* contain newlines
					subject = ''.join(subject.splitlines())
					email = loader.render_to_string(email_template_name, c)

					mailsender = MailSender.objects.latest('id')

					if mailsender.hostname == "example.com":
						send_mail(subject, email, settings.DEFAULT_FROM_EMAIL , [user.email], fail_silently=False)
					else:
						if mailsender.crypto == 3 or mailsender.crypto == 4:
							tls = True
						else:
							tls = False

						backend = EmailBackend(
									host = mailsender.hostname, port = mailsender.port, username = mailsender.username,
									password = mailsender.password, use_tls = tls
								)

						mail_msg = EmailMessage(subject = subject, body = email, to = [user.email], connection = backend)

						mail_msg.send()

				result = self.form_valid(form)
				messages.success(request, _("Soon you'll receive an email with instructions to set your new password. If you don't receive it in 24 hours, please check your spam box."))

				return result
			messages.error(request, _('No user is associated with this email address'))

		result = self.form_invalid(form)

		return result
Beispiel #24
0
def send_email(request):
    """Admin view - email.

    Not used currently.

    Args:
        request: HttpRequest object from Django.

    Returns:
        A Django TemplateResponse object that renders an html template.
    """

    if request.method == "POST":
        form = SendEmailForm(request.POST)
        if form.is_valid():
            # create html body
            visible_messages = Message.visible_objects.order_by("end_date")
            categories = (Category.objects.filter(
                messages__in=visible_messages).distinct().order_by("order"))
            config = MailConfiguration.objects.get(pk=1)
            template = get_template("email.html")
            context = Context({"categories": categories})
            text_content = strip_tags(template.render(context))
            html_content = template.render(context)
            # backend configuration
            backend = EmailBackend(
                host=config.host,
                port=config.port,
                username=config.username,
                password=config.password,
                use_tls=config.use_tls,
                fail_silently=config.fail_silently,
            )
            # create the email
            email = EmailMultiAlternatives(
                subject=form.cleaned_data["subject"],
                body=text_content,
                from_email=config.username,
                to=form.cleaned_data["to"].split(","),
                connection=backend,
            )
            # attach html content
            email.attach_alternative(html_content, "text/html")
            # send
            try:
                email.send()
                return JsonResponse({"success": True})
            except Exception as e:
                return JsonResponse({
                    "success": False,
                    "errors": {
                        "mail": "failed to send"
                    }
                })
        return JsonResponse({
            "success": False,
            "errors": dict(form.errors.items())
        })
Beispiel #25
0
 def smtp_backend(self):
     # raises an error if it fails to send
     return EmailBackend(host=self.host,
                         port=self.port,
                         username=self.username,
                         password=self.password,
                         use_tls=self.is_tls,
                         use_ssl=self.is_ssl,
                         fail_silently=False)
Beispiel #26
0
def get_email_backend():
    from constance import config
    return EmailBackend(
        host=config.EMAIL_HOST,
        port=config.EMAIL_PORT,
        username=config.EMAIL_HOST_USER,
        password=config.EMAIL_HOST_PASSWORD,
        use_tls=config.EMAIL_USE_TLS
    )
Beispiel #27
0
def checkout(request): # Create order function
    if request.session.get('skipass', {}):
        ses = request.session.get('skipass', {})
        request.session['skipass'] = ses
        summ = request.session.get('summ')
        if request.method == 'POST' and request.is_ajax(): # Check method POST and AJAX-request
            form = Checkout(request.POST) # create form Checkout
            ajax = {} # create dict from respose ajax dump
            if form.is_valid():
                # Filling form-data  to data-dict. Data dict is data for send mail.
                req = form.cleaned_data['req']
                if req is None:
                    req = False
                town = form.cleaned_data['town']
                phone = form.cleaned_data['phone']
                email = form.cleaned_data['email']
                name = form.cleaned_data['name']
                sename = form.cleaned_data['sename']
                data = {'name':name,
                        'sename':sename,
                        'email':email,
                        'phone':phone,
                        'town':town,
                        'req':req,
                        'ses':ses,
                        'summ':summ}
                t = get_template('email.html') # template from email
                html = t.render(data) # Fillind template data-info
                config = SMTP.objects.get(pk=1) # recipe smtp-config from DB
                backend = EmailBackend(host=config.host, port=config.port, use_ssl=config.ssl, use_tls=config.tls, username=config.user, password=config.password) # Set backend email
                mail = EmailMultiAlternatives(u'Оформление заказа от {0}'.format(form.cleaned_data['name']), 'text', 'BUKSKIPASS.PP.UA | Оформление <*****@*****.**>', [form.cleaned_data['email'], '{0}'.format(config.user)], connection=backend)
                mail.attach_alternative(html, "text/html") # Using alternative mail for sending email template
                # Try to send mail
                try:
                    mail.send()
                # If error
                except Exception:
                    message = u'Во время отправки возникла проблема. Попробуйте заказать позже или свяжитесь с нашим менеджером.'
                    ajax['message'] = message
                    return HttpResponse(json.dumps(ajax), content_type='application/json')
                else:
                    del request.session['skipass'] # Clear session
                    del request.session['summ'] # Clear session
                    request.session['success'] = 1 # Create session from redirect to "success link"
                    ajax['message'] = True
                    ajax['window'] = '/success/'
                    return HttpResponse(json.dumps(ajax), content_type='application/json')


        # If request method is GET
        else:
            form = Checkout() # Create form Checkout
        return render(request, 'checkout.html', {'form':form})
    # If session data is null - redirect to home page
    else:
        return redirect('/')
Beispiel #28
0
 def __init__(self):
     settingService = SettingService()
     mail_info = settingService.get_mail_info()
     self.from_email = mail_info.from_email
     if mail_info.use_tls:
         use_tls = True
     else:
         use_tls = False
     self.backend = EmailBackend(host=mail_info.host, port=mail_info.port, username=mail_info.username, \
             password=mail_info.password, use_tls=use_tls, timeout=30)
Beispiel #29
0
def send_mail(subject, body):

    try:
        mailob = AlertMailModel.objects.first()

        con = mail.get_connection(host=mailob.host_smtpaddress,
                                  port=mailob.port,
                                  fail_silently=False)
        try:
            con.open()
            print('Django connected to the SMTP server')

        except Exception as e:
            print(e.errno, e.strerror)

        ferob = Fernet(settings.FERNET_SECRET_KEY)

        # host = 'smtp.gmail.com'
        # host_user = '******'
        # host_pass = '******'
        # host_port = 587

        host = mailob.host_smtpaddress
        host_user = mailob.host_mail
        host_pass = ferob.decrypt(mailob.mail_host_password.encode()).decode()
        host_port = mailob.port
        tls = mailob.use_tls

        mail_obj = EmailBackend(host=host,
                                port=host_port,
                                password=host_pass,
                                username=host_user,
                                use_tls=True,
                                timeout=10)

        msg = mail.EmailMultiAlternatives(
            subject=subject,
            body=strip_tags(body),
            from_email=host_user,
            to=[mailob.receipient_mail],
            connection=con,
        )
        msg.attach_alternative(body, "text/html")
        mail_obj.send_messages([msg])
        print('Message has been sent.')

        mail_obj.close()
        print('SMTP server closed')
        return True

    except Exception as _error:
        print(_error)
        print('Error in sending mail >> {} {}'.format(
            str(_error.smtp_code), _error.smtp_code.decode()))
        return False
Beispiel #30
0
def email_backend():
    from common.models import EmailSetting
    config = EmailSetting.objects.first()

    backend = EmailBackend(host=config.email_host,
                           port=config.email_port,
                           username=config.email_host_user,
                           password=config.email_host_password,
                           use_tls=config.email_use_tls,
                           fail_silently=True)
    return backend