def __init__(self, apikey=None, debug=True): #default debug to true if apikey is None: apikey = '' Mandrill.__init__(self, apikey, debug) if os.environ.get('ENVIRONMENT') == 'test': self.level = logging.DEBUG else: self.level = logging.INFO
def sendEmails(to, from_name, subject, template, mergeVars): """ Send an email """ try: client = Mandrill(settings.MANDRILL_API_KEY) message = { 'from_email': settings.MANDRILL_FROM_EMAIL, 'from_name': from_name, 'headers': { 'Reply-To': settings.MANDRILL_FROM_EMAIL }, 'subject': subject, 'merge_vars': mergeVars, 'to': to, 'track_clicks': True, 'track_opens': True, } result = client.messages.send_template(template_name=template, template_content=[], message=message, async=True) except Exception as e: return False else: return result
def sendEmails(to, from_name, subject, template, mergeVars, attachments=[]): """ Send an email """ try: client = Mandrill(MANDRILL_API_KEY) message = { 'from_email': MANDRILL_FROM_EMAIL, 'from_name': from_name, 'headers': { 'Reply-To': MANDRILL_FROM_EMAIL }, 'subject': subject, 'merge_vars': mergeVars, 'to': to, 'track_clicks': True, 'track_opens': True, 'attachments': attachments } result = client.messages.send_template(template_name=template, template_content=[], message=message, async=True) except Exception, e: logging.error(str(e)) return False
def __init__(self, source, opt): super(PanoplyMandrill, self).__init__(source, opt) source["destination"] = source.get("destination") or DESTINATION source["idpattern"] = source.get("idpattern") or IDPATTERN fromsec = int(time.time() - (DAY_RANGE * DAY)) # disabled since we always need 30 days back with the AllowDuplicates # method self.fromTime = self.getLastTimeSucceed(source) # or formatTime(time.gmtime(fromsec)) self.fromTime = formatTime(time.gmtime(fromsec)) self.toTime = formatTime(time.gmtime()) self.metrics = copy.deepcopy(conf.metrics) self.total = len(self.metrics) self.key = source.get('key') self.ongoingJob = None self.mandrill_client = Mandrill(self.key) # will raise InvalidKeyError if the api key is wrong try: self.mandrill_client.users.ping() except InvalidKeyError as e: e.retryable = False raise e
def get_provider(provider): global _provider if _provider is not None: return _provider if provider == 'mailgun': _provider = Mailgun(config.mailgun) elif provider == 'mandrill': _provider = Mandrill(config.mandrill) elif provider == 'smtp': _provider = SMTP(config.smtp) else: raise AttributeError('provider "' + provider + '" must be one of: mailgun|mandrill|smtp') return _provider
from .config import _cfg from mandrill import Mandrill email = Mandrill(_cfg("mandrill_api")) def _email_admins(subject, content): admin_email = _cfg("admin_email") if "," in admin_email: to = [] for i in admin_email.split(","): to.append({"email": i}) else: to = [{"email": admin_email}] message = { "subject": subject, "text": content, "from_email": _cfg("from_email"), "to": to, } return email.messages.send(message=message, asynchronous=True) def send_report(text): return _email_admins("MediaCrush report", text)
def __init__(self, apikey): """ apikey jest to klucz, który jest wykorzystywany do wysyłania maili. """ self.m = Mandrill(apikey)
def send_email(to_email_addresses, email_body, api_key, subject, from_email, from_name, tags, reply_to=None, metadata=None, logger=None): logger = logger or current_app.logger if isinstance(to_email_addresses, string_types): to_email_addresses = [to_email_addresses] try: mandrill_client = Mandrill(api_key) message = { 'html': email_body, 'subject': subject, 'from_email': from_email, 'from_name': from_name, 'to': [{ 'email': email_address, 'type': 'to' } for email_address in to_email_addresses], 'important': False, 'track_opens': False, 'track_clicks': False, 'auto_text': True, 'tags': tags, 'metadata': metadata, 'headers': { 'Reply-To': reply_to or from_email }, 'preserve_recipients': False, 'recipient_metadata': [{ 'rcpt': email_address } for email_address in to_email_addresses] } result = mandrill_client.messages.send(message=message, async=True) except Error as e: # Mandrill errors are thrown as exceptions logger.error("Failed to send an email: {error}", extra={'error': e}) raise EmailError(e) logger.info("Sent {tags} response: id={id}, email={email_hash}", extra={ 'tags': tags, 'id': result[0]['_id'], 'email_hash': hash_string(result[0]['email']) })
def execute_task(task, data={}): ctx = app.test_request_context() ctx.push() compiler = Compiler() try: if task['needs_users']: from core.models.auth.user import User data['users'] = User.list() except KeyError: pass try: if task['has_email']: subject_template = compiler.compile(task['email_subject']) recipients_template = compiler.compile(task['email_to']) mandrill = Mandrill(app.config['MANDRILL_API_KEY']) body_template = compiler.compile( mandrill.templates.info(name=task['email_template'])['code']) message = mandrill.messages.send(message={ 'from_email': app.config['MANDRILL_FROM_EMAIL'], 'from_name': app.config['MANDRILL_FROM_NAME'], 'subject': subject_template(data), 'html': body_template(data), 'inline_css': True, 'to': [{ 'email': recipients_template(data), 'type': 'to' }] }, async=False) print(message) # body_template = compiler.compile(task['email_body']) # message = Message(subject_template(data), # sender=sender_template(data), # recipients=recipients_template(data).split(',')) # message.html = body_template(data) # app.mail.send(message) except KeyError: pass try: if task['has_webhook']: body_template = compiler.compile(task['webhook_body']) response = requests.request(task['webhook_method'].lower(), task['webhook_url'], data=body_template(data), headers=task['webhook_headers']) except KeyError: pass
def sendEventInvite(invite, recipients): to = [] mergeVars = [] for recipient in recipients: to.append({'email': recipient}) mergeVars.append({ 'rcpt': recipient, 'vars': [{ 'name': 'unsub_key', 'content': hashlib.sha512(recipient + UNSUBSCRIBE_SALT).hexdigest() }, { 'name': 'user_email', 'content': recipient }] }) buttonHtml = '<a href="https://bazaarboy.com/' + layout.eventUrl( invite.event ) + '" class="primary-btn view_event_btn" style="color: #222222; text-decoration: none; border-radius: 4px; font-weight: bold; text-align: center; font-size: 1.2em; box-sizing: border-box; padding: 12px 60px;background: #FFFFFF; border: thin solid ' + invite.color + ';">RSVP</a>' if invite.image: headerImageHtml = '<img align="left" alt="" src="' + invite.image.source.url.split( "?", 1 )[0] + '" width="564" style="max-width: 757px;padding-bottom: 0;display: inline !important;vertical-align: bottom;border: 0;outline: none;text-decoration: none;-ms-interpolation-mode: bicubic;" class="mcnImage">' else: headerImageHtml = '' if invite.profile.image: organizerLogo = "<img src='" + invite.profile.image.source.url.split( "?", 1 )[0] + "' style='max-width: 100px; max-height: 100px; padding-bottom: 0;display: inline !important;vertical-align: bottom;border: 0;outline: none;text-decoration: none;-ms-interpolation-mode: bicubic;' align='center' />" else: organizerLogo = '' inviteDetails = '' if invite.details: inviteDetails = invite.details globalVars = [{ 'name': 'profile_name', 'content': invite.profile.name }, { 'name': 'profile_id', 'content': invite.profile.id }, { 'name': 'header_image', 'content': headerImageHtml }, { 'name': 'event_date_short', 'content': layout.standardTime(invite.event.start_time) }, { 'name': 'event_name', 'content': invite.event.name }, { 'name': 'event_date', 'content': layout.standardDate(invite.event) }, { 'name': 'message', 'content': invite.message }, { 'name': 'rsvp_button', 'content': buttonHtml }, { 'name': 'details', 'content': inviteDetails }, { 'name': 'organizer_logo', 'content': organizerLogo }, { 'name': 'event_link', 'content': 'https://bazaarboy.com/' + layout.eventUrl(invite.event) }] template = 'new-invite' subject = 'Invitation to \'' + invite.event.name + '\'' attachments = [] try: client = Mandrill(MANDRILL_API_KEY) message = { 'from_email': MANDRILL_FROM_EMAIL, 'from_name': invite.profile.name, 'headers': { 'Reply-To': MANDRILL_FROM_EMAIL }, 'subject': subject, 'merge_vars': mergeVars, 'global_merge_vars': globalVars, 'to': to, 'track_clicks': True, 'track_opens': True, 'attachments': attachments, 'metadata': { 'invite_id': settings.INVITATION_PREFIX + '-' + str(invite.id), 'invite_event_id': settings.INVITATION_PREFIX + '-' + str(invite.event.id), 'profile_id': settings.INVITATION_PREFIX + '-' + str(invite.profile.id) } } result = client.messages.send_template(template_name=template, template_content=[], message=message, async=True) except Exception, e: logging.error(str(e)) return False
import os from uuid import uuid4 from mandrill import Mandrill from flask.ext.sqlalchemy import SQLAlchemy from flask import Flask, request, redirect, abort app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = os.environ['DATABASE_URL'] mandrill_client = Mandrill(os.environ['MANDRILL_API_KEY']) db = SQLAlchemy(app) class User(db.Model): def __init__(self, email): self.email = email self.uuid = str(uuid4()) id = db.Column(db.Integer, primary_key=True) email = db.Column(db.String(200), unique=True) uuid = db.Column(db.String(36), unique=True) @app.route('/') def index(): return redirect('http://samdobson.github.io/fwdform') @app.route('/register', methods=['POST']) def register(): user = User.query.filter_by(email=request.form['email']).first()
import os, sys, time import tempfile, zipfile import requests from mandrill import Mandrill apikey = os.environ.get('MANDRILL_API_KEY') client = Mandrill(apikey) out = client.exports.list() for o in out: if o['state'] == 'complete': print(o) url = 'https://mandrillapp.com/api/1.0' activity = { 'key': apikey, 'date_from': '2020-02-01 00:00:00', 'date_to': '2020-02-02 00:00:00' } # export_info_list = {'key': apikey} # res = requests.post('{}/exports/list.json'.format(url), json=export_info_list) # if res.ok: # print(res.content) def doit(): if apikey is None: return
def __init__(self): self.client = Mandrill(MANDRILL_API_KEY)