def send_email(self, recipients, subject, text, html=None, from_email=None): """ recipients can be passed as single email (string) or list of emails. """ if from_email is None: from_email = settings.SPARKPOST_FROM_EMAIL if isinstance(recipients, str): recipients = [recipients] sparky = SparkPost(self.api_key) data = { 'from_email': from_email, 'recipients': recipients, 'subject': subject, 'text': text } if html: data['html'] = html return sparky.transmissions.send(**data)
def test_failure_create_sending_domain_with_dkim(): with pytest.raises(ValueError): sp = SparkPost('fake-key') results = sp.sending_domains.create('example1.com', dkim_private='foo', dkim_public='bar', generate_dkim=False)
def __init__(self, fail_silently=False, **kwargs): super(SparkPostEmailBackend, self)\ .__init__(fail_silently=fail_silently, **kwargs) sp_api_key = getattr(settings, 'SPARKPOST_API_KEY', None) self.client = SparkPost(sp_api_key)
def __init__(self, **kwargs): """Init options from Django settings""" super(EmailBackend, self).__init__(**kwargs) # SPARKPOST_API_KEY is optional - library reads from env by default self.api_key = get_anymail_setting('api_key', esp_name=self.esp_name, kwargs=kwargs, allow_bare=True, default=None) # SPARKPOST_API_URL is optional - default is set by library; # if provided, must be a full SparkPost API endpoint, including "/v1" if appropriate api_url = get_anymail_setting('api_url', esp_name=self.esp_name, kwargs=kwargs, default=None) extra_sparkpost_params = {} if api_url is not None: if api_url.endswith("/"): api_url = api_url[:-1] extra_sparkpost_params['base_uri'] = _FullSparkPostEndpoint( api_url) try: self.sp = SparkPost( self.api_key, **extra_sparkpost_params) # SparkPost API instance except SparkPostException as err: # This is almost certainly a missing API key raise AnymailConfigurationError( "Error initializing SparkPost: %s\n" "You may need to set ANYMAIL = {'SPARKPOST_API_KEY': ...} " "or ANYMAIL_SPARKPOST_API_KEY in your Django settings, " "or SPARKPOST_API_KEY in your environment." % str(err))
def email_post(request): try: email_address = os.environ.get('EMAIL_ADDRESS') body = request.get_json() if body['metadata']['type'] == 'balance': accountName = body['account']['name'] subject = 'Balance Notification for {}'.format(accountName) elif body['metadata']['type'] == 'transaction': accountName = body['item']['accountName'] subject = 'Transaction Notification for {}'.format(accountName) email_text = pprint.pformat(body) sp = SparkPost(SPARKPOST_API_KEY) try: sp.transmissions.send( recipients=[email_address], text=email_text, from_email='Auditor <*****@*****.**>', subject=subject, track_opens=False, track_clicks=False, ) except SparkPostAPIException as err: print( "Error sending email through sparkpost. Got status {} and errors {}" .format(err.status, err.errors)) raise except Exception: traceback.print_exc() return 'Error', 500
def test_success_list_tracking_domains_subaccounts(): responses.add( responses.GET, 'https://api.sparkpost.com/api/v1/tracking-domains?subaccounts=foo,bar', status=200, content_type='application/json', match_querystring=True, body="""{ "results": [ { "port": 80, "domain": "example2.domain.com", "secure": false, "default": false, "status": { "verified": true, "cname_status": "valid", "compliance_status": "valid" }, "subaccount_id": 215 } ] }""") sp = SparkPost('fake-key') results = sp.tracking_domains.list(subaccounts=['foo', 'bar']) assert len(results) == 1 assert results[0]['domain'] == 'example2.domain.com'
def emailReport(os_command, err): """ Emails success or failure with a given SMTP defined by the credentials file keyword arguments: os_command -- The command found and to be executed err -- boolean value which indicates if the command was successful """ recipients = [obj.creds['To']] from_email = obj.creds['From'] if err is not None: body = '<html><body><p>A command:\n' + os_command + \ '\nwas unsuccessful:\nError: '+err + '</p></body></html' else: body = '<html><body><p>A command:\n' + os_command + \ '\nsent successfully </p></body></html>' subject = obj.creds['Subject'] """send message via our own SMTP server""" sparkykey = obj.creds['SPARKPOST_APIKEY'] sparky = SparkPost(sparkykey) response = sparky.transmission.send(recipients=recipients, html=body, from_email=from_email, subject=subject)
def form_valid(self, form): submission = form.save() email = SparkPost(settings.SPARKPOST_API_KEY) sub_data = { 'name': form.cleaned_data['name'], 'email_address': form.cleaned_data['email_address'], 'idea_description': form.cleaned_data['idea_description'], } if form.cleaned_data['idea_needs']: sub_data['idea_needs'] = form.cleaned_data['idea_needs'] if form.cleaned_data['idea_resources']: sub_data['idea_resources'] = form.cleaned_data['idea_resources'] if form.cleaned_data['attended_event']: sub_data['attended_event'] = 'yes' if form.cleaned_data['staffed_event']: sub_data['staffed_event'] = 'yes' if form.cleaned_data['contact_me']: sub_data['contact_me'] = 'yes' if form.cleaned_data['slack_invite']: sub_data['slack_invite'] = 'yes' email.transmissions.send( recipients=[form.cleaned_data['email_address']], template='maglabs-test-chamber-submission-acknowledge', substitution_data=sub_data) email.transmissions.send( recipient_list='maglabs-research-team', template='maglabs-test-chamber-submission-notification', substitution_data=sub_data) return super(CreateTestChamberApplicationView, self).form_valid(form)
def send(self, message=None): """Sends the message through the Sparkpost service. Keyword Arguments: message {string} -- The message to be sent to Sparkpost. (default: {None}) Returns: requests.post -- Returns the response as a requests object. """ try: from sparkpost import SparkPost except ImportError: raise DriverLibraryNotFound( 'Could not find the "sparkpost" library. Please pip install this library ' 'by running "pip install sparkpost"') if not message: message = self.message_body sp = SparkPost(api_key=self.config.DRIVERS['sparkpost']['api_key']) response = sp.transmissions.send(use_sandbox=self._sandbox_mode(), recipients=[self.to_address], html=message, from_email='{0} <{1}>'.format( self.config.FROM['name'], self.config.FROM['address']), subject=self.message_subject) return response
def test_success_get_sending_domain(): responses.add( responses.GET, 'https://api.sparkpost.com/api/v1/sending-domains/example1.com', status=200, content_type='application/json', body="""{ "results": { "tracking_domain": "click.example1.com", "status": { "ownership_verified": false, "spf_status": "unverified", "abuse_at_status": "unverified", "dkim_status": "unverified", "cname_status": "unverified", "mx_status": "pending", "compliance_status": "pending", "postmaster_at_status": "unverified", "verification_mailbox_status": "unverified" }, "dkim": { "headers": "from:to:subject:date", "public": "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC+W6scd3XWwvC/hPRksfDYFi3ztgyS9OSqnnjtNQeDdTSD1DRx/xFar2wjmzxp2+SnJ5pspaF77VZveN3P/HVmXZVghr3asoV9WBx/uW1nDIUxU35L4juXiTwsMAbgMyh3NqIKTNKyMDy4P8vpEhtH1iv/BrwMdBjHDVCycB8WnwIDAQAB", "selector": "hello_selector" }, "shared_with_subaccounts": false, "is_default_bounce_domain": false } }""") sp = SparkPost('fake-key') result = sp.sending_domains.get('example1.com') assert result is not None
def send_email(subject, message, user, email_admins=True): ''' Params: `user`: WHMCSclients model record `subject`: email subject `message`: email body contents `email_admins`: prevents spam to admins ''' html_template = ''' <html> <head> <title>%s</title> </head> <body> %s </body> </html> ''' html = html_template % (subject, message) if not app.config.get('TESTING'): # only send email to admins if it's a pending request if email_admins: email_addresses = [app.config['ADMIN_EMAIL']] else: email_addresses = [user.email] if email_addresses: sp = SparkPost(app.config['SPARKPOST_API_KEY']) sp.transmissions.send( from_email=app.config['ADMIN_EMAIL'], subject=subject, recipients=email_addresses, html=html )
def test_success_list_ip_pools(): responses.add(responses.GET, "https://api.sparkpost.com/api/v1/ip-pools", status=200, content_type="application/json", body="""{ "results": [ { "id": "marketing_ip_pool", "name": "Marketing IP Pool", "ips": [], "signing_domain": "example.com", "fbl_signing_domain": "sparkpostmail.com", "auto_warmup_overflow_pool": "overflow_pool" }, { "id": "default", "name": "Default", "ips": [ { "external_ip": "54.244.54.135", "hostname": "mta472a.sparkpostmail.com", "auto_warmup_enabled": true, "auto_warmup_stage": 5 } ] } ] }""") sp = SparkPost("fake-key") results = sp.ip_pools.list() assert len(results) == 2 assert results[0]["id"] == "marketing_ip_pool"
def test_success_create_sending_domain_with_dkim(): responses.add(responses.POST, 'https://api.sparkpost.com/api/v1/sending-domains', status=200, content_type='application/json', body="""{ "results": { "message": "Successfully Created domain.", "domain": "example1.com", "dkim": { "public": "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC+W6scd3XWwvC/hPRksfDYFi3ztgyS9OSqnnjtNQeDdTSD1DRx/xFar2wjmzxp2+SnJ5pspaF77VZveN3P/HVmXZVghr3asoV9WBx/uW1nDIUxU35L4juXiTwsMAbgMyh3NqIKTNKyMDy4P8vpEhtH1iv/BrwMdBjHDVCycB8WnwIDAQAB", "selector": "scph0316", "signing_domain": "example1.com", "headers": "from:to:subject:date" } } }""") sp = SparkPost('fake-key') results = sp.sending_domains.create('example1.com', dkim_private='foo', dkim_public='bar', dkim_selector='baz', generate_dkim=False) assert results is not None assert results['domain'] == 'example1.com'
def send_email(token_id, user, domain): try: sparkpost = SparkPost() default_app_name = "INFOSYSTEM" default_email_use_sandbox = False default_reset_url = 'http://objetorelacional.com.br/#/reset' default_noreply_email = '*****@*****.**' default_email_subject = 'INFOSYSTEM - CONFIRMAR email e CRIAR senha' infosystem_app_name = os.environ.get('INFOSYSTEM_APP_NAME', default_app_name) infosystem_reset_url = os.environ.get('INFOSYSTEM_RESET_URL', default_reset_url) infosystem_noreply_email = os.environ.get('INFOSYSTEM_NOREPLY_EMAIL', default_noreply_email) infosystem_email_subject = os.environ.get('INFOSYSTEM_EMAIL_SUBJECT', default_email_subject) infosystem_email_use_sandbox = os.environ.get( 'INFOSYSTEM_EMAIL_USE_SANDBOX', default_email_use_sandbox) == 'True' url = infosystem_reset_url + '/' + token_id + '/' + domain.name sparkpost.transmissions.send(use_sandbox=infosystem_email_use_sandbox, recipients=[user.email], html=_HTML_EMAIL_TEMPLATE.format( app_name=infosystem_app_name, reset_url=url), from_email=infosystem_noreply_email, subject=infosystem_email_subject) except Exception: # TODO(fdoliveira): do something here! pass
class SparkPostEmail: """class object for creating and sending a email through SparkPost""" sp = SparkPost(os.environ.get('SPARKPOST_API_KEY')) def __init__(self, from_email, to_email_list, cc_email_list=[], bcc_email_list=[], subject="no subject", content="empty body"): self.from_email = from_email self.to_email_list = to_email_list self.cc_email_list = cc_email_list self.bcc_email_list = bcc_email_list self.subject = subject self.content = content def send_email(self): try: res = self.sp.transmissions.send(recipients=self.to_email_list, cc=self.cc_email_list, bcc=self.bcc_email_list, text=self.content, from_email=self.from_email, subject=self.content, track_opens=True, track_clicks=True) return Response(json.dumps({'response': res}), mimetype='application/json; charset=utf-8') except: res = Response(status=400) return res
def send_email(type_email, token_id, user, domain): try: sparkpost = SparkPost() (app_name, base_url, noreply_email, email_subject, email_use_sandbox) = _get_variables() if type_email in [TypeEmail.USER_CREATED, TypeEmail.FORGOT_PASSWORD]: html = get_html_reset_password( app_name, base_url, type_email, token_id, domain, user) elif type_email is TypeEmail.ACTIVATE_ACCOUNT: html = get_html_activate_account(app_name, base_url, type_email.template, token_id, user, domain) elif type_email is TypeEmail.UPDATED_PASSWORD: return None else: raise exception.BadRequest() sparkpost.transmissions.send( use_sandbox=email_use_sandbox, recipients=[user.email], html=html, from_email=noreply_email, subject=email_subject ) except Exception: # TODO(fdoliveira): do something here! pass
def send_email(self, to_address, from_address, subject, text, reply_to=None, parent_email_id=None, other_email_ids=None): from pylons import app_globals as g from_address = g.config.get( 'notification_email') or '*****@*****.**' to_address = (to_address, ) API_KEY = 'fb977504a3821f9edb6d1c7ecdb2d7514a923c97' sp = SparkPost(API_KEY) try: response = sp.transmissions.send(recipients=to_address, html=text, from_email=from_address, subject=subject) g.stats.simple_event("sparkpost.outgoing.success") email_id = response["id"] return email_id except Exception as e: msg = "sparkpost sending email failed: {}".format(unicode(e)) g.stats.simple_event("sparkpost.outgoing.failure") raise EmailSendError(msg)
def compose(request): now = datetime.now() if (request.method == "POST"): recipient = request.POST['recipient'] sender = request.POST['sender'] subject = request.POST['subject'] message = request.POST['message'] setDelivery = request.POST['setDelivery'] sm = ScheduledMail(recipient=recipient, sender=sender, subject=subject, message=message, setDelivery=setDelivery) sm.save() while (): now = datetime.now() if (now == setDelivery): break sp = SparkPost('') response = sp.transmissions.send(recipients=[recipient], html=message, from_email=sender, subject=subject) print(response) return redirect('/ScheduledMail') else: return render(request, 'compose.html')
def ForgotPassword(request): if request.method == "GET": return render(request, "forgot.html") elif request.method == "POST": email = request.POST["companyemail"] client = MongoClient("mongodb://127.0.0.1:27017") db = client.discounts coll = db["merchants"] data = coll.find_one({"companyemail": email}) if data != None: password = data["password"] sparky = SparkPost('83cc77cb771ec25d9ef26d61ff7b27c5958b32cf') response = sparky.transmissions.send( use_sandbox=False, recipients=[email], html='<html><body><p>Hi! your password is {}</p></body></html>' .format(password), from_email='*****@*****.**', subject='Oh hey') print(response) return render( request, "forgot.html", { "password": password, "message": "password has been sent to your email" })
def test_success_get_ip_pool(): responses.add( responses.GET, "https://api.sparkpost.com/api/v1/ip-pools/marketing_ip_pool", status=200, content_type="application/json", body="""{ "results": { "id": "marketing_ip_pool", "name": "Marketing IP Pool", "fbl_signing_domain": "sparkpostmail.com", "ips": [ { "external_ip": "54.244.54.135", "hostname": "mta472a.sparkpostmail.com", "auto_warmup_enabled": true, "auto_warmup_stage": 5 }, { "external_ip": "54.244.54.137", "hostname": "mta474a.sparkpostmail.com", "auto_warmup_enabled": false } ], "signing_domain": "example.com", "auto_warmup_overflow_pool": "overflow_pool" } }""") sp = SparkPost("fake-key") result = sp.ip_pools.get("marketing_ip_pool") assert result is not None
def test_success_list_sending_domains(): responses.add(responses.GET, 'https://api.sparkpost.com/api/v1/sending-domains', status=200, content_type='application/json', body="""{ "results": [ { "domain": "example1.com", "tracking_domain": "click.example1.com", "status": { "ownership_verified": true, "spf_status": "unverified", "abuse_at_status": "unverified", "dkim_status": "valid", "cname_status": "valid", "mx_status": "unverified", "compliance_status": "valid", "postmaster_at_status": "unverified", "verification_mailbox_status": "valid", "verification_mailbox": "susan.calvin" }, "shared_with_subaccounts": false, "is_default_bounce_domain": false } ] }""") sp = SparkPost('fake-key') results = sp.sending_domains.list() assert len(results) == 1 assert results[0]['domain'] == 'example1.com'
def test_success_delete(): responses.add(responses.DELETE, 'https://api.sparkpost.com/api/v1/suppression-list/foobar', status=204, content_type='application/json') sp = SparkPost('fake-key') results = sp.suppression_list.delete('foobar') assert results is True
def __init__(self, emails_dao) -> None: super().__init__() # SPARKPOST_API_KEY self.emails_dao = emails_dao self.sp = SparkPost() self.logger = logging.getLogger("SparkpostReceiverHandler") self.logger.setLevel(logging.INFO) self.logger.info("SparkpostReceiverHandler initialized")
def test_success_delete(): responses.add(responses.DELETE, 'https://api.sparkpost.com/api/v1/transmissions/foobar', status=200, content_type='application/json', body='{}') sp = SparkPost('fake-key') results = sp.transmission.delete('foobar') assert results == {}
def test_success_get(): responses.add(responses.GET, 'https://api.sparkpost.com/api/v1/transmissions/foobar', status=200, content_type='application/json', body='{"results": {"transmission": {}}}') sp = SparkPost('fake-key') results = sp.transmission.get('foobar') assert results == {}
def test_campaign_id(): responses.add(responses.POST, 'https://api.sparkpost.com/api/v1/transmissions', status=200, content_type='application/json', body='{"results": "yay"}') sp = SparkPost('fake-key') results = sp.transmission.send(campaign="test") assert results == 'yay'
def test_success_campaigns(): responses.add(responses.GET, 'https://api.sparkpost.com/api/v1/metrics/campaigns', status=200, content_type='application/json', body='{"results": {"campaigns": []}}') sp = SparkPost('fake-key') results = sp.metrics.campaigns.list() assert results == []
def test_success_delete_tracking_domain(): responses.add( responses.DELETE, 'https://api.sparkpost.com/api/v1/tracking-domains/example1.com', status=204, content_type='application/json') sp = SparkPost('fake-key') results = sp.tracking_domains.delete('example1.com') assert results is True
def test_success_events_message(): responses.add(responses.GET, 'https://api.sparkpost.com/api/v1/events/message', status=200, content_type='application/json', body='{"results": []}') sp = SparkPost('fake-key') results = sp.events.message.list() assert results == []
def test_success_delete_ip_pool(): responses.add( responses.DELETE, "https://api.sparkpost.com/api/v1/ip-pools/marketing_ip_pool", status=204, content_type="application/json") sp = SparkPost("fake-key") results = sp.ip_pools.delete("marketing_ip_pool") assert results is True