Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def getRecentCampaigns():
campaign_data = []
client = MailChimp(mc_api=mailChimpKey)
today = datetime.date.today()
margin = datetime.timedelta(days = 7)
campaigns = client.campaigns.all(get_all=True)
for campaign in campaigns["campaigns"]:
try:
if today - margin <= datetime.datetime.strptime(campaign["send_time"][:10], "%Y-%m-%d").date() <= today:
print "Matching campaign:"
print "URL: " + campaign["archive_url"]
campaign_data.append([campaign["send_time"][:10], str(campaign['emails_sent']), campaign["recipients"]["list_name"], str(campaign["settings"]["subject_line"]), str(int(campaign['report_summary']["open_rate"]*100)) + "%", str(int(campaign['report_summary']["click_rate"]*100)) + "%", campaign["archive_url"]])
print "Current data is /n" + campaign_data
except:
print "Looks like no campaign date or another issue"
print campaign_data
return campaign_data
def handle(self, *args, **options):
site_domain = options['site_domain'][0]
try:
site = Site.objects.get(domain=site_domain)
except ObjectDoesNotExist:
raise CommandError(
'Site with domain name %s does not exist' % site_domain
)
else:
if (site.siteconfig.mailchimp_username and
site.siteconfig.mailchimp_api_key):
client = MailChimp(
site.siteconfig.mailchimp_username,
site.siteconfig.mailchimp_api_key
)
try:
lists = client.lists.all()
except Exception:
raise CommandError(
'There was a problem connecting to the MailChimp '
'API, check your credentials and try again'
)
if len(lists['lists']) > 0:
msg = "The following MailChimp lists exist:\n"
msg += "ID\t\tName\n"
import logging
from mailchimp3 import MailChimp
import md5
from requests import exceptions
from dancedeets import keys
from dancedeets.util import runtime
client = MailChimp(keys.get('mailchimp_username'), keys.get('mailchimp_key'))
LIST_WEB_ID = 554989
LIST_ID = '93ab23d636'
class UserNotFound(Exception):
pass
def get_list_id():
lists = client.lists.all()
list_id = [x['id'] for x in lists['lists'] if x['web_id'] == LIST_WEB_ID][0]
return list_id
def add_members(list_id, members):
def subscribe_user_to_chimp(profile):
configs = (
settings.MAILCHIMP_API_KEY,
settings.MAILCHIMP_USERNAME,
settings.MAILCHIMP_LIST_KEY,
)
if not all(configs):
return
client = MailChimp(settings.MAILCHIMP_API_KEY, settings.MAILCHIMP_USERNAME)
try:
client.lists.members.create(
settings.MAILCHIMP_LIST_KEY,
{"status": "subscribed", "email_address": profile.user.email},
)
except: # TODO specify which errors can be raised at this point
pass
def subscribe(request):
site = get_current_site(request)
if (request.method == 'POST' and site.siteconfig.mailchimp_username and
site.siteconfig.mailchimp_api_key and
site.siteconfig.mailchimp_list_id):
form = SubscribeForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
client = MailChimp(
site.siteconfig.mailchimp_username,
site.siteconfig.mailchimp_api_key
)
try:
client.lists.members.get(
site.siteconfig.mailchimp_list_id,
cd['email']
)
except requests.exceptions.HTTPError as e:
if e.response.status_code == 404:
client.lists.members.create(
site.siteconfig.mailchimp_list_id,
{
'email_address': cd['email'],
'status': 'pending',
if not token_id:
token_id = self.request.META.get('HTTP_API_KEY', None)
try:
token = APIToken.objects.get(id=token_id, is_activated=True)
except Exception: # General APIToken.DoesNotExist or django.core.exceptions.ValidationError
raise APIException("You must provide an active API token ID")
# We could be more aggressive with requirements checking here, but
# there could be use cases where you don't want to supply an email.
supplied_email_address = self.request.data.get('email_address', None)
email_ccdl_ok = self.request.data.get('email_ccdl_ok', False)
if supplied_email_address and MAILCHIMP_API_KEY \
and settings.RUNNING_IN_CLOUD and email_ccdl_ok:
try:
client = mailchimp3.MailChimp(mc_api=MAILCHIMP_API_KEY, mc_user=MAILCHIMP_USER)
data = {
"email_address": supplied_email_address,
"status": "subscribed"
}
client.lists.members.create(MAILCHIMP_LIST_ID, data)
except mailchimp3.mailchimpclient.MailChimpError as mc_e:
pass # This is likely an user-already-on-list error. It's okay.
except Exception as e:
# Something outside of our control has gone wrong. It's okay.
logger.exception("Unexpected failure trying to add user to MailChimp list.",
supplied_email_address=supplied_email_address,
mc_user=MAILCHIMP_USER
)
if not already_processing:
# Create and dispatch the new job.
except PermissionDenied:
error = mark_safe("This verification code is invalid or expired. <a href="%s">Resend verification</a>?" % reverse('resend-verification'))
else:
# user authenticated successfully
# update API limits for first X users per day
# users after this limit will have approved accounts, but we will have to go back manually to increase limits
site_limits = SiteLimits.add_values(daily_signups=1)
if site_limits.daily_signups < site_limits.daily_signup_limit:
user.total_case_allowance = user.case_allowance_remaining = settings.API_CASE_DAILY_ALLOWANCE
user.save()
# sign them up for the mailing list if they selected the mailing_list checkbox.
if settings.MAILCHIMP['api_key'] and user.mailing_list:
try:
mc_client = MailChimp(mc_api=settings.MAILCHIMP['api_key'], mc_user=settings.MAILCHIMP['api_user'])
mc_client.lists.members.create(
settings.MAILCHIMP['id'], {
'email_address': user.email,
'merge_fields': {'LNAME': user.first_name, 'FNAME': user.last_name},
'status': 'subscribed'
})
mailing_list_message = "Also, thanks for signing up for our newsletter, Lawvocado."
except MailChimpError as e:
if e.args[0]['status'] == 400 and e.args[0]['title'] == 'Member Exists':
mailing_list_message = "Also, thanks for your continued interest in our newsletter, " \
"Lawvocado. We'll keep you on our list."
else:
logger.exception("Error adding user email %s to mailing list" % user.email)
return render(request, 'registration/verified.html', {
'error': error,
def subscribe_to_newsletter(user):
if settings.MAILCHIMP_NEWSLETTER_KEY:
from mailchimp3 import MailChimp
try:
client = MailChimp(mc_api=settings.MAILCHIMP_API_KEY)
client.lists.members.create(settings.MAILCHIMP_NEWSLETTER_KEY, {
'email_address': user.email,
'status': 'subscribed',
'merge_fields': {
'FNAME': user.first_name,
'LNAME': user.last_name,
},
})
except Exception as error:
try:
if error.args[0]['title'] == 'Member Exists':
logger.info("%s already subscribed to newsletter" % user.email)
return
except Exception:
pass
raise error