Esempio n. 1
0
    def run(self, obj):
        from notificacao.models import Mensagem
        obj_msg = Mensagem.objects.get(pk=obj)

        if not obj_msg.enviado:
            lista_destinatarios = obj_msg.get_lista_completa_destinatarios()
            assunto = obj_msg.assunto
            from_email = settings.DEFAULT_FROM_EMAIL
            text_content = _(u'Essa é uma mensagem importante.')
            html_content = u'%(header)s \
                             %(texto)s \
                             %(footer)s'\
                             % {'header': TextosEmail.headerEmailInterno,
                                'footer': TextosEmail.footerEmailInterno,
                                'texto': obj_msg.get_texto_formatado(),
                                }

            msg = EmailMultiAlternatives(assunto, text_content, from_email, bcc=lista_destinatarios)
            msg.attach_alternative(html_content, "text/html")

            # insere anexos caso haja algum
            for anexo in obj_msg.anexo_set.all():
                msg.attach_file(anexo.arquivo_anexo.path)

            try:
                msg.send()
                obj_msg.enviado = True
                obj_msg.endereco_email_enviado = ', '.join(msg.bcc + msg.cc + msg.to)
                obj_msg.save()
            except smtplib.SMTPException as e:
                logger.error('Exceção em fila de envios de email: {0}'.format(e))
Esempio n. 2
0
def enviar_correo(correo, cuerpo_mensaje, ruta_archivo_adjunto, subject, from_email, attach_file):
    """
	Define el envio de correo electronico.
	
	Args:
	    correo: El correo electrónico destino.
		cuerpo_mensaje: El cuerpo del correo.
		ruta_archivo_adjunto: La ruta de un archivo a adjuntar.
		subject: El título del correo.
		from_email: El correo electrónico que envía.
		attach_file: El archivo a adjuntar.
        
    Returns:
        La excepción en caso de que se genere.
	"""
	
    valor = 0
    to = correo    
    text_content = 'This is an important message.'            
    html_content = '<br>%s' % (cuerpo_mensaje)    
    
    try:
        msg = EmailMultiAlternatives(subject, text_content, from_email, to)
        msg.attach_alternative(html_content, "text/html")
        
        if attach_file:            
            msg.attach_file(ruta_archivo_adjunto)
            
        msg.send()
    except Exception, e:
        valor = e
Esempio n. 3
0
    def email_submission(self, form_data, request, referrer):
        mail_to = re.compile('\s*[,;]+\s*').split(self.form_definition.email_to)
        mail_from = self.form_definition.email_from or None
        mail_subject = self.form_definition.email_subject or \
            'Form Submission - %s' % self.form_definition.name
        context = {
            'form': self.form_definition,
            'referrer': referrer,
            'title': mail_subject,
            'form_data': form_data,
            'request': request,
            'recipients': mail_to,
        }

        message = render_to_string('djangocms_forms/email_template/email.txt', context)
        message_html = render_to_string('djangocms_forms/email_template/email.html', context)

        email = EmailMultiAlternatives(mail_subject, message, mail_from, mail_to)
        email.attach_alternative(message_html, 'text/html')

        if self.files and self.form_definition.email_uploaded_files:
            for file_path in self.files:
                email.attach_file(file_path)

        email.send(fail_silently=False)
Esempio n. 4
0
    def handle(self, *args, **options):
        template = loader.get_template("wedding/invitation_email.html")

        for user in User.objects.filter(id__gte=331):
            print user
            profile = user.userprofile_set.all()[0]

            if profile.sent_invitation or user.email.endswith('email.com'):
                 print "Not sending to" + user.username + " already sent or bad email address"
                 continue
            html = template.render({'user_id': user.id, 'host_url': settings.HOST_URL, 'user_email': user.email})

            send_to = [user.email]

            if profile.alternate_email:
                send_to.append(profile.alternate_email)
            email = EmailMultiAlternatives(
                subject="Dave & Courtney's Wedding - Invitation",
                body=html,
                from_email=settings.EMAIL_FROM,
                to=send_to,
                reply_to=settings.EMAIL_REPLY_TO)
            email.attach_file(os.path.join(settings.BASE_DIR, "wedding", "static", "venue_directions.pdf"))
            email.attach_alternative(html, 'text/html')
            email.send()

            profile.sent_invitation = True
            profile.save()

            time.sleep(120)
Esempio n. 5
0
def _send_mail(subscriber,
               template_name,
               context,
               subject,
               attachmentfile=None):
    domain = Site.objects.get_current().domain
    context.update({
        "site_name": Site.objects.get_current().name,
        "site_domain": domain,
        "subscriber": subscriber
    })
    tmpl = template.loader.get_template(template_name + ".txt")
    msg = tmpl.render(context)
    try:
        tmpl = template.loader.get_template(template_name + ".html")
        htmlmsg = tmpl.render(context)
    except template.exceptions.TemplateDoesNotExist:
        htmlmsg = None
    email = EmailMultiAlternatives(subject, msg, subs_settings.NEWS_FROM,
                                   [subscriber.email])
    if htmlmsg:
        email.attach_alternative(htmlmsg, "text/html")
    if attachmentfile:
        email.attach_file(attachmentfile)
    try:
        email.send()
    except SMTPException:
        return False

    return True  # send_mail
Esempio n. 6
0
 def send_mail(self):
     template_txt = select_template([
         'leprikon/{}-mail/{}.txt'.format(self.pdf_export, self.subject.subject_type.slug),
         'leprikon/{}-mail/{}.txt'.format(self.pdf_export, self.subject.subject_type.subject_type),
         'leprikon/{}-mail/subject.txt'.format(self.pdf_export),
     ])
     template_html = select_template([
         'leprikon/{}-mail/{}.html'.format(self.pdf_export, self.subject.subject_type.slug),
         'leprikon/{}-mail/{}.html'.format(self.pdf_export, self.subject.subject_type.subject_type),
         'leprikon/{}-mail/subject.html'.format(self.pdf_export),
     ])
     context = {
         'object': self,
         'site': LeprikonSite.objects.get_current(),
     }
     content_txt = template_txt.render(context)
     content_html = template_html.render(context)
     msg = EmailMultiAlternatives(
         subject = self.mail_subject,
         body        = content_txt,
         from_email  = settings.SERVER_EMAIL,
         to          = self.all_recipients,
         headers     = {'X-Mailer': 'Leprikon (http://leprikon.cz/)'},
     )
     msg.attach_alternative(content_html, 'text/html')
     msg.attach(self.pdf_filename, self.get_pdf(), 'application/pdf')
     for attachment in self.all_attachments:
         msg.attach_file(attachment.file.file.path)
     msg.send()
Esempio n. 7
0
def send_email(request):
    subject = u'这是邮件标题'
    message = u'<h1>这是邮件内容</h1>'
    text_content = 'This is an important message.'

    html_content = '<p>This is an <strong>important</strong> message.</p>'
    from_email = u'*****@*****.**'  # 邮件接受者
    if subject and message and from_email:
        try:
            send_mail(subject,
                      message,
                      from_email, ['*****@*****.**'],
                      fail_silently=False)
            msg = EmailMultiAlternatives(subject, text_content, from_email,
                                         ['*****@*****.**'])
            msg.attach_alternative(html_content, 'text/html')
            msg.attach_file(U'D:\迅雷下载\celery-master.zip')
            msg.send()
        except BadHeaderError:
            return HttpResponse('Invalid header found.')
        return HttpResponse(U'<h3>发送成功</3>')
    else:
        # In reality we'd use a form class
        # to get proper validation errors.
        return HttpResponse('Make sure all fields are entered and valid.')
Esempio n. 8
0
def send_email(subject: str, content: str, domain: str, to_email: list):
    subject = subject
    content = content
    sender = email_config.values()[0]["email"]
    # to_email.append(settings.EMAIL_HOST_USER)
    receiver = to_email

    msg = EmailMultiAlternatives(subject, content, sender, receiver)
    msg.content_subtype = "html"

    # 证书位置
    ssl_key_file = os.path.join(CERT_DIR, domain, domain + ".key")
    ssl_cert_file = os.path.join(CERT_DIR, domain, "fullchain.cer")

    # 添加附件
    if os.path.isfile(ssl_key_file) and os.path.isfile(ssl_cert_file):
        # 复制一份证书链文件,加上域名作为标识
        new_ssl_cert_file = os.path.join(CERT_DIR, domain,
                                         domain + ".fullchain.cer")
        shutil.copy(ssl_cert_file, new_ssl_cert_file)

        msg.attach_file(ssl_key_file)
        msg.attach_file(new_ssl_cert_file)

    msg.send()

    log.info("Email was successfully sent to {}".format(receiver))
Esempio n. 9
0
def send_mass_html_mails(from_email, subject, templateName, data, receivers,
                         text_content='', files=None, path='email_templates/'):
    """
    Envía eficientemente varios correos con un template en html, data es un 
    diccionario y files una lista de archivos adjuntos
    """
    ############### hack para que envie el mail con un nombre ############
    try:
        from_email = "%s <%s>" % (settings.SENDER_NAME, from_email)
    except AttributeError:
        pass
    ######################################################################
    context = Context(data)
    html_content = mark_safe(render_to_string(
        '%s%s' % (path, templateName), context))
    li = []
    for to_ in receivers:
        msg = EmailMultiAlternatives(subject, text_content, from_email, [to_])
        msg.attach_alternative(html_content, "text/html")
        if files:
            for afile in files:
                msg.attach_file(afile)
        else:
            pass
        li.append(msg)

    if receivers:
        connection = mail.get_connection()
        connection.send_messages(li)
Esempio n. 10
0
def email_client(self, subject, text):
    # Send the client an email
    html_content = render_to_string(
        "../templates/baseTemplates/emailToUser.html", {
            'salutation': self.salutation,
            'last_name': self.last_name,
            'text_body': text
        })
    msg = EmailMultiAlternatives(
        subject,
        'Dear ' + self.salutation + ' ' + self.last_name + '/n' + text,
        '*****@*****.**',
        [self.email],
    )
    msg.attach_alternative(html_content, "text/html")
    msg.attach_file('static/Images/asranetLogo.jpg')
    msg.mixed_subtype = 'related'

    f = 'asranetLogo.jpg'
    fp = open(os.path.join(os.path.dirname(__file__), f), 'rb')
    msg_img = MIMEImage(fp.read())
    fp.close()
    msg_img.add_header('Content-ID', '<{}>'.format(f))
    msg.attach(msg_img)
    msg.send()
Esempio n. 11
0
def send_message(subject, html_content, text_content, to, from_email=None, reply_to=None, connection=None, attachments=None, usebcc=None, email_name=None):
    bcc=None

    if usebcc:
        bcc=to
        to=None

    headers = {"X-SMTPAPI": simplejson.dumps({'unique_args':
                   {'email_name': email_name}})
                }


    if reply_to and len(reply_to) > 0:
        headers.update({'Reply-To': reply_to})


    msg = EmailMultiAlternatives(subject=subject, body=text_content, from_email=from_email, to=to, bcc=bcc, connection=connection, headers=headers)
    msg.attach_alternative(html_content, "text/html")

    for attachment in attachments:
        if attachment and os.path.exists(attachment.path):
            msg.attach_file(attachment.path)

    msg.send()
    import django.core.mail.message
Esempio n. 12
0
    def _send(self):
        if not self.sent:
            self.last_attempt = timezone.now()

            subject, from_email = self.subject, '{0} <{1}>'.format(self.from_name, self.from_address)
            text_content = self.content
            
            msg = EmailMultiAlternatives(subject, text_content, from_email)
            
            if self.reply_to:
                msg.extra_headers.update({"reply-to": self.reply_to})

            if self.html_content:
                html_content = self.html_content
                msg.attach_alternative(html_content, "text/html")

            msg.to = [email.strip() for email in self.to_address.split(',') if email.strip()]
            msg.bcc = [email.strip() for email in self.bcc_address.split(',') if email.strip()]

            # Add any additional attachments
            for attachment in self.attachment_set.all():
                msg.attach_file(os.path.join(settings.MEDIA_ROOT, attachment.file_attachment.name))
            try:
                msg.send()
                self.sent = True
            except Exception as e:
                self.do_not_send = True
                logger.error('Mail Queue Exception: {0}'.format(e))
            self.save()
Esempio n. 13
0
def send_html_mail(subject, message, message_html, from_email, recipient_list,
                   priority="medium", fail_silently=False, auth_user=None,
                   auth_password=None, attach_files=[]):
    """
    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")

    for f in attach_files:
        if isinstance(f, (str, unicode)):
            email.attach_file(f)
        elif isinstance(f, (tuple, list)):
            n, fi, mime = f + (None,) * (3 - len(f))
            email.attach(n, fi, mime)

    msg.email = email
    msg.save()
    return 1
Esempio n. 14
0
def send_result_email(send_subject,
                      send_to,
                      send_cc,
                      send_text_content=None,
                      send_html_content=None,
                      send_file_path=[],
                      from_email=EMAIL_FROM):
    """
    :param send_subject: str
    :param send_to: list
    :param send_cc: list
    :param send_text_content: str
    :param send_html_content: html
    :param from_email: str
    :param send_file_path: list
    :return: bool
    """
    try:
        msg = EmailMultiAlternatives(subject=send_subject,
                                     from_email=from_email,
                                     to=send_to,
                                     cc=send_cc)
        if send_text_content:
            msg.attach_alternative(send_text_content, 'text/plain')
        if send_html_content:
            msg.attach_alternative(send_html_content, 'text/html')
        if send_file_path:
            for file_path in send_file_path:
                msg.attach_file(file_path)
        send_status = msg.send()
        return send_status
    except Exception as e:
        print(traceback.print_exc())
Esempio n. 15
0
def enviar_correo(correo, cuerpo_mensaje, ruta_archivo_adjunto, subject,
                  from_email, attach_file):
    """
	Define el envio de correo electronico.
	
	Args:
	    correo: El correo electrónico destino.
		cuerpo_mensaje: El cuerpo del correo.
		ruta_archivo_adjunto: La ruta de un archivo a adjuntar.
		subject: El título del correo.
		from_email: El correo electrónico que envía.
		attach_file: El archivo a adjuntar.
        
    Returns:
        La excepción en caso de que se genere.
	"""

    valor = 0
    to = correo
    text_content = 'This is an important message.'
    html_content = '<br>%s' % (cuerpo_mensaje)

    try:
        msg = EmailMultiAlternatives(subject, text_content, from_email, to)
        msg.attach_alternative(html_content, "text/html")

        if attach_file:
            msg.attach_file(ruta_archivo_adjunto)

        msg.send()
    except Exception, e:
        valor = e
Esempio n. 16
0
def send_via_email(request, content_type_id, object_id):
    model_class = ContentType.objects.get(pk=content_type_id).model_class()
    if model_class.__name__ == "Order":
        instance = model_class.objects.get(pk=object_id)

        path = instance.get_pdf_order_path()
        email = request.GET['email']

        cur_context = {}
        cur_context['order'] = instance.get_list_item_info(request)
        if instance.shopping_place:
            cur_context['company'] = instance.shopping_place.shop.company
        message_html_t = get_template('lugati_admin/lugati_version_1_0/orders/mail_template.html')
        message_html = message_html_t.render(Context(cur_context))

        # return render(request, 'lugati_admin/lugati_version_1_0/orders/ng_order_details_template.html', resp_data)

        try:
            msg_text = 'Hello, here is the receipt'
            emails = [email]
            msg = EmailMultiAlternatives('Order ' + str(instance.id) + ' receipt', msg_text, settings.DEFAULT_FROM_EMAIL, emails)
            msg.attach_alternative(message_html, "text/html")
            msg.attach_file(path)

            msg.send()
        except Exception, e:
            # pass
            logger.info('send via email err: ' + str(e))

        return HttpResponse(json.dumps({}))
Esempio n. 17
0
    def handle(self, *args, **options):
        db_name = settings.DJANGO_SETTINGS_DATABASE_NAME
        db_user = settings.DJANGO_SETTINGS_DATABASE_USER
        backup_file = NamedTemporaryFile(prefix="{}-db.bak.".format(db_name), suffix='.gz')

        # pg_restore  -Fc -U _0_prd_example -C -c --no-owner --dbname=_0_prd_example db.bak

        result = call("pg_dump -Fc -U {} {} | gzip".format(db_user, db_name), stdout=backup_file, shell=True)
        if result == 0:
            migrations_files = NamedTemporaryFile(prefix="{}-mig.bak.".format(db_name), suffix='.gz')
            repanier_path = os.path.join(os.path.dirname(settings.PROJECT_DIR), "repanier")
            result = call("cd {} && tar -zcf {} migrations{}*.py".format(repanier_path, migrations_files.name, os.sep),
                          stdout=migrations_files, shell=True)

            if result == 0:
                email = EmailMultiAlternatives(
                    subject="Backup {}".format(db_name),
                    body="Backup of the DB : {}".format(db_name),
                    to=[v for k, v in settings.ADMINS]
                )
                email.attach_file(os.path.abspath(backup_file.name),
                                  'application/zip')
                email.attach_file(os.path.abspath(migrations_files.name),
                                  'application/zip')
                email.send()
                for customer in Customer.objects.filter(
                        represent_this_buyinggroup=False,
                        subscribe_to_email=False,
                        is_group=False,
                        is_anonymized=False,
                ).order_by('?'):
                    if customer.get_purchase_counter() <= 0 and customer.get_participation_counter() <= 0 and customer.get_admin_balance().amount == DECIMAL_ZERO:
                        customer.is_active = False
                        customer.anonymize()
Esempio n. 18
0
def createmail(subject, htmltemplate='',texttemplate='', context={}, attachments=[]):
    """
    if you want to use Django template system:
       use `context` as template context (dict)
       and define `htmltemplate` and optionally `texttemplate` variables.
    """

    htmltemplate, images = src2cid(htmltemplate)

    html = Template(htmltemplate).render(Context(context))
    text = Template(texttemplate).render(Context(context))
    subject = Template(subject).render(Context(context))

    # creating mail object
    msg = EmailMultiAlternatives(subject='', body=text, from_email=None, to=None)
    msg.attach_alternative(html, "text/html")

    for img_path, img_cid in images:
        try:
            fp = open(os.path.join(settings.MEDIA_ROOT,img_path, 'rb'))
            cnt = fp.read()
            fp.close()
            msg.attach_image(cnt, img_cid)
        except:
            pass
    for attachment in attachments:
        msg.attach_file(attachment)
    return msg
Esempio n. 19
0
    def send_email(self):
        if self._reply:
            email_headers = {'Reply-To': self._reply}
        else:
            email_headers = {}

        content = self._content
        message = content['message']
        content.pop('message')
        message = message.format_map(content)

        mail = EmailMultiAlternatives(subject=self._subject,
                                      body=message,
                                      from_email=self._sender,
                                      to=self._recipients,
                                      headers=email_headers)

        if self._template:
            mail_template = get_template(self._template)
            mail_template = mail_template.render(self._content)
            mail.attach_alternative(mail_template, 'text/html')

        if self._files:
            for file in self._files:
                if isinstance(file, MIMEImage):
                    mail.attach(file)
                elif isinstance(file, str):
                    mail.attach_file(file)
        mail.send()
Esempio n. 20
0
def enviar_correo(asunto, template, recipients, data, attachment_file=None):
    image_path = os.path.join(settings.BASE_DIR,
                              'assets/images/afini_logo.png')
    image_name = 'afini_logo.png'

    context = {'image_name': image_name, 'data': data}
    html_content = render_to_string(template, context)
    reply_to = ['*****@*****.**']

    message = EmailMultiAlternatives(asunto,
                                     html_content,
                                     os.getenv('MAIL_USER'),
                                     to=recipients,
                                     reply_to=reply_to)

    if attachment_file is not None:
        message.attach_file(os.path.join(settings.BASE_DIR, attachment_file))

    message.attach_alternatives = (html_content, "text/html")
    message.content_subtype = "html"
    message.mixed_subtype = 'related'

    with open(image_path, mode='rb') as f:
        image = MIMEImage(f.read())
        message.attach(image)
        image.add_header('Content-ID', f"<{image_name}>")

    message.send()
Esempio n. 21
0
def send_templated_email(
    subject,
    email_template_name,
    email_context,
    recipients,
    bcc=None,
    fail_silently=True,
    files=None,
    request=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.

    email_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 file paths to be attached, or it can be left blank.
        eg ('/tmp/file1.txt', '/tmp/image.png')

    """
    # We can only send mail from the DEFAULT_FROM_EMAIL now
    sender = settings.DEFAULT_FROM_EMAIL
    template = loader.get_template(email_template_name)
    text_part = strip_tags(template.render(email_context, request=request))
    html_part = template.render(email_context, request=request)
    subject = f"[{Site.objects.get_current().domain.lower()}] {subject}"

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

    msg = EmailMultiAlternatives(
        subject, text_part, sender, recipients, bcc=bcc
    )
    msg.attach_alternative(html_part, "text/html")
    if files:
        if type(files) != list:
            files = [files]
        for file in files:
            msg.attach_file(file)
    return msg.send(fail_silently)
Esempio n. 22
0
def user_win(auction_id):
    from auction.models import Auction, Constant
    translation.activate('uk')

    auction = Auction.objects.get(id=auction_id)

    templates = {
        'banks things': 'auction/email/user_win_bank.html',
        'company things': 'auction/email/user_win.html'
    }
    text = loader.render_to_string(templates[auction.lot.bidding_type], {'auction': auction})

    mail = EmailMultiAlternatives(
        _('User win'), text,
        from_email=Constant.get_value('no_reply'),
        to=[auction.winner.email]
    )

    attach_text = loader.render_to_string(
        'auction/email/protocol_.html', {'auction': auction}
    )

    res = NamedTemporaryFile(delete=False, suffix='.html')
    res.write(attach_text.encode('utf8'))
    res.close()

    mail.attach_file(res.name)
    mail.send()

    os.unlink(res.name)
Esempio n. 23
0
    def _send(self):
        if not self.sent:
            self.last_attempt = timezone.now()

            subject, from_email = self.subject, self.from_address
            text_content = self.content
            msg = EmailMultiAlternatives(subject, text_content, from_email)
            if self.html_content:
                html_content = self.html_content
                msg.attach_alternative(html_content, "text/html")

            msg.to = [
                email.strip() for email in self.to_address.split(',')
                if email.strip()
            ]
            msg.bcc = [
                email.strip() for email in self.bcc_address.split(',')
                if email.strip()
            ]

            # Add any additional attachments
            for attachment in self.attachment_set.all():
                msg.attach_file(
                    os.path.join(settings.MEDIA_ROOT,
                                 attachment.file_attachment.name))
            try:
                msg.send()
                self.sent = True
            except Exception as e:
                self.do_not_send = True
                logger.error('Mail Queue Exception: {0}'.format(e))
            self.save()
Esempio n. 24
0
def send_bulk_mail(subject, email_body, recipients, attachments):
    try:
        text_msg = ""
        msg = EmailMultiAlternatives(subject, text_msg, settings.SENDER_EMAIL,
                                    recipients
                                    )
        msg.attach_alternative(email_body, "text/html")
        if attachments:
            for file in attachments:
                path = default_storage.save('attachments/'+file.name,
                                            ContentFile(file.read())
                                            )
                msg.attach_file(os.sep.join((settings.MEDIA_ROOT, path)),
                                mimetype="text/html"
                                )
                default_storage.delete(path)
        msg.send()

        message = "Email Sent Successfully"

    except Exception as exc_msg:
        message = """Error: {0}. Please check email address.\
                If email address is correct then
                Please contact {1}.""".format(exc_msg, settings.REPLY_EMAIL)

    return message
Esempio n. 25
0
def auth_view(request):
    if request.method == 'POST':
        username = request.POST['Username']
        password = request.POST['Password']
        print(username)
        student = Register.objects.filter(AppId=username,
                                          Password=password).exists()
        print(student)
        if student is not False:
            print(student)
            AppId = username
            res = Contact.objects.filter(AppId=AppId).first()
            subject, from_email, to = 'Introduction about the examination', settings.EMAIL_HOST_USER, res.EmailId
            text_content = 'Read the instructions carefully'
            msg = EmailMultiAlternatives(subject, text_content, from_email,
                                         [to])
            msg.attach_file(
                'C:/Users/Manish Prajapati/Desktop/SDP_HETVI/firsttry/media/Instructions.pdf'
            )
            msg.send()
            request.session['AppId'] = AppId
            # return redirect('/first/certificate/')
            return render(request, 'welcome.html', {"AppId": AppId})
        else:
            Usernm = "HetviPrajapati"
            Pwd = "Hetvi123@#"
            #superusers = User.objects.filter(is_superuser=True)
            #superusers_pwds = User.objects.filter(is_superuser=True).values_list('password')
            #print(superusers_pwds)
            #print(superusers)
            print(username)
            if username == Usernm and Pwd == password:
                questions = Question.objects.all()
                return render(request, "show.html", {'questions': questions})
    return render(request, 'login.html')
Esempio n. 26
0
def send_mail_contest(secret, email, reg_number, message_template,
                      name_contest, alias):
    list_emails = []
    list_emails.append(email)
    connection = get_connection(host=settings.EMAIL_CONTEST['host'],
                                port=settings.EMAIL_CONTEST['port'],
                                username=secret['user'],
                                password=secret['password'],
                                use_tls=settings.EMAIL_CONTEST['use_tls'])
    subject, from_email = name_contest, settings.EMAIL_CONTEST['from_contest']
    message = render_to_string(message_template, {'reg_number': reg_number})
    msg = EmailMultiAlternatives(subject,
                                 message,
                                 from_email,
                                 list_emails,
                                 connection=connection)
    msg.content_subtype = "html"
    try:
        if alias != 'teacher':
            attached_file = os.path.join(settings.MEDIA_ROOT, 'pdf', alias,
                                         f'{reg_number}.pdf')
        else:
            attached_file = os.path.join(settings.MEDIA_ROOT, 'zip',
                                         f'{reg_number}.zip')

        msg.attach_file(attached_file, mimetype='text/html')
        msg.send()
    except:
        msg.send()
    connection.close()
Esempio n. 27
0
    def send(self):
        #Create the weekmail content and send it.
        html_parser = html.parser.HTMLParser()
        content = {'weekmail': html_parser.unescape(self)}
        mail_content_txt = render_to_string('communication/weekmail.txt',
                                            content)
        mail_content_html = render_to_string('communication/weekmail.html',
                                            content)

        #You can change the weekmail recipients here.
        recipients = settings.WEEKMAIL_RECIPIENTS
        sender = settings.DEFAULT_FROM_EMAIL
        try:
            mail = EmailMultiAlternatives()
            mail.subject = _('[Weekmail] %s') % (self.subject)
            mail.body = mail_content_txt
            mail.from_email = sender
            mail.to = recipients
            mail.cc = [sender,]
            mail.attach_alternative(mail_content_html, "text/html")
            for attachment in self.attached.all():
                mail.attach_file(attachment.file.path)
            mail.send()
            self.sent_date = timezone.now()
            self.save()
            return True
        except SMTPException:
            return False
        return False
Esempio n. 28
0
    def handle(self, *args, **options):
        db_name = settings.DJANGO_SETTINGS_DATABASE_NAME
        db_user = settings.DJANGO_SETTINGS_DATABASE_USER
        backup_file = NamedTemporaryFile(prefix="{}-db.bak.".format(db_name), suffix='.gz')

        # pg_restore  -Fc -U _0_prd_example -C -c --no-owner --dbname=_0_prd_example db.bak

        result = call("pg_dump -Fc -U {} {} | gzip".format(db_user, db_name), stdout=backup_file, shell=True)
        if result == 0:
            migrations_files = NamedTemporaryFile(prefix="{}-mig.bak.".format(db_name), suffix='.gz')
            repanier_path = os.path.join(os.path.dirname(settings.PROJECT_DIR), "repanier")
            result = call("cd {} && tar -zcf {} migrations{}*.py".format(repanier_path, migrations_files.name, os.sep),
                          stdout=migrations_files, shell=True)

            if result == 0:
                email = EmailMultiAlternatives(
                    subject="Backup {}".format(db_name),
                    body="Backup of the DB : {}".format(db_name),
                    to=[v for k, v in settings.ADMINS]
                )
                email.attach_file(os.path.abspath(backup_file.name),
                                  'application/zip')
                email.attach_file(os.path.abspath(migrations_files.name),
                                  'application/zip')
                email.send()
                for customer in Customer.objects.filter(
                        represent_this_buyinggroup=False,
                        subscribe_to_email=False,
                        is_group=False,
                        is_anonymized=False,
                ).order_by('?'):
                    if customer.get_purchase() <= 0 and customer.get_participation() <= 0 and customer.get_admin_balance().amount == DECIMAL_ZERO:
                        customer.is_active = False
                        customer.anonymize()
Esempio n. 29
0
def generate(request):  #Generate the key file for the user.
    if (request.method == 'POST'):
        id = request.POST['fileid']
        try:
            info = file_info.objects.get(file_id=id)
        except ObjectDoesNotExist:
            info = None
        if info is not None:
            fkey = info.file_key
            keygenerate(fkey, id)
            mail = request.user.email
            name = request.user.first_name
            attach = MEDIA_ROOT + '/keys/' + id + '.png'
            mail_subject = 'Regenerate Key'
            html_message = render_to_string('key_email.html', {
                'name': name,
                'fileid': id,
                'create': 0
            })
            msg = EmailMultiAlternatives(mail_subject,
                                         html_message,
                                         '*****@*****.**', [mail],
                                         reply_to=['*****@*****.**'],
                                         headers={'Message-ID': 'Upload'})
            msg.attach_alternative(html_message, "text/html")
            msg.attach_file(attach)
            msg.send(fail_silently=False)
            os.remove(attach)
            messages.success(request, "Key send to the email")
            return redirect('view')
Esempio n. 30
0
def confirmation_view(request, product_id, saler_id):
    product = Product.objects.get(id=product_id)
    category_list = Category.objects.all()

    """ Information necesary for email processing """
    user = request.user
    saler = MyUser.objects.get(id=saler_id)
    total = product.shipping_cost + product.price
    d = Context({'user': user, 'product': product, 'saler': saler, 'total': total})

    email = request.user.email
    html = get_template('email/confirmation.html')
    html_content = html.render(d)

    msg = EmailMultiAlternatives('subject', html_content, EMAIL_HOST_USER, [email])
    msg.attach_alternative(html_content, 'text/html')
    msg.attach_file(BASE_DIR + product.image.url)
    msg.send()

    """ Reduce by one the quantity of items in database"""
    if id:
        a = Product.objects.get(id=product_id)
        count = a.quantity
        count -= 1
        a.quantity = count
        a.save()
        """ Delete any item from database is quantity equals zero """
        if count == 0:
            a.delete()
    return render_to_response('web_shop/confirmation.html',
                              {'title': 'Congratulations', 'product': product, 'category_list': category_list, 'user':user},
                                context_instance=RequestContext(request))
Esempio n. 31
0
def profile_email(request):
    if settings.IS_PRODUCTION:
        avatar_path = '{MEDIA_ROOT}/{PROFILE_IMAGE}'.format(
            MEDIA_ROOT=settings.MEDIA_ROOT,
            PROFILE_IMAGE=request.user.profile.avatar
        )
    else:
        avatar_path = '{BASE_DIR}/{MEDIA_ROOT}/{PROFILE_IMAGE}'.format(
            BASE_DIR=settings.BASE_DIR,
            MEDIA_ROOT=settings.MEDIA_ROOT,
            PROFILE_IMAGE=request.user.profile.avatar
        )

    email_template = get_template('users/email.html')
    email_content = email_template.render({
        'first_name': request.user.first_name,
        'last_name': request.user.last_name,
    })

    mail = EmailMultiAlternatives(
        'Your profile data request',
        email_content,
        settings.EMAIL_HOST_USER,
        [request.user.email]
    )
    mail.content_subtype = 'html'
    mail.attach_file(avatar_path)
    mail.send()

    return HttpResponseRedirect(reverse('users:profile'))
Esempio n. 32
0
def cubane_send_mail_no_html(to, subject, text, attachments=None):
    """
    Send an email to the given recepient with given subject line and text
    content.
    """
    if 'cubane.cms' not in settings.INSTALLED_APPS:
        raise ValueError('cubane.cms required for sending cms page emails.')
    from cubane.cms.views import get_cms
    cms = get_cms()

    # construct email
    msg = EmailMultiAlternatives(subject,
                                 text,
                                 cms.settings.enquiry_reply, [to],
                                 headers={
                                     'Reply-To': cms.settings.enquiry_reply,
                                     'From': cms.settings.enquiry_from
                                 })

    # attachement(s)
    if attachments:
        if not isinstance(attachments, list):
            attachments = [attachments]
        for attachment in attachments:
            msg.attach_file(attachment)

    # send it off
    msg.send()
Esempio n. 33
0
def email_clubs(EMAIL, ARPATH):
    clubs = Club.objects.all()
    for club in clubs:
        print "Processing: %s" % club.name
        # meals members had at other clubs without reciprocating
        mealsout = Exchange.objects.filter(meal_2=None).filter(meal_1__guest__club=club)
        # guests hosted at this club without reciprocating
        mealsin = Exchange.objects.filter(meal_2=None).filter(meal_1__host__club=club)
        email = club.account.email

        print "  rendering email msg"
        html_msg = render_to_string(
            "card/manager_email.html", {"club": club.name, "mealsout": mealsout, "mealsin": mealsin}
        )
        text_msg = strip_tags(html_msg)

        msg = EmailMultiAlternatives(
            "MealChecker: End of Month Update!", text_msg, "*****@*****.**", [email]
        )
        msg.attach_alternative(html_msg, "text/html")

        print "  attaching spreadsheet"
        archivename = ARPATH + club.name + ":" + str(month) + "-" + str(year) + ".xls"
        if mealsout or mealsin:
            msg.attach_file(archivename)
        try:
            print "  sending email"
            msg.send()
        except:
            print "  ERROR: unable to send email for %s" % club.name
Esempio n. 34
0
def contactos_view(request):
    infoEnviado = False #DEFINE SI SE ENVIA EL FORMULARIO
    email       = ""
    titulo      = ""
    texto       = ""
    envioCorreo = ""

    if request.method == "POST":
        formulario = contactoForm(request.POST)
        if formulario.is_valid():
            infoEnviado = True
            email = formulario.cleaned_data['Email']
            envioCorreo = formulario.cleaned_data['enviar']
            titulo = formulario.cleaned_data['Titulo']
            texto = formulario.cleaned_data['Texto']
            #CONFIGURACION DE ENVIO DE MENSAJES
            paraMsj   = envioCorreo
            contenido = "Informacion recibida de: [%s] <br><br><br>*** Mensaje ***<br><br>%s"%(email,texto)
            msj       = EmailMultiAlternatives('Correo de Contacto',contenido,'*****@*****.**',[paraMsj])
            msj.attach_alternative(contenido,'text/html') #DEFINIMOS EL CONTENIDO COMO HTML
            msj.attach_file('/home/david/Imágenes/che_anonymous.jpg')#PARA AGREGAR ARCHIVOS
            msj.send() #ENVIAMOS EL CORREO

    else:
        formulario = contactoForm()
    ctx = {'form':formulario,'email':email,'titulo':titulo,'texto':texto,'infoEnviado':infoEnviado}
    return render_to_response('contacto.html',ctx,context_instance=RequestContext(request))
Esempio n. 35
0
def send_message(sender, instance, **kwargs):
    mail_list = []
    for i in User.objects.filter(userprofile__subscribe_to_newsletter=True):
        mail_list.append(i.email)

    print(mail_list[0])
    contact_message = render_to_string('newsletter2.0.html', {
        'title': instance.title,
        'message': instance.email_message
    })
    connection = get_connection()  # uses SMTP server specified in settings.py
    connection.open()

    try:
        email = EmailMultiAlternatives(subject=str(instance.title),
                                       body=contact_message,
                                       from_email=settings.DEFAULT_FROM_EMAIL,
                                       to=mail_list,
                                       connection=connection)
        email.attach_alternative(contact_message, "text/html")
        email.sub_content_type = "html"
        email.attach_file(instance.file.path)
        email.send()
        connection.close()
        print("sent!")
    except Exception as e:
        print(e)
        pass
Esempio n. 36
0
def send_bulk_mail(subject, email_body, recipients, attachments):
    try:
        text_msg = ""
        msg = EmailMultiAlternatives(subject,
                                     text_msg,
                                     settings.SENDER_EMAIL,
                                     [settings.SENDER_EMAIL],
                                     bcc=recipients)
        msg.attach_alternative(email_body, "text/html")
        if attachments:
            for file in attachments:
                path = default_storage.save(
                    os.path.join('attachments', file.name),
                    ContentFile(file.read()))
                msg.attach_file(os.sep.join((settings.MEDIA_ROOT, path)),
                                mimetype="text/html")
                default_storage.delete(path)
        msg.send()

        message = "Email Sent Successfully"

    except Exception as exc_msg:
        message = """Error: {0}. Please check email address.\
                If email address is correct then
                Please contact {1}.""".format(exc_msg, settings.REPLY_EMAIL)

    return message
Esempio n. 37
0
def buyer_authenticate(request):
    if request.is_ajax() and request.method == "POST":
        if request.POST.get("type") == "1":
            phone = request.POST.get("inputPhone").strip()
            if phone in phone_list:
                json_data = json.dumps({"msg": "号码验证成功!", "flag": "true"})
                return HttpResponse(json_data)
            else:
                json_data = json.dumps({
                    "msg": "号码验证失败!抱歉,您不是我们的客户!",
                    "flag": "false"
                })
                return HttpResponse(json_data)
        elif request.POST.get("type") == "2":
            subject = "龟龟摄影微信公众号"
            text_content = "这是一封来自龟龟摄影微信公众号的邮件!" \
                           "附件中携带了您需要的资料。"
            html_content = "<p>这是一封来自<strong>龟龟摄影微信公众号</strong>的邮件!</p>" \
                           "<p><strong>附件</strong>中携带了您需要的资料。</p>"
            from_email = settings.DEFAULT_FROM_EMAIL
            to_email = request.POST.get("inputEmail").strip()
            msg = EmailMultiAlternatives(subject, text_content, from_email,
                                         [to_email])
            msg.attach_alternative(html_content, "text/html")
            msg.attach_file("media/resources/hacker.jpg")
            msg.send()
            return HttpResponse("邮件发送成功!")
    return render(request, "buyer_authenticate.html")
Esempio n. 38
0
    def invia_raw(cls,
                  oggetto,
                  corpo_html,
                  email_mittente,
                  reply_to=None,
                  lista_email_destinatari=None,
                  allegati=None,
                  fallisci_silenziosamente=False,
                  **kwargs):
        """ Questo metodo puo' essere usato per inviare una e-mail immediatamente. """

        plain_text = strip_tags(corpo_html)
        lista_reply_to = [reply_to] if reply_to else []
        lista_email_destinatari = lista_email_destinatari or []
        attachments = allegati or []

        msg = EmailMultiAlternatives(subject=oggetto,
                                     body=plain_text,
                                     from_email=email_mittente,
                                     reply_to=lista_reply_to,
                                     to=lista_email_destinatari,
                                     **kwargs)

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

        if type(attachments) == list:
            for attachment in attachments:
                if hasattr(attachment, 'file'):
                    msg.attach_file(attachment.file.path)
        else:
            filename = os.path.basename(attachments.name)
            msg.attach(filename, attachments.read())

        return msg.send(fail_silently=fallisci_silenziosamente)
Esempio n. 39
0
def email_clubs(ARPATH):
    clubs = Club.objects.all()
    for club in clubs:
        print 'Processing: %s'%club.name
        #meals members had at other clubs without reciprocating
        mealsout = Exchange.objects.filter(meal_2=None).filter(meal_1__guest__club=club)
        #guests hosted at this club without reciprocating
        mealsin = Exchange.objects.filter(meal_2=None).filter(meal_1__host__club=club)
        to_address =  ['*****@*****.**', '*****@*****.**']#[club.account.email]
        print 'Email: %s'%to_address

        print '  rendering email msg'
        html_msg = render_to_string('card/manager_email.html', {'club':
                                                               club.name, 'mealsout':mealsout, 'mealsin':mealsin})
        text_msg = strip_tags(html_msg)

        msg = EmailMultiAlternatives('MealChecker: End of Month Update for %s!' % club.name, 
                                     text_msg, '*****@*****.**', to_address)
        msg.attach_alternative(html_msg, "text/html")

        print '  attaching spreadsheet'
        archivename = ARPATH+club.name + ':'+ str(lastmonth_m)+'-'+str(lastmonth_y)+'.xls'
        if mealsout or mealsin:
            msg.attach_file(archivename)
        try:
            print '  sending email'
            msg.send()
        except:
            print '  ERROR: unable to send email for %s'%club.name
Esempio n. 40
0
    def invia_raw(cls,
                  oggetto,
                  corpo_html,
                  email_mittente,
                  reply_to=None,
                  lista_email_destinatari=None,
                  allegati=None,
                  fallisci_silenziosamente=False,
                  **kwargs):
        """
        Questo metodo puo' essere usato per inviare una e-mail
         immediatamente.
        """

        plain_text = strip_tags(corpo_html)
        lista_reply_to = [reply_to] if reply_to else []
        lista_email_destinatari = lista_email_destinatari or []
        allegati = allegati or []

        msg = EmailMultiAlternatives(subject=oggetto,
                                     body=plain_text,
                                     from_email=email_mittente,
                                     reply_to=lista_reply_to,
                                     to=lista_email_destinatari,
                                     **kwargs)
        msg.attach_alternative(corpo_html, "text/html")
        for allegato in allegati:
            msg.attach_file(allegato.file.path)
        return msg.send(fail_silently=fallisci_silenziosamente)
Esempio n. 41
0
def send_mail(ticket, attach_file=False):
    from main.models import GlobalSettings
    from django.core.mail import EmailMultiAlternatives
    from main import settings

    subject = ticket.subject
    from_email = settings.EMAIL_SENDER_FROM
    recipient_list = [ticket.provider.contact.email]
    footer_text = GlobalSettings.objects.get_setting(
        'service_email_footer').value
    html_message = ticket.text.replace(
        '\n', '<br/>') + '<br/><br/>' + footer_text.replace('\n', '<br/>')
    text_message = ticket.text + '\n\n' + footer_text

    email = EmailMultiAlternatives(subject=subject,
                                   body=text_message,
                                   from_email=from_email,
                                   to=recipient_list)
    email.attach_alternative(html_message, 'text/html')

    if attach_file:
        if ticket.issue and ticket.issue.photo:
            email.attach_file(ticket.issue.photo.path)

    if ticket.photo:
        email.attach_file(ticket.photo.path)

    email_sent = False
    error = ''
    try:
        email_sent = email.send()
    except Exception as e:
        error = str(e)

    return {'sent': email_sent, 'error': error}
Esempio n. 42
0
def send_email_from_recovery(request, rcode):
	if request.method == 'POST':
		ticket = OnTheFlyTicket.objects.get(recovery_code = rcode)
				
		mail_subject = 'bTicket|OntheFly Recovery'
		mail_body = 'The following Ticket information was issued from our service to been sent to this e-mail.\n\nTicket information: \n\n \tRecovery Code:\n\t' +  ticket.recovery_code + "\n \tQR Code:\n\t"
		mail_from = DEFAULT_FROM_EMAIL
		mail_to =  [request.POST['Email']]
	
		qrc_image = qrcode.make(ticket.qr_code.qr_code)
		qrc_image.save('site_media/'+ ticket.qr_code.qr_code + ".png")
		msg = EmailMultiAlternatives(mail_subject, mail_body, mail_from, mail_to)
		msg.attach_file('site_media/'+ ticket.qr_code.qr_code + ".png")
		msg.send()
		os.remove('site_media/'+ ticket.qr_code.qr_code + ".png")
		variables = RequestContext(request, {
			'email' : request.POST['Email'],
			'ontheflyticket': ticket,
			'recovery_msg': 'true',
		})
		
		return render_to_response(
			'main_page.html',
			variables
		)
	else:
		form = SentEmailFromRecoveryForm()
		variables = RequestContext(request, {
			'recoveryForm' : form
		})
		return render_to_response(
			'main_page.html',
			variables
		)
Esempio n. 43
0
    def invia_raw(cls, oggetto, corpo_html, email_mittente,
                  reply_to=None, lista_email_destinatari=None,
                  allegati=None, fallisci_silenziosamente=False,
                  **kwargs):
        """
        Questo metodo puo' essere usato per inviare una e-mail
         immediatamente.
        """

        plain_text = strip_tags(corpo_html)
        lista_reply_to = [reply_to] if reply_to else []
        lista_email_destinatari = lista_email_destinatari or []
        allegati = allegati or []

        msg = EmailMultiAlternatives(
            subject=oggetto,
            body=plain_text,
            from_email=email_mittente,
            reply_to=lista_reply_to,
            to=lista_email_destinatari,
            **kwargs
        )
        msg.attach_alternative(corpo_html, "text/html")
        for allegato in allegati:
            msg.attach_file(allegato.file.path)
        return msg.send(fail_silently=fallisci_silenziosamente)
Esempio n. 44
0
def send_email_view(request):
    subject = '来自leontom的测试邮件'
    time_task_name = 'time定时'
    task_result_code = 'run success!'
    task_time = '60s'
    text_content = '定时任务<{}>已执行完成,结果为<{}>,执行时间为<{}>。详细测试结果见附件'.format(time_task_name,task_result_code, task_time)
    html_content = '<p>定时任务<strong>&lt;{}&gt;</strong>已执行完成,结果为<strong>&lt;{}&gt;</strong>,执行时间为<strong><{}></strong>。详细测试结果见附件</p>'
    html_content = html_content.format(time_task_name, task_result_code, task_time)
    from_email = settings.EMAIL_HOST_USER
    to_emails = ['*****@*****.**', ]
    if subject and text_content and from_email:
        try:
            msg = EmailMultiAlternatives(subject, text_content, from_email, to_emails)
            msg.attach_alternative(html_content, "text/html")                              # 邮箱内容html格式
            file_path = settings.UPLOAD_FILE_PATH + 'test.json'
            file_path = None
            # msg.attach(filename='test', content='file data')
            if file_path:
                msg.attach_file(file_path)                                                     # 添加附件
            msg.send()
        except BadHeaderError:
            return HttpResponse('Invalid header found.')
        return HttpResponseRedirect('Send email success!')
    else:
        return HttpResponse('参数不完整')
Esempio n. 45
0
def send_user_notification(message, from_email, to_email, reply=None):
    """
    Send notification to user
    """
    full_name = message.name + ' ' + message.surname
    template_html = 'email/notification.html'
    html_content = render_to_string(
        template_html, {
            'subject': message.subject,
            'notification': message.text,
            'full_name': full_name,
            'phone': message.phone,
            'sender_email': message.email,
            'reply': reply
        })
    text_content = strip_tags(html_content)
    if reply:
        # If reply send notification to user, which created message
        to_email = message.email
    msg = EmailMultiAlternatives(message.subject, text_content, from_email,
                                 [to_email])
    msg.attach_alternative(html_content, 'text/html')
    if message.image:
        msg.attach_file(message.image.path)
    msg.send(fail_silently=False)
Esempio n. 46
0
def send(permit_link, attachments, permit_path, mail_type, recipients,
         administrative_entity_instance):

    mail = Mail.objects.filter(
        type=mail_type,
        administrative_entity=administrative_entity_instance).first()

    emailcontent = mail.body
    if permit_link != '' and mail_type != 'permit_confirmation':
        emailcontent += '<br>Cliquer ici pour consulter la demande<br><br>'
        emailcontent += '<a href="' + permit_link + '">' + permit_link + '</a>'

    subject, from_email = mail.subject, settings.EMAIL_HOST_USER
    html_content = emailcontent
    if recipients == '':
        recipients = mail.recipients.split(',')

    msg = EmailMultiAlternatives(subject, html_content, from_email, recipients)
    msg.attach_alternative(html_content, "text/html")

    if len(attachments) > 0:
        for file in attachments:
            attachment_path = settings.STATIC_ROOT + '/doc/' + file
            msg.attach_file(attachment_path)

    if permit_path != '':
        msg.attach_file(permit_path)

    msg.send()
Esempio n. 47
0
def Mypdf(request):
    # filename = 'create.pdf'
    # pdf = wkhtmltopdf(template)
    # return HttpResponse(pdf)





    # config = pdfkit.configuration(wkhtmltopdf='/usr/local/bin/html2pdf')
    # pdfkit.from_string('template', 'salary1.pdf', configuration=config)
    logger = logging.getLogger('pdf')
    logger.info('pdf file')
    config = pdfkit.configuration(wkhtmltopdf='/usr/local/bin/html2pdf')
    composers = ComposersProfile.objects.all()
    for composer in composers:
        context = Context({'my_name': composer.first_name,'last_name':composer.last_name })
        print context
        body = "<html>ggggggg</html>"
        template = Template("<table>My name is</table>{{ my_name }}{{ last_name }}")
        print template
        m = template.render(context)
        print m
        pdfkit.from_string(m, 'salary7.pdf', configuration=config)
        mail = EmailMultiAlternatives('Regarding Password Change','email_body','*****@*****.**',['*****@*****.**'])
        mail.attach_file('salary7.pdf')
        mail.send()
    logger.info('end')
    return HttpResponse('0')
Esempio n. 48
0
def mail_send_task(
    to: str,
    subject: str,
    body: str,
    sender: str,
    html: str = None,
    cc: list = None,
    bcc: list = None,
    headers: dict = None,
    attachments: list = None,
):
    email = EmailMultiAlternatives(
        subject, body, sender, to=to, cc=cc, bcc=bcc, headers=headers
    )
    if html is not None:
        email.attach_alternative(inline_css(html), "text/html")
    if attachments:
        from byro.documents.models import Document

        for attachment in attachments:
            email.attach_file(Document.objects.get(pk=attachment).document.path)
    backend = get_connection(fail_silently=False)

    try:
        backend.send_messages([email])
    except Exception:
        logger.exception("Error sending email")
        raise SendMailException("Failed to send an email to {}.".format(to))
def send_email(filename):
    lu = {}
    filedir = "/home/p/r/prasad/webapps/django/MCB-Graphics-Printer-Scheduler/media/"
    filepath = os.path.join(filedir, filename)

    pdf_data = open(filepath, "rb").read()

    cal_admin = CalendarUser.objects.get(pk=1384)
    reservation = Reservation.objects.get(pk=3935)
    cal_user = reservation.user
    lu.update({'cal_event': reservation.calendarevent_ptr,
               'cal_user': cal_user,
               'cal_admin': cal_admin,
               'hostname': 'http://mcbweb.unix.fas.harvard.edu',
               'static_url': STATIC_URL})
    plaintext = get_template('email/download_pdf.txt')
    htmly     = get_template('email/download_pdf.html')
    d = Context(lu)
    subject = 'Invoice copy from MCB Graphics 1'
    from_email, to = MCB_GRAPHICS_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")
    msg.attach_file(filepath)
    msg.send()     
Esempio n. 50
0
File: mail.py Progetto: simone/upy
def send_mail(subject,
              text_content,
              from_email,
              to,
              html_content=None,
              attachments=None,
              publication=""):
    """
    This function sends mail using EmailMultiAlternatives and attachs all attachments
    passed as parameters
    """
    msg = EmailMultiAlternatives(subject, text_content, from_email, to)
    if html_content:
        msg.attach_alternative(html_content, "text/html")
    if attachments:
        for att in attachments:
            mimetype = mimetypes.guess_type(att.file.url)[0]
            if str(mimetype) in ('image/jpeg', 'image/pjpeg', 'image/png',
                                 'image/gif'):
                try:
                    with open(att.file.path) as f:
                        email_embed_image(msg, att.name, f.read())
                except Exception, e:
                    print e
            else:
                msg.attach_file("%s" % (att.file.url[1:]))
Esempio n. 51
0
def Mypdf(request):
    # filename = 'create.pdf'
    # pdf = wkhtmltopdf(template)
    # return HttpResponse(pdf)

    # config = pdfkit.configuration(wkhtmltopdf='/usr/local/bin/html2pdf')
    # pdfkit.from_string('template', 'salary1.pdf', configuration=config)
    logger = logging.getLogger('pdf')
    logger.info('pdf file')
    config = pdfkit.configuration(wkhtmltopdf='/usr/local/bin/html2pdf')
    composers = ComposersProfile.objects.all()
    for composer in composers:
        context = Context({
            'my_name': composer.first_name,
            'last_name': composer.last_name
        })
        print context
        body = "<html>ggggggg</html>"
        template = Template(
            "<table>My name is</table>{{ my_name }}{{ last_name }}")
        print template
        m = template.render(context)
        print m
        pdfkit.from_string(m, 'salary7.pdf', configuration=config)
        mail = EmailMultiAlternatives('Regarding Password Change',
                                      'email_body', '*****@*****.**',
                                      ['*****@*****.**'])
        mail.attach_file('salary7.pdf')
        mail.send()
    logger.info('end')
    return HttpResponse('0')
Esempio n. 52
0
    def handle(self, *args, **options):
        db_name = settings.DATABASES['default']['NAME']
        db_user = settings.DATABASES['default']['USER']
        backup_file = NamedTemporaryFile(prefix=db_name + '-db.bak.', suffix='.gz')
        # pg_dump  -Fc -U pi _8_dev_gassines -f db.bak

        # sudo /etc/init.d/postgresql restart
        # sudo -u postgres psql
        # drop database _8_dev_gassines;
        # CREATE DATABASE _8_dev_gassines WITH TEMPLATE = template0 OWNER = pi ENCODING = 'UTF8' LC_COLLATE = 'fr_BE.UTF-8' LC_CTYPE = 'fr_BE.UTF-8';
        # \q
        # pg_restore  --username=pi --format=c --no-owner --dbname=_8_dev_gassines db.bak

        result = call("pg_dump -Fc -U " + db_user + " " + db_name + " | gzip", stdout=backup_file, shell=True)
        if result == 0:
            migrations_files = NamedTemporaryFile(prefix=db_name + '-mig.bak.', suffix='.gz')
            repanier_path = "%s%s%s" % (os.path.dirname(settings.PROJECT_DIR), os.sep, "repanier")
            result = call("cd %s && tar -zcf %s migrations%s*.py" % (repanier_path, migrations_files.name, os.sep),
                          stdout=migrations_files, shell=True)

            if result == 0:
                email = EmailMultiAlternatives(
                    "Backup " + db_name,
                    "Backup of the DB : " + db_name,
                    settings.DEFAULT_FROM_EMAIL,
                    [v for k, v in settings.ADMINS]
                )
                email.attach_file(os.path.abspath(backup_file.name),
                                  'application/zip')
                email.attach_file(os.path.abspath(migrations_files.name),
                                  'application/zip')
                email.send()
Esempio n. 53
0
    def _send(self):
        if not self.sent:
            if getattr(settings, 'USE_TZ', False):
                # This change breaks SQLite usage.
                from django.utils.timezone import utc
                self.last_attempt = datetime.datetime.utcnow().replace(tzinfo=utc)
            else:
                self.last_attempt = datetime.datetime.now()

            subject, from_email, to = self.subject, self.from_address, self.to_address
            text_content = self.content
            msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
            if self.html_content:
                html_content = self.html_content
                msg.attach_alternative(html_content, "text/html")
            if self.bcc_address:
                if ',' in self.bcc_address:
                    msg.bcc = [ email.strip() for email in self.bcc_address.split(',') ]
                else:
                    msg.bcc = [self.bcc_address, ]

            # Add any additional attachments
            for attachment in self.attachment_set.all():
                msg.attach_file(os.path.join(settings.MEDIA_ROOT, attachment.file_attachment.name))
            try:
                msg.send()
                self.sent = True
            except Exception as e:
                self.do_not_send = True
                logger.error('Mail Queue Exception: {0}'.format(e))
            self.save()
Esempio n. 54
0
def send_templated_email(subject,
                         email_template_name,
                         email_context,
                         recipients,
                         sender=None,
                         bcc=None,
                         fail_silently=False,
                         files=None):

    if not sender:
        sender = settings.DEFAULT_FROM_EMAIL

    html_content = render_to_string(email_template_name, email_context)
    text_content = strip_tags(html_content)

    if isinstance(recipients, str):
        if recipients.find(','):
            recipients = recipients.split(',')
    elif not isinstance(recipients, list):
        recipients = [recipients]
    msg = EmailMultiAlternatives(subject,
                                 text_content,
                                 sender,
                                 recipients,
                                 bcc=bcc)
    msg.attach_alternative(html_content, "text/html")
    if files:
        if not isinstance(files, list):
            files = [files]
        for file in files:
            msg.attach_file(file)
    return msg.send(fail_silently)
Esempio n. 55
0
def payment_email(student):
    subject = "Thanks For Purchasing a PennCycle Membership"
    from_email = "*****@*****.**"
    to_email = student.email
    text_content = """
Dear {},

Thank you for signing up for a PennCycle plan! Once your payment is processed, you will be eligible to check out PennCycles from any of our locations on campus.

In order to check out bikes, text 'help' to 215-688-5468 for instructions. The basic commands are 'check out (bike)' and 'check in (location)'.

While using PennCycle, keep the following in mind:

1. Before riding do an ABC Check (Air in Tires, Brakes, Chain)

2. If you experience any problems while riding or finding a bike, email [email protected].

3. Remember to physically locate the bike you want to check out before texting. This is very important and ensures that you will not be liable for damage/loss of a bike whose location you were unaware of.

4. If your tires feel flat you can pump them up at the bike racks to the next to Pottruck, by the Chemistry Building, and at Quaker Corner, or email us at [email protected] and we'll pump them up for you!

5. Always lock up your bike properly! See the attached picture of a properly locked bike. Ensure the lock goes through the rack, the front wheel and a sturdy part of the frame. If you can't include the front wheel, be sure to include the frame. PennCycle will charge a $5 fee for an improperly locked bike. Never lock your bike to a garbage can, or bench.

We hope that you enjoy your PennCycle experience!

Happy Cycling!

Bobby and the PennCycle Team
""".format(student.name)
    html_content = """
<p>Dear {},</p>

<p>Thank you for signing up for a PennCycle plan! Once your payment is processed, you will be eligible to check out PennCycles from any of our locations on campus.</p>

<p>In order to check out bikes, text 'help' to 215-688-5468 for instructions. The basic commands are 'check out (bike)' and 'check in (location)'.</p>

<p>While using PennCycle, keep the following in mind:</p>
<ol>
    <li>Before riding do an ABC Check (Air in Tires, Brakes, Chain)</li>

    <li>If you experience any problems while riding or finding a bike, email [email protected].</li>

    <li><b>Remember to physically locate the bike you want to check out before texting.</b> This is very important and ensures that you will not be liable for damage/loss of a bike whose location you were unaware of.</li>

    <li>If your tires feel flat you can pump them up at the bike racks to the next to Pottruck, by the Chemistry Building, and at Quaker Corner, or email us at [email protected] and we'll pump them up for you!</li>

    <li><b>Always lock up your bike properly!</b> See the attached picture of a properly locked bike. Ensure the lock goes through the rack, the front wheel and a sturdy part of the frame. If you can't include the front wheel, be sure to include the frame. PennCycle will charge a $5 fee for an improperly locked bike. Never lock your bike to a garbage can, or bench.</li>
</ol>

<p>We hope that you enjoy your PennCycle experience!</p>

<p>Happy cycling!</p>

<p>The PennCycle Team</p>""".format(student.name)
    msg = EmailMultiAlternatives(subject, text_content, from_email, [to_email])
    msg.attach_alternative(html_content, "text/html")
    msg.attach_file("penncycle/assets/img/locked_bike.png")
    msg.send()
Esempio n. 56
0
def send_mail_text_and_html(subject, email_template_name, email_context, recipients, sender=None, bcc=None, 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.

    email_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 file paths to be attached, or it can be left blank.
        eg ('/tmp/file1.txt', '/tmp/image.png')
    """
    c = Context(email_context)
    if not sender:
        sender = settings.DEFAULT_FROM_EMAIL

    tpl_plain = email_template_name + ".txt"
    tpl_html = email_template_name + ".html"

    template_plain = loader.get_template(tpl_plain)
    template_html = loader.get_template(tpl_html)
    text_part = template_plain.render(c)
    html_part = template_html.render(c)

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

    message = EmailMultiAlternatives(subject, text_part, sender, recipients, bcc=bcc)
    message.attach_alternative(html_part, "text/html")

    if files:
        if type(files) != list:
            files = [files]

        for file in files:
            message.attach_file(file)

    sender = SESBackend()
    result = sender.send_messages([message])

    return result
Esempio n. 57
0
 def shoot_email(self):
     #html_content = EMAIL['header'] + self.kwargs['body'] + EMAIL['footer']
     html_content = self.kwargs['body']
     msg = EmailMultiAlternatives(self.kwargs['subject'], html_content, EMAIL_HOST_USER, \
             [self.kwargs['email']])
     if 'attachment' in self.kwargs:
         msg.attach_file(self.kwargs['attachment'])
     msg.attach_alternative(html_content, "text/html")
     msg.send()
Esempio n. 58
0
def send_email(request, id):
    person_print = FIO.objects.get(id=id)
    # creating email
    subject, from_email, to = u'Письмо', '*****@*****.**', person_print.email
    text_content = u"Письмо".format(person_print.name, person_print.surname)
    msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
    msg.attach_file('/Users/danilakimov/Desktop/readytemplate.pdf')
    msg.send()
    return render(request, 'template_page.html', {'person_template': person_print})
 def send_mail(self,reporting_file_path):
     today_date = datetime.datetime.now().strftime("%Y-%m-%d")
     subject = "Health & Nutrition (West Africa): Data received till %s"%(today_date)
     from_email = dg.settings.EMAIL_HOST_USER
     to_email = ['*****@*****.**', '*****@*****.**']
     body = "Dear Team,\n\nPlease find the attached Health & Nutrition (West Africa) data entered till %s.\nPlease contact [email protected] for any question or clarification.\n\nThank you."%(today_date)
     msg = EmailMultiAlternatives(subject, body, from_email, to_email)
     msg.attach_file(reporting_file_path, 'text/csv' )
     msg.send()