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)
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))
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, })
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 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, })
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()
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()
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")
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()
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)
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 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' )
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()
def test_missing_subject(self): # No subject should raise exception when using send() message = PMMail(sender="*****@*****.**", to="*****@*****.**", text_body="Body", api_key="test") self.assert_missing_value_exception( message.send, "Cannot send an e-mail without a subject")
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()
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)
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()
def test_missing_recipient_fields(self): # No recipient should raise exception when using send() message = PMMail(sender='*****@*****.**', subject='test', text_body='Body', api_key='test') self.assert_missing_value_exception( message.send, 'Cannot send an e-mail without at least one recipient (.to field or .bcc field)' )
def test_missing_subject(self): # No subject should raise exception when using send() message = PMMail(sender='*****@*****.**', to='*****@*****.**', text_body='Body', api_key='test') self.assert_missing_value_exception( message.send, 'Cannot send an e-mail without a subject')
def send_mail(subject, text_body, tag="favor8"): ''' Send an email with analytics event ''' message = PMMail(api_key=POSTMARK_API_TOKEN, subject=subject, sender="*****@*****.**", to="*****@*****.**", text_body=text_body, tag=tag)
def send(self): body = """%s <%s>\n\n%s""" % (self.name.data, self.email.data, self.comments.data) PMMail( api_key=settings.POSTMARK_KEY, to='*****@*****.**', sender='*****@*****.**', subject='[SunlightCAM] contact form submission', text_body=body, ).send()
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()
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()
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()
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()
def test_missing_recipient_fields(self): # No recipient should raise exception when using send() message = PMMail(sender="*****@*****.**", subject="test", text_body="Body", api_key="test") self.assert_missing_value_exception( message.send, "Cannot send an e-mail without at least one recipient (.to field or .bcc field)", )
def test_check_values_bad_template_data_alias(self): # Try sending with template ID only message = PMMail(api_key="test", sender="*****@*****.**", to="*****@*****.**", template_alias="alias") self.assert_missing_value_exception( message.send, "Cannot send a template e-mail without a both template_id and template_model set", )
def test_422_error_unprocessable_entity(self): json_payload = BytesIO() json_payload.write(b'{"Message": "", "ErrorCode": 422}') json_payload.seek(0) message = PMMail(sender='*****@*****.**', to='*****@*****.**', subject='Subject', text_body='Body', api_key='test') with mock.patch('postmark.core.urlopen', side_effect=HTTPError('', 422, '', {}, json_payload)): self.assertRaises(PMMailUnprocessableEntityException, message.send)
def send_emails(watches, page): for watch in watches: logger.info("Sending email to %s for url %s" % (watch.email, page.url)) PMMail(api_key=settings.POSTMARK_API_TOKEN, subject="The VA Bar Results have been released!!", sender=settings.POSTMARK_SENDER_EMAIL, to=watch.email, text_body="Click here to see the bar results: %s" % page.url, html_body="Click <a href='%s'>here</a> to see the bar results" % page.url).send() watch.triggered = True watch.save()
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)