def post(self, request): email = request.POST.get("email") client = MailchimpMarketing.Client() client.set_config({ "api_key": settings.MAILCHIMP_KEY, "server": settings.MAILCHIMP_SERVER_PREFIX, }) content = {"email_address": email, "status": "subscribed"} body = {"members": [content], "update_existing": True} http_status = 200 response_data = {"data": content} try: client.lists.batch_list_members(settings.MAILCHIMP_LIST_ID, body) except ApiClientError as error: http_status = 500 response_data = { "errors": [{ "status": 500, "title": "mailchimp_marketing ApiClientError", "detail": error.text, }] } return JsonResponse(response_data, status=http_status)
class SubsciberListView(LoginRequiredMixin, GroupRequiredMixin, TemplateView): group_required = [u'Administrator', u'Project manager', u'Member'] template_name = "newsletter/subscriber/list.html" try: mailchimp = MailchimpMarketing.Client() mailchimp.set_config({"api_key": api_key, "server": server}) response = mailchimp.lists.get_list_members_info(list_id) response = (response['members']) data_list = [] for member in response: email = member["email_address"] status = member["status"] subcribed_on = member["timestamp_signup"] data = { 'email': email, 'status': status, 'subcribed_on': subcribed_on, } data_list.append(data) except ApiClientError as error: print("Error: {}".format(error.text)) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["data"] = self.data_list return context
def get_mailchimp_client(self) -> MailchimpMarketing.Client: client = MailchimpMarketing.Client() client.set_config({ "api_key": mailchimp_config['MAILCHIMP_API_KEY'], "server": mailchimp_config['MAILCHIMP_SERVER_PREFIX'] }) return client
def mailchimpListMembers(): try: client = MailchimpMarketing.Client() client.set_config({ "api_key": config.MAILCHIMP_API_KEY, "server": config.MAILCHIMP_SERVER_PREFIX }) members = [] offset = 0 #response = client.lists.get_list_members_info(config.MAILCHIMP_LIST_ID, offset=offset, count=config.MAILCHIMP_PAGE_SIZE) #members.extend(response['members']) while (True): response = client.lists.get_list_members_info( config.MAILCHIMP_LIST_ID, offset=offset, count=config.MAILCHIMP_PAGE_SIZE) #TODO : si code HTTP retour = 429, attendre une seconde et recommencer members.extend(response['members']) if (len(response['members']) < config.MAILCHIMP_PAGE_SIZE): break offset = offset + config.MAILCHIMP_PAGE_SIZE for member in members: tags = [] for t in member['tags']: tags.append(t['name']) member["tags"] = tags member['displayName'] = member['merge_fields'][ 'FNAME'] + " " + member['merge_fields']['LNAME'] return members except ApiClientError as error: print("Error: {}".format(error.text)) return False
def mailchimp(request): try: mailchimp = MailchimpMarketing.Client() mailchimp.set_config({ 'api_key': settings.MAILCHIMP_API_KEY, 'server': 'us13' }) list_id = "9bb5a9f1da" email_address = request.POST.get('email_address') member_info = { "email_address": email_address, "status": "pending", "merge_fields": { "FNAME": "", "LNAME": "" } } response = mailchimp.lists.add_list_member(list_id, member_info) message = "Your e-mail address was successfully added to our mailing list, please check your inbox for a confirmation e-mail!" response = JsonResponse({"result": {"success": message}}) return response except ApiClientError as error: message = "This e-mail address could not be added to our mailing list ..." response = JsonResponse({"result": {"error": message}}) return response
def __init__(self): self.client = MailchimpMarketing.Client() self.client.set_config({ "api_key": MAILCHIMP_API_KEY, "server": MAILCHIMP_DATA_CENTER }) self.list_id = MAILCHIMP_EMAIL_LIST_ID
def sign_up_for_newsletters(request): fname = request.data.get("firstName") lname = request.data.get("lastName") email = request.data.get("email") phoneNumber = request.data.get("phoneNumber") # countryCode = request.data.get('countryCode'), TODO: when we fix front-end form, we can uncomment this part mailchimp = MailchimpMarketing.Client() mailchimp_config = os.path.join("api","mailchimp_config.json") with open(mailchimp_config) as infile: data = json.load(infile) mailchimp.set_config(data['keys']) list_id = data["listid"]["id"] member_info = { "email_address": email, "status": "subscribed", "merge_fields": { "FNAME": fname, "LNAME": lname, "PHONE": phoneNumber, # "PHONE": (f'+{countryCode}{phoneNumber}'), TODO: when we fix front-end form, we can uncomment this part } } try: response = mailchimp.lists.add_list_member(list_id, member_info) print("response: {}".format(response)) except ApiClientError as error: print("An exception occurred: {}".format(error.text)) #TODO test this functionality more thoroughly return Response( {"success": "true"} )
def _client(self): client = mailchimp_marketing.Client() client.set_config({ "api_key": self._dynamic_setting("mailchimp__api_key"), "server": self._dynamic_setting("mailchimp__server"), }) return client
def main(getMailchimpStats: func.TimerRequest) -> None: logging.info('Python HTTP trigger function processed a request.') try: client = MailchimpMarketing.Client() client.set_config({ 'api_key': app_config.MAILCHIMP_API_KEY, 'server': 'us7' }) # Get list info # https://mailchimp.com/developer/api/marketing/lists/get-list-info/ listStats = client.lists.get_list(app_config.MAILCHIMP_LIST_ID) totalSubscribers = int(listStats['stats']['member_count']) # Get Confirmed segment info # https://mailchimp.com/developer/marketing/api/list-segments/get-segment-info/ # https://us7.admin.mailchimp.com/lists/segments?id=518946 segmentConfirmedStats = client.lists.get_segment( app_config.MAILCHIMP_LIST_ID, '3577267') confirmedSubscribers = int(segmentConfirmedStats['member_count']) segmentUnconfirmedStats = client.lists.get_segment( app_config.MAILCHIMP_LIST_ID, '3577271') unconfirmedSubscribers = int(segmentUnconfirmedStats['member_count']) except ApiClientError as error: logging.error(f'Mailchimp Error: {error.text}') return # Construct message to send to Basecamp content = '<strong>Mailchimp Stats (py)</strong><ul>' # The total number of subscribers in the list # Includes confirmed and unconfirmed content += '<li><strong>Confirmed subscribers:</strong> ' content += f'{confirmedSubscribers:,}</li>' content += '<li><strong>Unconfirmed members:</strong> ' content += f'{unconfirmedSubscribers:,}</li>' content += '<li><strong>Total list members:</strong> ' content += f'{totalSubscribers:,}</li>' content += '</ul>' if 'PRODUCTION' in os.environ: # Post to Campfire r = requests.post(app_config.CAMPFIRE_ROOM, json={'content': content}) if r.status_code != 200 or r.status_code != 201: logging.error(f'Basecamp error: {r.status_code} {r.text}') else: logging.info('Not in production mode, would have posted:') logging.info(content)
def __init__(self): api_key = os.environ.get('MAILCHIMP_APIKEY', None) if api_key == None: raise Exception("No API Key Specified") self.client = MailchimpMarketing.Client() self.client.set_config({ "api_key": api_key, "server": "us7" })
def authCallback(): # You should always store your client id and secret in environment variables for security — the exception: sample code. MAILCHIMP_CLIENT_ID = "YOUR_CLIENT_ID" MAILCHIMP_CLIENT_SECRET = "YOUR_CLIENT_SECRET" BASE_URL = "http://127.0.0.1:3000" OAUTH_CALLBACK = "{}/oauth/mailchimp/callback".format(BASE_URL) code = request.args['response_type'] # Here we're exchanging the temporary code for the user's access token. tokenResponse = requests.post("https://login.mailchimp.com/oauth2/token", data={ 'body': { 'grant_type': 'authorization_code', 'client_id': MAILCHIMP_CLIENT_ID, 'client_secret': MAILCHIMP_CLIENT_SECRET, 'redirect_uri': OAUTH_CALLBACK, 'code': code }}) access_token = itemgetter('access_token')(tokenResponse.json()) print(access_token) # Now we're using the access token to get information about the user. # Specifically, we want to get the user's server prefix, which we'll use to # make calls to the API on their behalf. This prefix will change from user # to user. metadataResponse = requests.get( 'https://login.mailchimp.com/oauth2/metadata', headers={'Authorization': "OAuth {}".format(access_token)}) dc = itemgetter('dc')(metadataResponse.json()) print(dc) # Below, we're using the access token and server prefix to make an # authenticated request on behalf of the user who just granted OAuth access. # You wouldn't keep this in your production code, but it's here to # demonstrate how the call is made. mailchimp = MailchimpMarketing.Client() mailchimp.set_config({ "access_token": "YOUR_ACCESS_TOKEN", "server": "YOUR_SERVER_PREFIX" }) response = mailchimp.ping.get() print(response) return """<p>This user's access token is {} and their server prefix is {}.</p> <p>When pinging the Mailchimp Marketing API's ping endpoint, the server responded:<p> <code>{}</code> """.format(access_token, dc, code)
def connectToMailchimp(): #Try connecting to mailchimp client try: mailchimp = MCM.Client() mailchimp.set_config({ "api_key": credentials.MAILCHIMP_API_KEY, "server": credentials.MAILCHIMP_SERVER_PREFIX }) except ApiClientError as error: logging.error('ERROR: {}'.format(error.text)) return 'error' return mailchimp
def subscribe_newsletter(data): try: client = MailchimpMarketing.Client() client.set_config({ "api_key": settings.MAILCHIMP_API_KEY, "server": settings.MAILCHIMP_SERVER }) list_id = settings.MAILCHIMP_LIST_ID # Unused as yet, response info here: https://mailchimp.com/developer/marketing/api/list-members/add-member-to-list/ client.lists.add_list_member(list_id, data) return True except ApiClientError as error: raise Exception from error
def add(self, email): try: client = MailchimpMarketing.Client() client.set_config({ "api_key": MAILCHIMP_API_KEY, "server": MAILCHIMP_DATA_CENTER, }) response = client.lists.add_list_member(self.list_id, { "email_address": email, "status": "subscribed" }) print(response) except ApiClientError as error: print("Error: {}".format(error.text))
def mailchimpLists(): try: client = MailchimpMarketing.Client() client.set_config({ "api_key": config.MAILCHIMP_API_KEY, "server": config.MAILCHIMP_SERVER_PREFIX }) #res_l = client.lists.get_all_lists() #TODO : si code HTTP retour = 429, attendre une seconde et recommencer response = client.lists.get_list(config.MAILCHIMP_LIST_ID) return response except ApiClientError as error: print("Error: {}".format(error.text)) return False
def add_member_to_mailing_list_chimp(email: str, list_id: str): try: client = mailchimp_marketing.Client() client.set_config({ "api_key": os.environ['mail_chimp'], "server": "us1" }) response = client.lists.add_list_member(list_id, { "email_address": email, "status": "pending" }) return (0, response) except ApiClientError as error: return (-1, error.text)
def mailchimpMembersTags(): if is_session_valid() == False: return flask.redirect( url_for('login', redirect='/mailchimpMembersTags')) try: client = MailchimpMarketing.Client() client.set_config({ "api_key": config.MAILCHIMP_API_KEY, "server": config.MAILCHIMP_SERVER_PREFIX }) response = client.lists.tag_search(config.MAILCHIMP_LIST_ID) return jsonify(response['tags']) except ApiClientError as error: print("Error: {}".format(error.text)) return jsonify(list(res.values()))
def subscriber(payload): mailchimp = MailchimpMarketing.Client() mailchimp.set_config({ "api_key": payload['API_KEY'], "server": payload['SERVER_PREFIX'] }) list_id = payload['LIST_ID'] member_info = { "email_address": payload['SUB_EMAIL'], "status": "subscribed" } try: response = mailchimp.lists.add_list_member(list_id, member_info) print("response: {}".format(response)) except ApiClientError as error: print("An exception occurred: {}".format(error.text))
def serve(self, request): form = SubscribeForm() context = { 'self': self, } member_info = {} if request.GET: form = SubscribeForm(initial={'email': request.GET.get('email', None)}) if request.method == 'POST': form = SubscribeForm(request.POST) if form.is_valid(): member_info['email_address'] = form.cleaned_data['email'] member_info['merge_fields'] = { 'FNAME': form.cleaned_data['first_name'], 'LNAME': form.cleaned_data['last_name'], 'ORG': form.cleaned_data['organization'], 'COUNTRY': form.cleaned_data['country'], } try: if api_key and server and list_id: client = MailchimpMarketing.Client() client.set_config({ 'api_key': api_key, 'server': server, }) member_info['status'] = 'pending' response = client.lists.add_list_member(list_id, member_info) logger.info(f'Successful newsletter sign up: {response["email_address"]}') except ApiClientError as error: logger.error('An error occurred with Mailchimp: {}'.format(error.text)) return render(request, self.landing_page_template, context) context['form'] = form return render(request, self.template, context)
def subscribe(email): """ Contains code handling the communication to the mailchimp api to create a contact/member in an audience/list. """ client = MailchimpMarketing.Client() client.set_config({ "api_key": api_key, "server": server, }) member_info = { "email_address": email, "status": "subscribed", } try: response = client.lists.add_list_member(list_id, member_info) print("response: {}".format(response)) except ApiClientError as error: print("An exception occurred: {}".format(error.text))
def subscribed_add_view(request): if request.method == 'POST': email = request.POST['email'] message_success = 'You have successfully subscribed to the newsletter.' message_email_exist = 'You are already subscribed to the newsletter.' result = '' try: mailchimp = MailchimpMarketing.Client() mailchimp.set_config({"api_key": api_key, "server": server}) response = mailchimp.lists.get_list_members_info(list_id) response = (response['members']) data_list = [] for member in response: member_email = member["email_address"] data_list.append(member_email) if email in data_list: result = message_email_exist else: result = message_success mailchimp.lists.add_list_member(list_id, { "email_address": email, "status": "pending" }) """ print(json.dumps(json_object, indent=3)) """ except ApiClientError as error: print("Error: {}".format(error.text)) return render(request, 'newsletter/subscriber/add.html', {'result': result})
def main(req: func.HttpRequest) -> func.HttpResponse: logging.info('Python HTTP trigger function processed a request.') try: client = MailchimpMarketing.Client() client.set_config({ 'api_key': app_config.MAILCHIMP_API_KEY, 'server': 'us7' }) # Get Confirmed segment info # https://mailchimp.com/developer/marketing/api/list-segments/get-segment-info/ # https://us7.admin.mailchimp.com/lists/segments?id=518946 segmentConfirmedStats = client.lists.get_segment( app_config.MAILCHIMP_LIST_ID, '3577267') confirmedSubscribers = str(segmentConfirmedStats['member_count']) except ApiClientError as error: logging.error(f'Mailchimp Error: {error.text}') jsonResponse = json.dumps( {'frames': [{ 'icon': 'i619', 'text': 'Mailchimp Error' }]}) return func.HttpResponse(jsonResponse, mimetype='application/json') # The total number of subscribers in the list # Includes confirmed and unconfirmed jsonResponse = json.dumps( {'frames': [{ 'icon': 'i29438', 'text': confirmedSubscribers }]}) return func.HttpResponse(jsonResponse, mimetype='application/json')
import argparse import sys import traceback from hashlib import md5 import mailchimp_marketing as MailchimpMarketing import requests from consolemsg import step, error, success from erppeek import Client import time import configdb ERP_CLIENT = Client(**configdb.erppeek) MAILCHIMP_CLIENT = MailchimpMarketing.Client( dict(api_key=configdb.MAILCHIMP_APIKEY, server=configdb.MAILCHIMP_SERVER_PREFIX)) def get_member_category_id(): module = 'som_partner_account' semantic_id = 'res_partner_category_soci' IrModelData = ERP_CLIENT.model('ir.model.data') member_category_relation = IrModelData.get_object_reference( module, semantic_id) if member_category_relation: return member_category_relation[-1] def get_not_members_email_list():
def post(self, request): body = request.data if User.objects.filter(email=body.get("email").lower()).exists(): return Response( {"message": "error.accountAlreadyExists"}, status=status.HTTP_409_CONFLICT, ) if Profile.objects.filter(screen_name=body.get("screenName").lower()).exists(): return Response( {"message": "error.screenNameAlreadyExists"}, status=status.HTTP_409_CONFLICT, ) new_user = User.objects.create( email=body.get("email").lower(), email_verified=False, ) new_user.set_password(body.get("password")) new_user.save() profile = Profile.objects.create( user=new_user, member_type_id=config.DEFAULT_MEMBER_TYPE, first_name=body.get("firstName"), last_name=body.get("lastName"), screen_name=body.get("screenName"), phone=body.get("mobile"), ) profile.save() verification_token = EmailVerificationToken.objects.create(user=new_user) url = f"{config.SITE_URL}/profile/email/{verification_token.verification_token}/verify/" verification_token.user.email_link( "Action Required: Verify Email", "Verify Email", "Verify Email", "Please verify your email address to activate your account.", url, "Verify Now", ) profile.email_profile_to(config.EMAIL_ADMIN) if not config.ENABLE_STRIPE_MEMBERSHIP_PAYMENTS: new_user.email_link( f"Action Required: {config.SITE_OWNER} New Member Signup", "Next Step: Register for an Induction", "Important. Please read this email for details on how to " "register for an induction.", f"Hi {profile.first_name}, thanks for signing up! The next step to becoming a fully " "fledged member is to book in for an induction. During this " "induction we will go over the basic safety and operational " f"aspects of {config.SITE_OWNER}. To book in, click the link below.", f"{config.INDUCTION_URL}", "Register for Induction", ) try: if config.MAILCHIMP_API_KEY: import mailchimp_marketing from mailchimp_marketing.api_client import ApiClientError client = mailchimp_marketing.Client() client.set_config( { "api_key": config.MAILCHIMP_API_KEY, "server": config.MAILCHIMP_SERVER, } ) list_id = config.MAILCHIMP_LIST_ID merge_fields = { "FNAME": new_user.profile.first_name, "LNAME": new_user.profile.last_name, "PHONE": new_user.profile.phone, } print("merge fields") print(merge_fields) payload = { "email_address": new_user.email, "email_type": "html", "status": "subscribed", "merge_fields": merge_fields, "vip": False, "tags": [ config.MAILCHIMP_TAG, ], } response = client.lists.add_list_member(list_id, payload) print(response) except Exception as e: # gracefully catch and move on sentry_sdk.capture_exception(e) print(e) return Response() return Response()
def mailchimpAdd(): if is_session_valid() == False: return flask.redirect(url_for('login', redirect='/mailchimp')) import json form = json.loads(request.form.getlist('values')[0]) print(form) if 'email_address' in form.keys(): email_address = form['email_address'] else: email_address = request.form.getlist('key')[0] try: client = MailchimpMarketing.Client() client.set_config({ "api_key": config.MAILCHIMP_API_KEY, "server": config.MAILCHIMP_SERVER_PREFIX }) h = hashlib.md5(email_address.lower().encode()).hexdigest() # CREATION ou MISE A JOUR DU MEMBRE d = dict({"email_address": email_address}) d["status"] = form[ 'status'] #"subscribed", "unsubscribed", "cleaned", "pending", or "transactional". if d['status'] in ["new", ""]: d['status'] = "subscribed" d["vip"] = form["vip"] d['merge_fields'] = form['merge_fields'] print(d) print(flask.session['mail'] + " ===> client.lists.set_list_member", config.MAILCHIMP_LIST_ID, h, d) response = client.lists.set_list_member(config.MAILCHIMP_LIST_ID, h, d) #TODO : si code HTTP retour = 429, attendre une seconde et recommencer print(response) #MISE A JOUR DES TAGS t = [] response_tags = client.lists.tag_search(config.MAILCHIMP_LIST_ID) for tag in response_tags['tags']: if tag['name'] in form['tags']: t.append(dict({"name": tag['name'], "status": "active"})) else: t.append(dict({"name": tag['name'], "status": "inactive"})) print( flask.session['mail'] + " ===> client.lists.update_list_member_tags", config.MAILCHIMP_LIST_ID, h, t) response_update_list_member_tags = client.lists.update_list_member_tags( config.MAILCHIMP_LIST_ID, h, {'tags': t}) #TODO : si code HTTP retour = 429, attendre une seconde et recommencer print(response_update_list_member_tags) res = dict({ 'email_address': response["email_address"], 'status': response['status'], 'tags': form['tags'], 'vip': response['vip'], 'merge_fields': response['merge_fields'] }) return jsonify(res) except ApiClientError as error: print("Error: {}".format(error.text)) import json error_dic = json.loads(error.text) return jsonify(error.text), error_dic["status"] return Response(jsonify("Erreur"), 500)
def start(): # create an IMAP4 class with SSL imap = imaplib.IMAP4_SSL("imap.gmail.com") # authenticate imap.login(username, password) (status, messages) = imap.select('INBOX') threading.Timer(5.0, start).start() #ex every 5 secs # number of top emails to fetch N = 100 # push key emails = [] # total number of emails messages = int(messages[0]) for i in range(messages, messages - N, -1): # fetch the email message by ID res, msg = imap.fetch(str(i), '(RFC822)') for response in msg: if isinstance(response, tuple): # parse a bytes email into a message object msg = email.message_from_bytes(response[1]) # decode the email subject # (subject, encoding) = decode_header(msg['Subject'])[0] # if isinstance(subject, bytes): # subject = subject.decode(encoding) From, encoding = decode_header(msg.get('From'))[0] if isinstance(From, bytes): From = From.decode(encoding) #if '*****@*****.**' in From: # print ('epa 2', subject) # if the email message is multipart if msg.is_multipart(): for part in msg.walk(): content_type = part.get_content_type() content_disposition = \ str(part.get('Content-Disposition')) if content_type == 'text/plain' \ and 'attachment' not in content_disposition \ and '*****@*****.**' in From: body = part.get_payload(decode=True) # decode body2 = str(body.decode('latin-1')) ref.push().set(get_email(body2)) try: client = MailchimpMarketing.Client() client.set_config({ "api_key": os.environ['chimp_key'], "server": "us1" }) response = client.lists.add_list_member( os.environ['list_id'], { "email_address": get_email(body2), "status": "subscribed" }) #response2 = response = client.lists.get_list_member_tags(os.environ["list_id"], "*****@*****.**") response2 = client.lists.batch_segment_members( {"members_to_add": [get_email(body2)]}, os.environ['list_id'], "3092922") print(response2) except ApiClientError as error: print(error.text) break imap.close() imap.logout()
import os import mailchimp_marketing as MailchimpMarketing from mailchimp_marketing.api_client import ApiClientError try: client = MailchimpMarketing.Client() client.setConfig(os.getenv("API_KEY"), os.getenv("API_SERVER")) response = client.campaigns.create({"type": "plaintext"}) print("client.ping.get() response: {}".format(response)) except ApiClientError as error: print("An exception occurred: {}".format(error.text))
def setUp(self): self.maxDiff = None self.client = MailchimpMarketing.Client( dict(api_key=configdb.MAILCHIMP_APIKEY, server=configdb.MAILCHIMP_SERVER_PREFIX)) self.somenergia_member_list = configdb.mailchimp_member_list_info