def handle_inbound_unsolicited(mail): '''Mail that arrives at this view was sent directly to [email protected] without an id (like [email protected]). In response, we'll send a generic "Hi! What are you doing?" email. ''' # Create the reply-to address. if settings.POSTMARK_MX_FORWARDING_ENABLED: inbound_host = settings.EARWIG_INBOUND_EMAIL_HOST else: inbound_host = settings.POSTMARK_INBOUND_HOST reply_to_tmpl = '{0.POSTMARK_INBOUND_HASH}@{1}' reply_to = reply_to_tmpl.format(settings, inbound_host) subject_tmpl = 'plugins/default/email/unsolicited/subject.txt' body_text_tmpl = 'plugins/default/email/unsolicited/body.txt' body_html_tmpl = 'plugins/default/email/unsolicited/body.html' message = pystmark.Message( sender=settings.EARWIG_EMAIL_SENDER, reply_to=reply_to, to=mail['FromFull']['Email'], subject=render_to_string(subject_tmpl, {}), text=render_to_string(body_text_tmpl, {}), html=render_to_string(body_html_tmpl, {})) pystmark.send(message, settings.POSTMARK_API_KEY) return HttpResponse()
def send_email(from_email, subject, message): # Send a single message message = pystmark.Message(sender=os.environ.get('DEFAULT_FROM_EMAIL'), to=os.environ.get('PERSONAL_EMAIL'), subject=subject, text=message) pystmark.send(message, api_key=os.environ.get('POSTMARK_API_KEY'))
def send_email(email, subject, body): # Send a single message message = pystmark.Message(sender=config.SENDER_EMAIL, to=email, subject=subject, text=body) pystmark.send(message, api_key=config.POSTMARKAPP_API_KEY)
def send_email(to, subject, body_text=None, body_html=None): # Send a single message message = pystmark.Message(sender=config.EMAIL_SENDER, to=to, subject=subject, text=body_text, html=body_html) pystmark.send(message, api_key=config.POSTMARKAPP_API_KEY)
def send_email(from_email, subject, body): subject = '[kateheddleston.com] ' + subject body = "\n This email was sent by {}\n\n".format(from_email) + body # Send a single message message = pystmark.Message(sender=config.SENDER_EMAIL, to=config.PERSONAL_EMAIL, subject=subject, text=body) pystmark.send(message, api_key=config.POSTMARKAPP_API_KEY)
def test_send_with_unicode(self, mock_request): test_text = u'Hi Jos\xe9' mock_request.return_value = self.mock_response(self.json_response) message = pystmark.Message(sender='*****@*****.**', text=test_text, to='*****@*****.**') pystmark.send(message, api_key=POSTMARK_API_TEST_KEY) request_data = mock_request.mock_calls[0][2]['data'] str(request_data) # ssl lib will convert to str self.assertEqual(json.loads(request_data)['TextBody'], test_text)
def send_mail(to, subject, text, sender=constants.MAILER_FROM): if constants.ENVIRONMENT == 'test': logging.warn( 'Skipping sending mail to {} due to ENVIRONMENT == test'.format( to)) return message = pystmark.Message(sender=sender, to=to, subject=subject, text=text) pystmark.send(message, api_key=constants.MAILER_POSTMARK_API_KEY) logging.info('Send mail to {} with subject `{}`'.format(to, subject))
def test_send_with_attachments(self, mock_request): mock_request.return_value = self.mock_response(self.json_response) message = pystmark.Message(sender='*****@*****.**', text='hi', to='*****@*****.**') message.attach_binary(urandom(64), 'test.pdf') r = pystmark.send(message, api_key=POSTMARK_API_TEST_KEY) self.assertValidJSONResponse(r, self.response)
def send(self): pm = pystmark.Message(sender=self._sender if self._sender else settings.POSTMARK_SENDER, to=self._to, subject=self._subject, text=self._text, html=self._html) res = pystmark.send(pm, api_key=settings.POSTMARK_API_KEY) res.raise_for_status()
def send_message(self, attempt, debug=False): contact_detail = attempt.contact self.check_contact_detail(contact_detail) recipient_email_address = contact_detail.value ctx = dict( attempt=attempt, login_url=getattr(settings, 'LOGIN_URL', 'PUT REAL LOGIN URL HERE')) path = 'plugins/default/email/body.html' body_html = self.render_template(path, **ctx) path = 'plugins/default/email/body.txt' body_txt = self.render_template(path, **ctx) path = 'plugins/default/email/subject.txt' subject = self.render_template(path, **ctx) message = attempt.messages.get() reply_to = self.get_reply_to(message) message = pystmark.Message( sender=settings.EARWIG_EMAIL_SENDER, reply_to=reply_to, to=recipient_email_address, subject=subject, text=body_txt, html=body_html) api_key = getattr(settings, 'POSTMARK_API_KEY', None) response = pystmark.send(message, api_key) resp_json = response.json() message_id = resp_json.get('MessageID') if message_id is None: attempt.mark_attempted( status=DeliveryStatus.invalid, plugin='postmark', template='default') return meta = PostmarkDeliveryMeta.objects.create( attempt=attempt, message_id=message_id) # Mark the attempt sent. attempt.mark_attempted( status=DeliveryStatus.sent, plugin='postmark', template='default') if debug: return { "text": body_txt, "html": body_html, "subject": subject, "obj": meta }
def test_send_with_attachments_content_id(self, mock_request): content_id = 'cid:%[email protected]' % (uuid.uuid4()) mock_request.return_value = self.mock_response(self.json_response) message = pystmark.Message(sender='*****@*****.**', text='hi', to='*****@*****.**') message.attach_binary(urandom(64), 'test.pdf', content_type='image/png', content_id=content_id) r = pystmark.send(message, api_key=POSTMARK_API_TEST_KEY) self.assertValidJSONResponse(r, self.response)
def handle_inbound_unsolicited(mail): '''Mail that arrives at this view was sent directly to [email protected] without an id (like [email protected]). In response, we'll send a generic "Hi! What are you doing?" email. ''' reply_to = get_reply_to_address() subject_tmpl = 'plugins/default/email/unsolicited/subject.txt' body_text_tmpl = 'plugins/default/email/unsolicited/body.txt' body_html_tmpl = 'plugins/default/email/unsolicited/body.html' message = pystmark.Message( sender=settings.EARWIG_EMAIL_SENDER, reply_to=reply_to, to=mail['FromFull']['Email'], subject=render_to_string(subject_tmpl, {}), text=render_to_string(body_text_tmpl, {}), html=render_to_string(body_html_tmpl, {})) pystmark.send(message, settings.POSTMARK_API_KEY) return HttpResponse()
def handle_inbound_stranger_reply(mail): '''Mail that arrives at this view was contained a valid MessageRecipient id as the MailboxHash, but wasn't from the original sender or any of the email accounts on file for the original recipient. This view sends a reply telling the person we couldn't deliver the message. ''' reply_to = get_reply_to_address() subject_tmpl = 'plugins/default/email/stranger_reply/subject.txt' body_text_tmpl = 'plugins/default/email/stranger_reply/body.txt' body_html_tmpl = 'plugins/default/email/stranger_reply/body.html' message = pystmark.Message( sender=settings.EARWIG_EMAIL_SENDER, reply_to=reply_to, to=mail['FromFull']['Email'], subject=render_to_string(subject_tmpl, {}), text=render_to_string(body_text_tmpl, {}), html=render_to_string(body_html_tmpl, {})) pystmark.send(message, settings.POSTMARK_API_KEY) return HttpResponse()
def send_email(self, message, subject): message = message.decode('utf-8', errors="ignore") msg = pystmark.Message(sender=self.email_from, to=self.email_to, subject=subject, html=message, tag="daily-twitter-digest") response = pystmark.send(msg, api_key=self.postmark_api_key) try: response.raise_for_status() except Exception as e: print e.message
def send_email(self): outdateds = self.get_outdated_requirements() if outdateds: html = render_template('email.html', reqs=outdateds) message = pystmark.Message( sender='*****@*****.**', to=self.email, subject="There are updated packages in PyPI", html=html) response = pystmark.send(message, current_app.config['POSTMARK_APIKEY']) response.raise_for_status() else: logger.info("No outdated requirement.")
def _send_email(tupl): subject, message = tupl c = yaml.safe_load(open('../postmark.yml')) """ a decorator to send an email """ msg = pystmark.Message(sender=c['from'], to=c['to'], subject=subject, html=message, tag="tests") response = pystmark.send(msg, api_key=c['api_key']) try: response.raise_for_status() except Exception as e: print e.message
def send(self, to, reply_to, subject, body_txt, body_html): '''Send an email using stock earwig sender, reply-to addresses. ''' message = pystmark.Message( sender=settings.EARWIG_EMAIL_SENDER, reply_to=reply_to, to=to, subject=subject, text=body_txt, html=body_html) api_key = getattr(settings, 'POSTMARK_API_KEY', None) response = pystmark.send(message, api_key) resp_json = response.json() return resp_json
def email_pdf(request): if request.method == 'POST': try: data = json.loads(request.body) except ValueError: return HttpResponseBadRequest("No JSON provided") try: msubject = data['Subject'] mfrom = data['From'] mbody = data['TextBody'] except KeyError: return HttpResponseBadRequest("Invalid JSON") # Now let's create the pdf try: styling = Stationary.objects.get(name__icontains='msubject').styling except ObjectDoesNotExist: styling = '' rendered_html = render_to_string('documanager/print_render.html', {'html':mbody, 'styling':styling}) pdf_file = generate_pdf(html=rendered_html) PM_API_KEY = getattr(settings, "PM_API_KEY", None) PM_SENDER = getattr(settings, "PM_SENDER", None) message = pystmark.Message(sender=PM_SENDER, to=mfrom, subject = 'Hi', text = 'Your email should (not yet) be attached', tag = 'greeting') pystmark.send(message, api_key=PM_API_KEY) return HttpResponse("Success!") else: return HttpResponseNotAllowed(['POST'])
def send_mail(to, subject, text, attachment=None, attachment_name=''): message = pystmark.Message( sender=env('MAIL_FROM'), to=to, subject=subject, text=text, ) if attachment is not None: message.attach_binary(attachment.read(), attachment_name) result = pystmark.send(message, api_key=env('POSTMARK_API_KEY')) result.raise_for_status() return result
def send_pdf_by_mail(exp, force=False): import pystmark from django.conf import settings from django.core.files.storage import default_storage as storage if not exp.subject.send_to: logger.info("The user di not allow to send e-mail at {}".format(exp.subject.mail)) return False if exp.subject.sent is not None and not force: logger.info("Mail already sent to the recipient {}".format(exp.subject.mail)) return False try: message = pystmark.Message(sender=settings.POSTMASTER['sender'], to=exp.subject.mail, subject='FoodCAST Neuroscience Experiment result', text='Dear {},\nwe\'re happy to send you the resuts for the experiment you took part in WiredNext 2014 at the FoodCAST stand.\n\nBest regard,\nThe FoodCAST Team'.format(exp.subject.name)) # Attach using filename fh = storage.open(exp.pdf_file.name, "r") message.attach_binary(fh.read(), exp.pdf_file.name.split("/")[-1]) pystmark.send(message, api_key=settings.POSTMASTER['key']) logger.info("Mail sent to the recipient {}".format(exp.subject.mail)) fh.close() return True except Exception as e: raise
def share_contact(request): global session_manager session_id = request.GET.get("sessionId") user = request.GET.get("user") now,heartbeats,profiles = session_manager.heartbeat(session_id,user) user_profile = None peer_profile = None print "Going to search within these profiles: %s using this user: %s" % (profiles, user) for profile in profiles.values(): if profile['profile_id'] == long(user): user_profile = profile else: peer_profile = profile if user_profile == None or peer_profile == None: return HttpResponse( json.dumps({ 'successful':False, 'reason': 'Failed to find one of the profiles.' }), content_type="application/json") from_email = user_profile['email'] from_name = user_profile['name'] to_email = peer_profile['email'] to_name = peer_profile['name'] message = pystmark.Message( sender=settings.POSTMARK_SENDER, to=to_email, reply_to=from_email, subject='%s wants to connect with you' % from_name, text=format_email_body(to_name, from_name, from_email)) email_response = pystmark.send(message, api_key=settings.POSTMARK_API_KEY) successful = True if email_response.ok else False return HttpResponse( json.dumps({ 'successful':successful, 'reason': ('' if successful else email_response.text) }), content_type="application/json")
def send(self, params): message_key = params["message_key"] email_data = params["email_data"] to_email = params["email_to"] subject_email = params["email_subject"] message_tag = params["message_tag"] email_text = email_message.message[message_key] email_return = templating.Templating.render(email_text, email_data) message = pystmark.Message(sender=config.G_POSTMARK_API_SENDER_EMAIL, to=to_email, subject=subject_email, tag=message_tag, html=email_return) message.track_opens = True response = pystmark.send(message, api_key=config.G_POSTMARK_API_SERVER_TOKEN) # we have to check for failed to send emails and log them json_response = response._data print json_response
def test_simple_api(self, mock_request): mock_request.return_value = self.mock_response(self.json_response) r = pystmark.send(self.message, test=True) self.assertValidJSONResponse(r, self.response)
def suggestCallScriptApi(): try: newCallScript = request.get_json() if not request.userId or 'g-recaptcha-response' in newCallScript: if 'g-recaptcha-response' not in newCallScript: raise Exception("No recaptcha response! Are you a robot!?") captchaResult = requests.post( "https://www.google.com/recaptcha/api/siteverify", params={ 'secret': app.config['GOOGLE_RECAPTCHA_SECRET'], 'response': newCallScript['g-recaptcha-response'], 'remoteip': request.remote_addr }, headers={ 'Referer': app.config['BASE_URL'], }) if captchaResult.status_code != 200: raise Exception("Exception running captcha verification") captchaResultObj = captchaResult.json() if captchaResultObj['success'] == False: errorCodes = captchaResultObj.get("error-codes", "Unknown error") raise Exception( "Exception running captcha verification: {}".format( errorCodes)) del newCallScript['g-recaptcha-response'] jsonschema.validate(newCallScript, callScriptSchema) newCallScript['approved'] = False newCallScript['approvalCode'] = str(ObjectId()) res = putCallScript(request.get_json(), True) campaignDoc = mongo.db.campaigns.find_one( {'_id': ObjectId(newCallScript['campaign'])}) adminsCursor = mongo.db.users.find( {'_id': { '$in': campaignDoc['owners'] }}) approvalLink = "{0}/api/approveCallScript?approval={1}".format( app.config['BASE_URL'], newCallScript['approvalCode']) emailText = """<p>A new call script has been submitted to your campaign!</p> <p>You can approve this call script by going here <a href="{0}">{0}</a></p>. <p><strong>Title:</strong> {}</p> <p><strong>Blurb:</strong> {}</p> <p><strong>Applies To:</strong> {}</p> <p><strong>Text:</strong> {}</p> <p><strong>Tags:</strong> {}</p> <p><strong>Submitted By:</strong> {}</p> """.format(approvalLink, newCallScript['title'], newCallScript['blurb'], ', '.join(newCallScript['appliesTo']), newCallScript['text'], ', '.join(newCallScript.get('tags', [])), newCallScript.get('submittedBy', '')) for admin in adminsCursor: message = pystmark.Message(sender='*****@*****.**', to=admin['email'], subject='New Suggested Call Script', html=emailText) pystmark.send(message, api_key=app.config['POSTMARK_API_KEY']) return json.dumps({'status': 'OK', 'result': 'Submitted!'}) except Exception as e: return json.dumps({'status': 'FAIL', 'error_message': str(e)})