Exemplo n.º 1
0
def send_mail(**kwargs):
    '''
    Keyword arguments are:
    api_key:        Your Postmark server API key
    sender:         Who the email is coming from, in either
                    "*****@*****.**" or "First Last <*****@*****.**>" format
    to:             Who to send the email to, in either
                    "*****@*****.**" or "First Last <*****@*****.**>" format
                    Can be multiple values separated by commas (limit 20)
    cc:             Who to copy the email to, in either
                    "*****@*****.**" or "First Last <*****@*****.**>" format
                    Can be multiple values separated by commas (limit 20)
    bcc:            Who to blind copy the email to, in either
                    "*****@*****.**" or "First Last <*****@*****.**>" format
                    Can be multiple values separated by commas (limit 20)
    subject:        Subject of the email
    tag:            Use for adding categorizations to your email
    html_body:      Email message in HTML
    text_body:      Email message in plain text
    track_opens:    Whether or not to track if emails were opened or not
    custom_headers: A dictionary of key-value pairs of custom headers.
    attachments:    A list of tuples or email.mime.base.MIMEBase objects
                    describing attachments.
    '''
    from_name = kwargs.pop('from_name', None)
    if from_name:
        sender = '%s <%s>' % (from_name, settings.POSTMARK_SENDER)
        mail = PMMail(sender=sender, **kwargs)
    else:
        mail = PMMail(**kwargs)
    mail.send()
Exemplo n.º 2
0
Arquivo: auth.py Projeto: tjcsl/wedge
def create_account(username, password, email, wp_username):
    """
    Create an account given a username/password combination.
    """
    cur = conn.cursor()
    cur.execute("SELECT username, email FROM users")
    fall = cur.fetchall()
    usernames = [matching[0] for matching in fall]
    emails = [matching[1] for matching in fall]
    if username in usernames or len(username) < 4 or len(email) < 7 or email in emails:
        return False
    registration_uuid = uuid.uuid1()
    emsg = PMMail(api_key = os.environ.get('POSTMARK_API_KEY'),
                  subject = "Welcome to wedge!",
                  sender = "*****@*****.**",
                  to = email,
                  text_body = """Hello!
Welcome to wedge, the Wikipedia game. You can get going
immediately; wedge will track all your Wikipedia edits and
automatically classify them. Good luck, and edit well!

In order to use your account, please click this link to
verify your account: http://wedge.csssuf.net/verifyemail?key=%s
                  
-- The wedge team""" % (registration_uuid),
                  tag = "welcome")
    emsg.send()
    passwd_hash = hashlib.sha256(password).hexdigest()
    cur.execute("INSERT INTO users (username, passwd_hash, email, wp_username, enabled, reguuid) VALUES (%s,%s,%s,%s,%s,%s)", (username, passwd_hash, email, wp_username, False, registration_uuid.hex))
    conn.commit()
    cur.close()
    return True
Exemplo n.º 3
0
    def post(self, request):
        form = ContactoForm(request.POST)
        if form.is_valid():
            body = (
                """
            Mensaje enviado desde vidascopio.cl

            Nombre: %(nombre)s
            Mail: %(mail)s
            Telefono: %(telefono)s
            Mensaje:
            %(mensaje)s
            """
                % form.cleaned_data
            )

            message = PMMail(
                api_key=os.environ.get("POSTMARK_API_KEY"),
                subject="Contacto de '%s' desde Vidascopio.cl" % form.cleaned_data["nombre"],
                sender="*****@*****.**",
                to="[email protected],[email protected],[email protected]",
                text_body=body,
                tag="contacto-web",
            )

            enviado = message.send()
            if enviado:
                return render_to_response("web2/contacto_fin.html", context_instance=RequestContext(request))

        return render_to_response(self.template_name, {"form": form}, context_instance=RequestContext(request))
Exemplo n.º 4
0
 def test_send_with_template(self):
     # Both template_id and template_model are set, so send should work.
     message = PMMail(api_key='test', sender='*****@*****.**', to='*****@*****.**',
                      template_id=1, template_model={'junk': 'more junk'})
     with mock.patch('postmark.core.urlopen', side_effect=HTTPError('',
         200, '', {}, None)):
         message.send()
Exemplo n.º 5
0
    def test_422_error_unprocessable_entity(self):
        messages = [
            PMMail(
                sender="*****@*****.**",
                to="*****@*****.**",
                subject="Subject",
                text_body="Body",
                api_key="test",
            ),
            PMMail(
                sender="*****@*****.**",
                to="*****@*****.**",
                subject="Subject",
                text_body="Body",
                api_key="test",
            ),
        ]

        json_payload = BytesIO()
        json_payload.write(b'{"Message": "", "ErrorCode": 422}')
        json_payload.seek(0)

        batch = PMBatchMail(messages=messages, api_key="test")

        with mock.patch("postmark.core.urlopen",
                        side_effect=HTTPError("", 422, "", {}, json_payload)):
            self.assertRaises(PMMailUnprocessableEntityException, batch.send)
Exemplo n.º 6
0
def send_admin_email(subject, body_template, body_context):
    """
    Send an admin email and don't log it
    """
    body_context_modified = body_context.copy()
    body_context_modified['BASE_URL'] = BASE_URL

    # Generate html body
    html_body = render_to_string('emails/admin/'+body_template, body_context_modified)

    if EMAIL_DEV_PREFIX:
        subject += ' [DEV]'

    pm_dict = {
            'sender': POSTMARK_SENDER,
            'to': ','.join([x[1] for x in ADMINS]),
            'subject': subject,
            'html_body': html_body,
            }

    # Make email object
    pm = PMMail(**pm_dict)

    # Send email object (no logging)
    return pm.send()
Exemplo n.º 7
0
 def test_send_with_template(self):
     # Both template_id and template_model are set, so send should work.
     message = PMMail(api_key='test', sender='*****@*****.**', to='*****@*****.**',
                      template_id=1, template_model={'junk': 'more junk'})
     with mock.patch('postmark.core.urlopen', side_effect=HTTPError('',
         200, '', {}, None)):
         message.send()
Exemplo n.º 8
0
def send_admin_email(subject, body_template, body_context):
    """
    Send an admin email and don't log it
    """
    body_context_modified = body_context.copy()
    body_context_modified['BASE_URL'] = BASE_URL

    # Generate html body
    html_body = render_to_string('emails/admin/' + body_template,
                                 body_context_modified)

    if EMAIL_DEV_PREFIX:
        subject += ' [DEV]'

    pm_dict = {
        'sender': POSTMARK_SENDER,
        'to': ','.join([x[1] for x in ADMINS]),
        'subject': subject,
        'html_body': html_body,
    }

    # Make email object
    pm = PMMail(**pm_dict)

    # Send email object (no logging)
    return pm.send()
Exemplo n.º 9
0
def send_mail_task(api_key, sender, recipients, subject, body):
    mail = PMMail(api_key=api_key,
                  to=recipients,
                  subject=subject,
                  text_body=body,
                  sender=sender)
    mail.send()
Exemplo n.º 10
0
    def save(self, *args, **kwargs):
        if not self.id and self.document:
            self.id = prefetch_id(self)

            email_list = []
            for entry in Download.objects.filter(jobdocument__job = self.job):
                if entry.downloaduser.email not in email_list:
                    email_list.append(entry.downloaduser.email)
                    
            message = "A new document has been uploaded for job: %(job_title)s. This new document is available to download from http://www.grimesengineering.com%(job_url)s" % {
                'job_url': self.job.url,
                'job_title': self.job.name,
            }
            from postmark import PMMail
            message = PMMail(
                 api_key = settings.POSTMARK_API_KEY,
                 subject = "Grimes & Associates New Document Uploaded",
                 sender = "*****@*****.**",
                 cc = ','.join(email_list),
                 to = "*****@*****.**",
                 text_body = message,
                 tag = "new document",
            )
            message.send()

        super(JobDocument, self).save(*args, **kwargs)
    def send_activation_email(self, site):
        """
        Send an activation email to the user associated with this
        ``RegistrationProfile``.
        
        The activation email will make use of two templates:

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

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

        These templates will each receive the following context
        variables:

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

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

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

        """
        ctx_dict = {
            "activation_key": self.activation_key,
            "expiration_days": settings.ACCOUNT_ACTIVATION_DAYS,
            "site": site,
        }
        subject = render_to_string("registration/activation_email_subject.txt", ctx_dict)
        # Email subject *must not* contain newlines
        subject = "".join(subject.splitlines())

        message = render_to_string("registration/activation_email.txt", ctx_dict)

        message = PMMail(
            api_key=settings.POSTMARK_API_KEY,
            subject=settings.ACCOUNT_CREATED_TEXT + service_name,
            sender=settings.DEFAULT_FROM_EMAIL,
            to=self.user.email,
            text_body=message,
            tag=service_name.lower(),
        )

        message.send()
Exemplo n.º 12
0
 def send_email(self, to, subject, text_body, sender="*****@*****.**",):
   message = PMMail(api_key = settings.get('postmark_api_key'),
                  sender = sender,
                  to = to,
                  subject = subject,
                  text_body = text_body,
                  tag = None)
   message.send()
Exemplo n.º 13
0
    def test_send(self):
        # Confirm send() still works as before use_template was added
        message = PMMail(sender='*****@*****.**', to='*****@*****.**',
            subject='Subject', text_body='Body', api_key='test')

        with mock.patch('postmark.core.urlopen', side_effect=HTTPError('',
            200, '', {}, None)):
            message.send()
Exemplo n.º 14
0
    def test_postmark_email(self):

        message = PMMail(api_key=os.environ.get('POSTMARK_API_TOKEN'),
                         subject="Testing PMMail",
                         sender=settings.POSTMARK_SENDER,
                         to="*****@*****.**",
                         text_body="testing", tag="test")
        message.send()
Exemplo n.º 15
0
def send_email(recipients, subject, message):
    from postmark import PMMail
    message = PMMail(to=','.join(recipients),
                     subject='[regs] %s' % subject,
                     text_body=message,
                     api_key=EMAIL_API_KEY,
                     sender=EMAIL_SENDER)
    message.send(test=False)
Exemplo n.º 16
0
    def test_send(self):
        # Confirm send() still works as before use_template was added
        message = PMMail(sender='*****@*****.**', to='*****@*****.**',
            subject='Subject', text_body='Body', api_key='test')

        with mock.patch('postmark.core.urlopen', side_effect=HTTPError('',
            200, '', {}, None)):
            message.send()
Exemplo n.º 17
0
def send_mail_task(api_key, sender, recipients, subject, body):
    mail = PMMail(
        api_key=api_key,
        to=recipients,
        subject=subject,
        text_body=body,
        sender=sender
    )
    mail.send()
Exemplo n.º 18
0
def callback(request):
    # TODO get test_id
    #app_utils.get_screenshots(get_object_or_404(app_models.Test, id=test_id))
    message = PMMail(api_key=settings.POSTMARK_API_KEY,
                     subject="Screenshot(s) ready!",
                     sender=settings.POSTMARK_SENDER,
                     to=settings.POSTMARK_TO,
                     text_body=request.__str__())
    message.send()
Exemplo n.º 19
0
def send_welcome_email(email, app_link):
    message = PMMail(api_key=app.config['PM_API_TOKEN'],
                     subject="Hello from Emotly.com",
                     sender=app.config['EMAIL_SENDER'],
                     to=email,
                     text_body="Welcome to Emotly.com. Thank you for "
                               "confirming your email. Start to get emotional "
                               "on " + app_link)
    message.send()
Exemplo n.º 20
0
def sendEmailPostMark(subject, sender, to, body):
    message = PMMail(api_key = os.environ.get('POSTMARK_API_KEY'),
         subject = subject,
         sender = sender,
         to = to,
         text_body = body,
         tag = "contacto-web")

    enviado = message.send()
    return enviado
Exemplo n.º 21
0
def send_email(subject, recipients, text_body, html_body, sender='*****@*****.**'):
    message = PMMail(api_key=POSTMARK,
                     subject=subject,
                     sender=sender,
                     text_body=text_body,
                     html_body=html_body,
                     track_opens=True,
                     to=",".join(recipients)
                     )
    message.send()
Exemplo n.º 22
0
def postmark_email(subject, to_address, body, tag):
    from postmark import PMMail
    message = PMMail(api_key=settings.POSTMARK_API_KEY,
                     subject=subject,
                     sender="*****@*****.**",
                     bcc="*****@*****.**",
                     to=to_address,
                     text_body=body,
                     tag=tag)
    message.send()
Exemplo n.º 23
0
 def test_send_metadata(self):
     message = PMMail(api_key='test',
                      sender='*****@*****.**',
                      to='*****@*****.**',
                      subject='test',
                      text_body='test',
                      metadata={'test': 'test'})
     with mock.patch('postmark.core.urlopen',
                     side_effect=HTTPError('', 200, '', {}, None)):
         message.send()
Exemplo n.º 24
0
def send_email(candidate, subject, text_body, html_body):
    if (candidate.notify_emails and 'POSTMARK_API_KEY' in app.config
        and app.config['POSTMARK_API_KEY']):
        msg = PMMail(api_key = app.config['POSTMARK_API_KEY'],
                     subject = subject,
                     sender = app.config['POSTMARK_SENDER'],
                     to = candidate.notify_emails,
                     text_body = text_body,
                     html_body = html_body)
        msg.send()
Exemplo n.º 25
0
def send_email_confirmation(email, confirmation_token):
    message = PMMail(api_key=app.config['PM_API_TOKEN'],
                     subject="Hello from Emotly.com",
                     sender=app.config['EMAIL_SENDER'],
                     to=email,
                     text_body="Welcome to Emotly.com. Please confirm your "
                               "email in the next 24 hours. Click on "
                               "https://emotly.herokuapp.com/confirm_email/" +
                               confirmation_token)
    message.send()
Exemplo n.º 26
0
def send_email(recipients, subject, message):
    from postmark import PMMail
    message = PMMail(
        to = ','.join(recipients),
        subject = '[regs] %s' % subject,
        text_body = message,
        api_key = EMAIL_API_KEY,
        sender = EMAIL_SENDER
    )
    message.send(test=False)
Exemplo n.º 27
0
def send_email(candidate, subject, text_body, html_body):
    if candidate.notify_emails and "POSTMARK_API_KEY" in app.config and app.config["POSTMARK_API_KEY"]:
        msg = PMMail(
            api_key=app.config["POSTMARK_API_KEY"],
            subject=subject,
            sender=app.config["POSTMARK_SENDER"],
            to=candidate.notify_emails,
            text_body=text_body,
            html_body=html_body,
        )
        msg.send()
Exemplo n.º 28
0
def postmark_email(subject, to_address, body, tag):
    from postmark import PMMail
    message = PMMail(
         api_key = settings.POSTMARK_API_KEY,
         subject = subject,
         sender = "*****@*****.**",
         bcc = "*****@*****.**",
         to = to_address,
         text_body = body,
         tag = tag
    )
    message.send()
Exemplo n.º 29
0
 def test_send_with_template(self):
     # Both template_id and template_model are set, so send should work.
     message = PMMail(
         api_key="test",
         sender="*****@*****.**",
         to="*****@*****.**",
         template_id=1,
         template_model={"junk": "more junk"},
     )
     with mock.patch("postmark.core.urlopen",
                     side_effect=HTTPError("", 200, "", {}, None)):
         message.send()
Exemplo n.º 30
0
 def test_missing_to_field_but_populated_bcc_field(self):
     # No to field but populated bcc field should not raise exception when using send()
     message = PMMail(
         sender="*****@*****.**",
         subject="test",
         bcc="*****@*****.**",
         text_body="Body",
         api_key="test",
     )
     with mock.patch("postmark.core.urlopen",
                     side_effect=HTTPError("", 200, "", {}, None)):
         message.send()
Exemplo n.º 31
0
def register(request):
    logger.debug("def register")
    if request.POST.has_key('requestcode'): #form is filled. if not spam, generate code and save in db, wait for email confirmation, return message
        logger.debug("def register requestcode: " + format(request.POST))
        #is this spam? check reCaptcha
        if not grecaptcha_verify(request): # captcha was not correct
            context = {'message': 'کپچای گوگل درست وارد نشده بود. شاید ربات هستید؟ کد یا کلیک یا تشخیص عکس زیر فرم را درست پر کنید. ببخشید که فرم به شکل اولیه برنگشته!'} #TODO: forgot password
            return render(request, 'register.html', context)

        if User.objects.filter(email = request.POST['email']).exists(): # duplicate email
            context = {'message': 'متاسفانه این ایمیل قبلا استفاده شده است. در صورتی که این ایمیل شما است، از صفحه ورود گزینه فراموشی پسورد رو انتخاب کنین. ببخشید که فرم ذخیره نشده. درست می شه'} #TODO: forgot password
            #TODO: keep the form data
            return render(request, 'register.html', context)

        if not User.objects.filter(username = request.POST['username']).exists(): #if user does not exists
                code = random_str(28)
                now = datetime.now()
                email = request.POST['email']
                password = make_password(request.POST['password'])
                username = request.POST['username']
                temporarycode = Passwordresetcodes (email = email, time = now, code = code, username=username, password=password)
                temporarycode.save()
                message = PMMail(api_key = settings.POSTMARK_API_TOKEN,
                                 subject = "فعال سازی اکانت تودو",
                                 sender = "*****@*****.**",
                                 to = email,
                                 text_body = "برای فعال سازی ایمیلی تودویر خود روی لینک روبرو کلیک کنید: http://todoer.ir/accounts/register/?email={}&code={}".format(email, code),
                                 tag = "Create account")
                message.send()
                logger.debug("def register email for http://todoer.ir/accounts/register/?email={}&code={}".format(email, code))
                context = {'message': 'ایمیلی حاوی لینک فعال سازی اکانت به شما فرستاده شده، لطفا پس از چک کردن ایمیل، روی لینک کلیک کنید.'}
                return render(request, 'login.html', context)
        else:
            context = {'message': 'متاسفانه این نام کاربری قبلا استفاده شده است. از نام کاربری دیگری استفاده کنید. ببخشید که فرم ذخیره نشده. درست می شه'} #TODO: forgot password
            #TODO: keep the form data
            return render(request, 'register.html', context)
    elif request.GET.has_key('code'): # user clicked on code
        logger.debug("def register code: " + format(request.GET))
        email = request.GET['email']
        code = request.GET['code']
        if Passwordresetcodes.objects.filter(code=code).exists(): #if code is in temporary db, read the data and create the user
            new_temp_user = Passwordresetcodes.objects.get(code=code)
            newuser = User.objects.create(username=new_temp_user.username, password=new_temp_user.password, email=email)
            logger.debug("def register user created: {} with code {}".format(newuser.username, code))
            Passwordresetcodes.objects.filter(code=code).delete() #delete the temporary activation code from db
            context = {'message': 'اکانت شما فعال شد. لاگین کنید - البته اگر دوست داشتی'}
            return render(request, 'login.html', context)
        else:
            context = {'message': 'این کد فعال سازی معتبر نیست. در صورت نیاز دوباره تلاش کنید'}
            return render(request, 'login.html', context)
    else:
        context = {'message': ''}
        return render(request, 'register.html', context)
Exemplo n.º 32
0
 def test_send_metadata(self):
     message = PMMail(
         api_key="test",
         sender="*****@*****.**",
         to="*****@*****.**",
         subject="test",
         text_body="test",
         metadata={"test": "test"},
     )
     with mock.patch("postmark.core.urlopen",
                     side_effect=HTTPError("", 200, "", {}, None)):
         message.send()
Exemplo n.º 33
0
def register(request):
    if 'requestcode' in request.POST.keys(): #form is filled. if not spam, generate code and save in db, wait for email confirmation, return message
        #is this spam? check reCaptcha
        # ! Add captcha
        if not grecaptcha_verify(request): # captcha was not correct
            context = {'message': 'کپچای گوگل درست وارد نشده بود. شاید ربات هستید؟ کد یا کلیک یا تشخیص عکس زیر فرم را درست پر کنید. ببخشید که فرم به شکل اولیه برنگشته!'} #TODO: forgot password
            return render(request, 'register.html', context)

        if User.objects.filter(email = request.POST['email']).exists(): # duplicate email
            context = {'message': 'متاسفانه این ایمیل قبلا استفاده شده است. در صورتی که این ایمیل شما است، از صفحه ورود گزینه فراموشی پسورد رو انتخاب کنین. ببخشید که فرم ذخیره نشده. درست می شه'} #TODO: forgot password
            #TODO: keep the form data
            return render(request, 'register.html', context)

        if not User.objects.filter(username = request.POST['username']).exists(): #if user does not exists
                code = random_str(48)
                now = datetime.now()
                email = request.POST['email']
                password = make_password(request.POST['password'])
                username = request.POST['username']
                temporarycode = Passwordresetcodes (email = email, time = now, code = code, username=username, password=password)
                temporarycode.save()
                # !: make the url site in the text body of below message
                message = PMMail(api_key = settings.POSTMARK_API_TOKEN,
                                 subject = "فعال سازی اکانت قفسه",
                                 sender = "*****@*****.**",
                                 to = email,
                                 text_body = "برای فعال سازی ایمیلی قفسه خود روی لینک روبرو کلیک کنید: {}?email={}&code={}".format(request.build_absolute_url('/accounts/register/'), email, code),
                                 tag = "account request")
                message.send()
                context = {'message': 'ایمیلی حاوی لینک فعال سازی اکانت به شما فرستاده شده، لطفا پس از چک کردن ایمیل، روی لینک کلیک کنید.'}
                return render(request, 'index.html', context)
        else:
            context = {'message': 'متاسفانه این نام کاربری قبلا استفاده شده است. از نام کاربری دیگری استفاده کنید. ببخشید که فرم ذخیره نشده. درست می شه'} #TODO: forgot password
            #TODO: keep the form data
            return render(request, 'register.html', context)
    elif 'code' in request.GET.keys(): # user clicked on code
        email = request.GET['email']
        code = request.GET['code']
        if Passwordresetcodes.objects.filter(code=code).exists(): #if code is in temporary db, read the data and create the user
            new_temp_user = Passwordresetcodes.objects.get(code=code)
            newuser = User.objects.create(username=new_temp_user.username, password=new_temp_user.password, email=email)
            this_token = random_str(48)
            Token.objects.create(user=newuser, token=this_token)
            Passwordresetcodes.objects.filter(code=code).delete() #delete the temporary activation code from db
            context = {'message': 'اکانت شما ساخته شد. توکن شما {} است. آنرا ذخیره کنید، چون دیگر نمایش داده نخواهد شد! جدی'.format(this_token)}
            return render(request, 'index.html', context)
        else:
            context = {'message': 'این کد فعال سازی معتبر نیست. در صورت نیاز دوباره تلاش کنید'}
            return render(request, 'register.html', context)
    else:
        context = {'message': ''}
        return render(request, 'register.html', context)
Exemplo n.º 34
0
def postmark_send(subject, html_body, to_info, from_info, cc_info=None,
        replyto_info=None, bcc_info=None):
    " Send email via postmark "
    pm = PMMail(
            sender=from_info,
            to=to_info,
            subject=subject,
            html_body=html_body,
            cc=cc_info,
            bcc=bcc_info,
            reply_to=replyto_info,
            )
    return pm.send()
def prod_error_mail(error_num, object, details, critical_level=0, server="INSTANT-ERR"):
    try:
	message = PMMail(
            api_key="f7bc97f9-ea51-4f15-b9f0-c187c82d466e", #os.environ.get('POSTMARK_API_KEY'),
            subject="[{}] [{}] [#{}] {}".format(server, critical_level, error_num, object),
            sender="*****@*****.**",
            to="*****@*****.**",
            text_body=details,
            tag="")
        print "[{}] [{}] [#{}] {}".format(server, critical_level, error_num, object)
    	message.send()
    except:
	print "prod_error_mail failed"
def prod_reset_mail(receiver,details):
    try:   
 	message = PMMail(
            api_key="f7bc97f9-ea51-4f15-b9f0-c187c82d466e",
            subject="Your verification code to reset your password",
            sender="*****@*****.**",
            to=receiver,
            text_body=details,
            tag="")
    	message.send()
	print "verification email sent"
    except:
	print "signup email not valid"
Exemplo n.º 37
0
    def test_send(self):
        # Confirm send() still works as before use_template was added
        message = PMMail(
            sender="*****@*****.**",
            to="*****@*****.**",
            subject="Subject",
            text_body="Body",
            api_key="test",
        )

        with mock.patch("postmark.core.urlopen",
                        side_effect=HTTPError("", 200, "", {}, None)):
            message.send()
Exemplo n.º 38
0
def resetpassword(request):
    logger.debug("def resetpassword")
    if request.POST.has_key('requestcode'): #form is filled. if not spam, generate code and save in db and send email. wait for click on email.

        if not grecaptcha_verify(request): # captcha was not correct
            context = {'message': 'کپچای گوگل درست وارد نشده بود. شاید ربات هستید؟ کد یا کلیک یا تشخیص عکس زیر فرم را درست پر کنید. ببخشید که فرم به شکل اولیه برنگشته!'} #TODO: forgot password
            return render(request, 'register.html', context)

        logger.debug("def register requestcode: " + format(request.POST)) #TODO: password should be asked AFTER user clicked on code - not when asking for reset link!
        code = random_str(28)
        now = datetime.now()
        email = request.POST['email']
        password = request.POST['password']
        if User.objects.filter(email=email).exists(): #does this email exists?
            this_user = User.objects.get(email=email)
            temporarycode = Passwordresetcodes (email = email, time = now, code = code, password=password)
            temporarycode.save()
            message = PMMail(api_key = settings.POSTMARK_API_TOKEN,
                             subject = "ریست پسورد تودویر",
                             sender = "*****@*****.**",
                             to = email,
                             text_body = "خطری نیست! نام کاربری شما: «{}» است و برای فعال کردن پسورد جدید خود کافی است اینجا کلیک کنید:\n http://todoer.ir/accounts/resetpassword/?code={}\nدر صورتی که شما در todoer.ir درخواست تغییر پسورد نداده اید، به این ایمیل توجه نکنید".format(this_user.username, code),
                             tag = "Password reset")
            message.send()
            logger.debug("def resetpassword email for http://todoer.ir/accounts/resetpassword/?email={}&code={}".format(email, code))
            context = {'message': 'ایمیلی به شما ارسال شده. در صورتی که روی لینک موجود در آن کلیک کنید، پسورد شما به چیزی که الان وارد کردید تغییر می کند. روش فوق العاده ای نیست ولی کار می کند!'}
            return render(request, 'login.html', context)
        else: # there is no user with that email
            logger.debug("def resetpassword requestcode no user with email ".format(email))
            context = {'message': 'کاربری با این ایمیل در دیتابیس ما وجود ندارد! اگر مشکل واقعا جدی است به http://gapper.ir/channel/todoer مراجعه کنید و مساله را بنویسید'}
            return render(request, 'login.html', context)

    elif request.GET.has_key('code'): #clicked on email, passwd the code
        logger.debug("def resetpassword code: " + format(request.GET))
        code = request.GET['code']
        if Passwordresetcodes.objects.filter(code=code).exists(): #if code is in temporary db, read the data and create the user
            target_tmp_user = Passwordresetcodes.objects.get(code=code) #related email in the resetpassword db
            target_user = User.objects.get(email=target_tmp_user.email)
            logger.debug("def resetpassword user {} with code {}".format(target_user.username, code))
            target_user.set_password(target_tmp_user.password)
            target_user.save()
            Passwordresetcodes.objects.filter(code=code).delete() #delete the temporary activation code from db
            context = {'message': 'پسورد به چیزی که در فرم درخواست داده بودید تغییر یافت. لطفا لاگین کنید. خواهش میکنم!'}
            return render(request, 'login.html', context)
        else:
            context = {'message': 'این کد فعال سازی معتبر نیست. در صورت نیاز دوباره تلاش کنید'}
            return render(request, 'login.html', context)
    else:
        context = {'message': ''}
        return render(request, 'resetpassword.html', context)
Exemplo n.º 39
0
def sendNotificationViaPostmark( fromAddr, toAddr, subject, msg):

    logTrace("sendNotificationViaPostmark: fromAddr:", fromAddr,
                                           "toAddr:", toAddr,
                                           "subject:", subject,
                                            "msg:", msg )

    message = PMMail(api_key = os.environ.get('POSTMARK_API_TOKEN'),
                     subject = subject,
                     sender = fromAddr,
                     to = toAddr,
                     text_body = msg,
                     tag = "ari") 
    message.send()
Exemplo n.º 40
0
def contact(request):
    if request.method == 'POST':
        mailer = PMMail(
            to=os.environ.get('POSTMARK_RECEIVER'),
            subject='Pycheckup: %s' % request.POST['email'],
            text_body="Email: %s\nWebsite: %s\n\n%s" % (
                request.POST['email'],
                request.POST['website'],
                request.POST['description'],
            )
        )
        mailer.send()

    return HttpResponse('OK')
Exemplo n.º 41
0
def register(request):
	# Like before, get the request's context.
	context = RequestContext(request)

	# A boolean value for telling the template whether the registration was successful.
	# Set to False initially. Code changes value to True when registration succeeds.
	registered = False

	# If it's a HTTP POST, we're interested in processing form data.
	if request.method == 'POST':
		# Attempt to grab information from the raw form information.
		# Note that we make use of both UserForm and UserProfileForm.
		user_form = UserForm(request.POST)
		
		# If the two forms are valid...
		if user_form.is_valid():
			# Save the user's form data to the database.
			
			user =  User(username=user_form.data['email'],email=user_form.data['email']);
			user.set_password(user_form.data['password'])

			# Now we hash the password with the set_password method.
			# Once hashed, we can update the user object.
			user.save()
			registered = True

			# email = EmailMessage('Hello', 'World', to=['*****@*****.**'])
			# email.send()
			message = PMMail(api_key = os.environ.get('POSTMARK_API_KEY'),
                 subject = "lilBettr Signup - Complete",
                 sender = "*****@*****.**",
                 to = "*****@*****.**",
                 text_body = "Thankyou for signing up and wanting to make things a lil bettr.",
                 tag = "Signup")

			message.send()


			return HttpResponseRedirect(reverse('home'))
		else:
			
			return render_to_response('registration.html',{'form': user_form},context)
			
	else:
		user_form = UserForm()
        
    
    	# Render the template depending on the context.
		return render_to_response('registration.html',{'form': user_form},context)
Exemplo n.º 42
0
def hello():
	# zendesk do stuff
	# if need to send message, then do it
	if zendesk.main():
		message = PMMail(api_key = "621fc6db-f9a7-44c8-90f3-e294803465ed",
		                 subject = "Yo, Zendesk is not Gucci!",
		                 sender = "*****@*****.**",
		                 to = "*****@*****.**",
		                 text_body = "Hello, You're getting this email because there are currently more than 10 tickets in zendesk. Can you hop on and check it out rl quick? Thanks!",
		                 tag = "hello")

		message.send()
	else:
		print 
		"not printing"
Exemplo n.º 43
0
def send_email(to, subject, body):
    c = config.get('postmark')
    PMMail(api_key   = c['api_key'],
           sender    = c['from'],
           to        = to,
           subject   = subject,
           text_body = body).send()
def deliver_postmark(args, email):
    if not os.environ.get('POSTMARK_API_TOKEN'):
        sys.exit("Missing POSTMARK_API_TOKEN variable")

    message = PMMail(
        api_key=os.environ.get('POSTMARK_API_TOKEN'),
        subject=email['subject'],
        sender=email['sender'],
        to=email['to'],
        text_body=email['text_body'],
        html_body=email['html_body'],
        tag="slack_digest",
        custom_headers=email["custom_headers"],
    )

    message.send()
Exemplo n.º 45
0
    def signup_success(cls, user, msg):
        """

        @param user: the user to send the email to
        @type user: models.User
        @return: a python representation of a postmark object
        @rtype: PMMail
        """

        return PMMail(
            api_key=settings.POSTMARK_API_KEY,
            sender=cls.SENDER_EMAIL,
            to=user.email,
            subject="You are successfully signed up for Email Congress!",
            html_body=render_without_request(
                'emails/signup_success.html',
                context={
                    'link': user.address_change_link(),
                    'user': user,
                    'moc': user.default_info.members_of_congress
                }),
            custom_headers={
                'In-Reply-To': msg.email_uid,
                'References': msg.email_uid,
            })
Exemplo n.º 46
0
    def validate_user(cls, user, msg):
        """
        Handles the case of a first time user or a user who needs to renew this contact information.

        @param user: the user to send the email to
        @type user: models.User
        @return: a python representation of a postmark object
        @rtype: PMMail
        """

        veri_link = msg.verification_link()

        return PMMail(api_key=settings.POSTMARK_API_KEY,
                      sender=cls.SENDER_EMAIL,
                      to=user.email,
                      subject='Re: ' + msg.subject,
                      html_body=render_without_request(
                          "emails/validate_user.html",
                          context={
                              'verification_link': veri_link,
                              'user': user
                          }),
                      track_opens=True,
                      custom_headers={
                          'In-Reply-To': msg.email_uid,
                          'References': msg.email_uid,
                      })
Exemplo n.º 47
0
def flag():

    sid = request.form.get('submission', None)

    if sid:
        submission = submission_lookup(sid)
        if 'ok' in request.args:
            submission['flagged'] = False
            submission['removed'] = False
            submission['approved'] = True
        elif 'remove' in request.args:
            submission['flagged'] = True
            submission['removed'] = True
            submission['approved'] = False
        elif not submission.get('approved', False):
            submission['flagged'] = True

            body = """http://sunlightcam.com/browse?flagged\n\n"""
            body += "\n".join("%s: %s" % (k, submission[k])
                              for k in sorted(submission.keys()))

            PMMail(
                api_key=settings.POSTMARK_KEY,
                to='*****@*****.**',
                sender='*****@*****.**',
                subject='[SunlightCAM] new flagged submission',
                text_body=body,
            ).send()

        g.db.submissions.save(submission)

    return Response("{}", mimetype="application/json")
Exemplo n.º 48
0
    def test_inline_attachments(self):
        image = MIMEImage(b'image_file', 'png', name='image.png')
        image_with_id = MIMEImage(b'inline_image_file', 'png', name='image_with_id.png')
        image_with_id.add_header('Content-ID', '<*****@*****.**>')
        inline_image = MIMEImage(b'inline_image_file', 'png', name='inline_image.png')
        inline_image.add_header('Content-ID', '<*****@*****.**>')
        inline_image.add_header('Content-Disposition', 'inline', filename='inline_image.png')

        expected = [
            {'Name': 'TextFile', 'Content': 'content', 'ContentType': 'text/plain'},
            {'Name': 'InlineImage', 'Content': 'image_content', 'ContentType': 'image/png', 'ContentID': 'cid:[email protected]'},
            {'Name': 'image.png', 'Content': 'aW1hZ2VfZmlsZQ==', 'ContentType': 'image/png'},
            {'Name': 'image_with_id.png', 'Content': 'aW5saW5lX2ltYWdlX2ZpbGU=', 'ContentType': 'image/png', 'ContentID': '*****@*****.**'},
            {'Name': 'inline_image.png', 'Content': 'aW5saW5lX2ltYWdlX2ZpbGU=', 'ContentType': 'image/png', 'ContentID': 'cid:[email protected]'},
        ]
        json_message = PMMail(
            sender='*****@*****.**', to='*****@*****.**', subject='Subject', text_body='Body', api_key='test',
            attachments=[
                ('TextFile', 'content', 'text/plain'),
                ('InlineImage', 'image_content', 'image/png', 'cid:[email protected]'),
                image,
                image_with_id,
                inline_image,
            ]
        ).to_json_message()
        assert len(json_message['Attachments']) == len(expected)
        for orig, attachment in zip(expected, json_message['Attachments']):
            for k, v in orig.items():
                assert orig[k] == attachment[k].rstrip()
Exemplo n.º 49
0
def contact(request):

    if request.method == "POST":

        form = ContactForm(request.POST)

        if form.is_valid():

            name = form.cleaned_data['name']
            from_email = form.cleaned_data['from_email']
            message = "%s <%s> wrote:\n\n%s" % (name, from_email,
                                                form.cleaned_data['message'])

            PMMail(
                to='*****@*****.**',
                reply_to="%s <%s>" % (name, from_email),
                subject="[SunlightFoundation.com] message from %s" % name,
                text_body=message,
            ).send()

            messages.success(
                request,
                'Thank you for contacting us! We will get back to you shortly.'
            )
            return HttpResponseRedirect("/contact/")

    else:

        form = ContactForm()

    return render_to_response("contact/form.html", {"form": form},
                              context_instance=RequestContext(request))
Exemplo n.º 50
0
def deliver_postmark(args, email):
    if not os.environ.get('POSTMARK_API_TOKEN'):
        sys.exit("Missing POSTMARK_API_TOKEN variable")

    message = PMMail(
        api_key=os.environ.get('POSTMARK_API_TOKEN'),
        subject=email['subject'],
        sender=email['sender'],
        to=email['to'],
        text_body=email['text_body'],
        html_body=email['html_body'],
        tag="slack_digest",
        custom_headers=email["custom_headers"],
    )

    message.send()
Exemplo n.º 51
0
    def test_500_error_server_error(self):
        message = PMMail(sender='*****@*****.**', to='*****@*****.**',
            subject='Subject', text_body='Body', api_key='test')

        with mock.patch('postmark.core.urlopen', side_effect=HTTPError('',
            500, '', {}, None)):
            self.assertRaises(PMMailServerErrorException, message.send)
Exemplo n.º 52
0
    def send_email_confirmation(email_addr, token):
        subject = "Caseworx Beta Confirmation"
        to = email_addr

        html_email = get_template('email_confirmation.html')

        d = Context({'confirmation_code': token})
        body = html_email.render(d)

        message = PMMail(api_key=os.environ.get('POSTMARK_API_KEY'),
                         subject=subject,
                         sender=os.environ.get('POSTMARK_SENDER'),
                         to=to,
                         html_body=body,
                         tag="hello")
        message.send()
Exemplo n.º 53
0
 def test_check_values_bad_template_data(self):
     # Try sending with template ID only
     message = PMMail(api_key='test', sender='*****@*****.**', to='*****@*****.**', template_id=1)
     self.assert_missing_value_exception(
         message.send,
         'Cannot send a template e-mail without a both template_id and template_model set'
     )
Exemplo n.º 54
0
def register(request):
    if request.POST.has_key('requestcode'):
        if not grecapcha_verify(request):
            context = {'message', 'سلام کد یا کلید یا تشخیص عکس زیر درست پر کنید ببخشید که فرم به شکل اولیه برنگشته'}
            return render(request, 'register.html', context)

        if User.objects.filter(email = request.POST['email']).exists():
            context = {'message', 'ببخشید که فرم ذخیره نمیشه درست میشه'}
            return render(request, 'register.html', context)

        if User.objects.filter(username = request.POST['username']).exists():
            code = random_str(28)
            now = datetime.now()
            email = request.POST['email']
            password = make_password(request.POST['password'])
            username = request.POST['username']
            temporarycode = Passwordresetcodes(email = email, time = now, code = code ,username = username, password = password)
            temporarycode.save()
            message = PMMail(api_key = settings.POSTMark_API_TOKEN,
                             subject = 'برای فعال سازی به لینک زیر مراجعه کنید http://www.hadirasool.tk/accounts/register?email={}&code={}'.format(email, code),
                             sender = '*****@*****.**',
                             to = email,
                             text_body = 'ایمیل تودو خود را در لینک زیر کلیک کنی',
                             tag = 'create account')
            message.send()
            context = {'message': 'لطفا پس از چک کردن ایمیل روی لینک زیر کلیک کنید'}
            return render(request, 'login.html', context)
        else:
            context = {'message','از نام کاربری دیگری استفاده کنید.ببخشید که فرم ذخیره نشده.درست میشه'}
            return render(request, 'register.html', context)
    elif request.GET.has_key('code'):
        email = request.GET['email']
        code = request.GET['code']
        if Passwordresetcodes.objects.filter(code=code).exists():
            new_temp_user = Passwordresetcodes.objects.get(code=code)
            newuser = User.objects.create(username=new_temp_user.username, password=new_temp_user.password, email=email)
            this_token = random_str(48)
            token = Token.objects.create(user=newuser, token=this_token)
            Passwordresetcodes.objects.filter(code=code).delete()
            context = {'message', 'اکانت شما فعال شد توکن شما {} است آن را ذخیره کنید چون نمایش داده نخواهد شد'.format(this_token)}
            return render(request, 'login.html', context)
        else:
            context = {'message', 'فعال سازی معتبر نیست در صورت نیاز دبار تلاش کنید'}
            return render(request, 'login.html', context)
    else:
        context = {'message': ''}
        return render(request, 'register.html', context)
Exemplo n.º 55
0
def send_postmark(to="", bcc="", subject="", plaintext=""):
    """
    Send an email via Postmark. Used when the application is deployed on
    Heroku.
    """
    try:
        message = PMMail(api_key = conf.POSTMARK_API_KEY,
                        subject = subject,
                        sender = conf.NOTIFICATION_EMAIL,
                        text_body = plaintext)
        message.to = to
        if bcc != "":
            message.bcc = bcc
        message.send()
    except Exception as e:
        logger.exception("send_postmark raised:")
        raise e
Exemplo n.º 56
0
Arquivo: web.py Projeto: dmc2015/mpt
def contact():
    if request.method == 'POST':
        # different dropdowns -> mail for different people
        mail_to = {
            "data": os.environ.get('DATA_RECIPIENT', GENERIC_RECIPIENT),
            "casestudies": os.environ.get('CASESTUDIES_RECIPIENT', GENERIC_RECIPIENT),
            "declaration": os.environ.get('DECLARATION_RECIPIENT', GENERIC_RECIPIENT),
            "resources": os.environ.get('RESOURCES_RECIPIENT', GENERIC_RECIPIENT),
            "other": os.environ.get('OTHER_RECIPIENT', GENERIC_RECIPIENT)
        }[request.form.get('issue').lower()]

        addr = request.form.get('email')
        msg = request.form.get('message')

        if msg and addr and '@' in addr:
            mail = PMMail(api_key=POSTMARK_API_KEY, sender=POSTMARK_SENDER)
            mail.subject = '[MPT] contact from %s' % addr
            mail.to = mail_to
            mail.reply_to = addr
            mail.text_body = msg
            mail.send()

        return redirect('/thanks')

    return render_template('contact.html')
Exemplo n.º 57
0
def send_error_email(job, error):

	if job.email_result:

		email_body = 'There was an error processing your job:\n'
		email_body += str(error)
		email_body += '\n\nPlease try again.'

		email_subject = 'Error running Salesforce Org Compare job.'

		#send_mail('Your Org Compare Results', email_body, '*****@*****.**', [job.email], fail_silently=False)
		message = PMMail(api_key = os.environ.get('POSTMARK_API_KEY'),
				subject = email_subject,
	            sender = "*****@*****.**",
	            to = job.email,
	            text_body = email_body,
	            tag = "orgcompareemail")
		message.send()
Exemplo n.º 58
0
def contact(request):
    if request.method == 'POST':
        form = ContactForm(request.POST, label_suffix="")
        if form.is_valid():
            data = form.cleaned_data
            mailmsg = PMMail(
                subject='[PublicMarkup.org] contact from %s' % data['name'],
                text_body='%s <%s>\n\n%s' % (data['name'], data['email'], data['comment']),
                sender=settings.POSTMARK_SENDER,
                to=settings.POSTMARK_SENDER,
                reply_to=data['email'],
            )
            mailmsg.send()
            messages.success(request, "Thanks for contacting us. We'll get back to you shortly.")
            return HttpResponseRedirect('/')
    else:
        form = ContactForm(label_suffix="")
    return render_to_response("contact.html", {'form': form}, context_instance=RequestContext(request))