def send_mails(recipients, subject, message): ''' Send emails using mailjet Args: recipients: List of strings. Email addresses of recipients. subject: String. Subject line of each email. message: String. Plain text message for each email. ''' import mailjet_rest import requests_toolbelt.adapters.appengine requests_toolbelt.adapters.appengine.monkeypatch() from src import secrets client = mailjet_rest.Client(auth=(secrets.MAILJET_API_KEY, secrets.MAILJET_API_SECRET)) for recipient in recipients: data = { 'FromEmail': secrets.MAILJET_SENDER, 'FromName': 'CONSIDER Admin', 'Subject': subject, 'Text-part': message, 'Html-part': message, 'Recipients': [{ 'Email': recipient }] } result = client.send.create(data=data) log("Email sent:" + str(result.json()))
def test_get_message(self) -> None: """get_message basic usage.""" before = datetime.datetime.now() message_id = mailjet_rest.Client(version='v3.1').send.create({ 'Messages': [{ 'To': [{ 'Email': '*****@*****.**', }], 'TemplateID': 123456, }] }).json()['Messages'][0]['To'][0]['MessageID'] message = mail.get_message(message_id) assert message self.assertEqual(message_id, message.get('ID')) self.assertEqual('sent', message.get('Status')) arrived_at_string = message.get('ArrivedAt') assert isinstance(arrived_at_string, str) arrived_at = datetime.datetime.strptime(arrived_at_string, '%Y-%m-%dT%H:%M:%SZ') self.assertGreaterEqual(arrived_at, before - datetime.timedelta(seconds=1)) self.assertLessEqual( arrived_at, datetime.datetime.now() + datetime.timedelta(seconds=1))
def sync_properties_to_mailjet(): """Only whether they are paying right now""" conf = flask.current_app.config mailjet = mailjet_rest.Client(auth=(conf["MAILJET_API_KEY"], conf["MAILJET_API_SECRET"])) list_id = conf['MAILJET_PROPPRY_GENERAL_UPDATES_LIST_ID'] unsubscribed = set(x.email for x in Unsubscribed.query.all()) contacts = [] for user in User.query.all(): if user.email in unsubscribed: continue contacts.append({ "Email": user.email, "Properties": { "paying": user.company.is_paying(), }, }) response = mailjet.contactslist_managemanycontacts.create({ "Action": "addnoforce", "Contacts": contacts, }, id=list_id) if not response.ok: logging.error("mailjet upload failed: %s", response.json())
def sync_from_mailjet(delta_hours=6): """ mailjet has two tables, one for opened and one for clicked. We're running this job every hour and getting the last 6h of changes, that way we cover windows of downtime. """ conf = flask.current_app.config mailjet = mailjet_rest.Client(auth=(conf["MAILJET_API_KEY"], conf["MAILJET_API_SECRET"])) from_ts = int(time.time() - delta_hours * 3600) # 6h ago logging.info("syncing from {}".format(from_ts)) for x in mailjet.openinformation.get_many({"FromTS": from_ts}).json()['Data']: oi = OpenInformation.query.get(x['MessageID']) if oi is not None: continue contact = ensure_contact_in_db(mailjet, x['ContactID']) ensure_message_in_db(mailjet, x['MessageID']) opened_at = dateutil.parser.parse(x['OpenedAt']) oi = OpenInformation(json_response=x, contact_id=contact.id, opened_at=opened_at, message_id=x['MessageID']) db.session.merge(oi) for x in mailjet.clickstatistics.get_many({"FromTS": from_ts}).json()['Data']: cs = ClickStatistics.query.get(x['MessageID']) if cs is not None: continue contact = ensure_contact_in_db(mailjet, x['ContactID']) ensure_message_in_db(mailjet, x['MessageID']) clicked_at = dateutil.parser.parse(x['ClickedAt']) cs = ClickStatistics(json_response=x, contact_id=contact.id, clicked_at=clicked_at, message_id=x['MessageID']) db.session.merge(cs) unsubscribed = set(x.email for x in Unsubscribed.query.all()) # So apparently we can't request just the unsub list of contacts, it returns # an empty array # That means we need to do one API request to get the ids of unsub and then # one per user to get their email filters = {"Limit": 0, "Unsub": "true"} logging.info("Syncing unsubscribe") for x in mailjet.listrecipient.get(filters=filters).json()["Data"]: try: email = mailjet.contact.get(id=x["ContactID"]).json()['Data'][0]["Email"] except Exception as e: logging.error("Failed to fetch contact %d from mailjet: %r" % (x["ContactID"], e)) if email not in unsubscribed: logging.info("Unsubscribing %s" % email) db.session.add(Unsubscribed(email=email)) try: db.session.commit() except: db.session.rollback() raise
def _send_email(self, email_address: str = '*****@*****.**') -> int: return typing.cast( int, mailjet_rest.Client(version='v3.1').send.create({ 'Messages': [{ 'To': [{ 'Email': email_address }], 'TemplateID': 123456, }] }).json()['Messages'][0]['To'][0]['MessageID'])
def send_email(receiver, subject, body): client = mailjet_rest.Client( auth=(config.MAILJET_API_KEY, config.MAILJET_API_SECRET)) data = { 'FromEmail': config.MAILJET_SENDER, 'FromName': 'visa-gnib.info', 'Subject': subject, 'Text-part': body, 'Recipients': [{'Email': receiver}] } result = client.send.create(data=data)
def send_email(address, subject, text_part, html_part=None): mailjet = mailjet_rest.Client( auth=(secrets.MJ_APIKEY_PUBLIC, secrets.MJ_APIKEY_PRIVATE)) data = { 'FromEmail': '*****@*****.**', 'FromName': 'Idea Reminder', 'Subject': subject, 'Text-part': text_part, 'Html-part': html_part, 'Recipients': [{'Email': address}] } result = mailjet.send.create(data=data) logging.info(result.json())
def pwresetloggedoutemail(request): to = request.POST.get('email', '') subject = 'Temporary [PRODUCT NAME] Password' new_pw = User.objects.make_random_password() message =\ 'We received your password reset request for [PRODUCT NAME].\n\n'\ + 'Your new password is %s and we suggest that you reset this to '\ % new_pw\ + 'something easier to remember. If you did not request a '\ + 'password reset, please contact us at [SUPPORT to ADDRESS].\n\n'\ + 'If you have any questions, feel free to reply to this email.\n\n'\ + 'Regards,\n'\ + '[COMPANY NAME] Support' # from_email = settings.EMAIL_HOST_USER # request.user.email # to_list = [email] # print User.objects.filter(email=email) if User.objects.filter(email=to).exists(): u = User.objects.get(email=to) else: messagetext = \ 'We do not have the email address "%s" on file. ' % to\ + 'If this email address is correct, '\ + 'please contact [SUPPORT EMAIL ADDRESS]' messages.warning(request, messagetext) return HttpResponseRedirect('/changepwlo/') u.set_password(new_pw) u.save() # send_mail(subject, message, from_email, to_list, fail_silently=True) client = mailjet_rest.Client(auth=(settings.MAILJET_API_KEY, settings.MAILJET_API_SECRET)) data = { 'FromEmail': settings.MAILJET_SENDER, 'FromName': 'sdapp automated email', 'Subject': subject, 'Text-part': message, 'Html-part': message, 'Recipients': [{ 'Email': to }] } client.send.create(data=data) messagetext = \ 'You should receive a new temporary password shortly.' messages.warning(request, messagetext) return HttpResponseRedirect('/changepwlo/')
def test_too_many_get_message(self) -> None: """get_message when server has received too many get API requests already.""" message_id = mailjet_rest.Client(version='v3.1').send.create({ 'Messages': [{ 'To': [{ 'Email': '*****@*****.**', }], 'TemplateID': 123456, }] }).json()['Messages'][0]['To'][0]['MessageID'] mailjetmock.set_too_many_get_api_requests() with self.assertRaises(requests.HTTPError): mail.get_message(message_id)
def send_message(to): client = mailjet_rest.Client(auth=(MAILJET_API_KEY, MAILJET_API_SECRET)) data = { 'FromEmail': MAILJET_SENDER, 'FromName': 'App Engine Flex Mailjet Sample', 'Subject': 'Example email.', 'Text-part': 'This is an example email.', 'Html-part': 'This is an <i>example</i> email.', 'Recipients': [{ 'Email': to }] } result = client.send.create(data=data) return result.json()
def sync_to_mailjet(execute, delta_hours): conf = flask.current_app.config mailjet = mailjet_rest.Client(auth=(conf["MAILJET_API_KEY"], conf["MAILJET_API_SECRET"])) list_id = conf['MAILJET_PROPPRY_GENERAL_UPDATES_LIST_ID'] # Wait 5 days to sign people up to avoid spamming them before we # sent the introductory feedback email. # # Sync over delta_hours window and we run hourly so we collect everyone. cutoff = datetime.datetime.utcnow() - datetime.timedelta(days=5) start = cutoff - datetime.timedelta(hours=delta_hours) assert contactslist_exists(mailjet, list_id), "unexpected error: contactslists not found" unsubscribed = set(x.email for x in Unsubscribed.query.all()) contacts = list( dict(Email=x.email) for x in User.query.filter(User.created_at >= start, User.created_at < cutoff) if x.email not in unsubscribed ) remove = list(dict(Email=x) for x in unsubscribed) logging.info("Adding to contact list (there may be some overlap) from %s to %s; ListID: %s; Contacts: %s", start, cutoff, list_id, contacts) if execute: # See https://dev.mailjet.com/guides/#contact_managemanycontacts response = mailjet.contactslist_managemanycontacts.create({ "Action": "addnoforce", "Contacts": contacts, }, id=list_id) if not response.ok: logging.error("mailjet upload failed: %s", response.json()) # TODO wait for job to finish to report status. # mailjet_rest.client.api_call(mailjet.auth, 'get', 'https://api.mailjet.com/v3/REST/contactslist/18112/managemanycontacts/7040130', {}) # Expliclty unsubscribe people in case they're still stuck response = mailjet.contactslist_managemanycontacts.create({ "Action": "remove", "Contacts": remove, }, id=list_id) if not response.ok: logging.error("mailjet removing failed: %s", response.json())
def _send_mailjet(message, subject, to, to_name, sender, sender_name): """Mailjet implementation of sending email.""" api_key = app.config.get('MJ_APIKEY_PUBLIC') api_secret = app.config.get('MJ_APIKEY_PRIVATE') if not api_key or not api_secret: app.logger.error('Missing MJ_APIKEY_PUBLIC/MJ_APIKEY_PRIVATE!') return # Note the data structures we use are api v3.1 client = mailjet_rest.Client( auth=(api_key, api_secret), api_url='https://api.mailjet.com/', version='v3.1') from_obj = { "Email": sender, } if sender_name: from_obj["Name"] = sender_name to_obj = [{ "Email": to, }] if to_name: to_obj[0]["Name"] = to_name message = { "From": from_obj, "To": to_obj, "Subject": subject, "TextPart": message, } result = client.send.create(data={'Messages': [message]}) if result.status_code != 200: app.logger.error( 'Error sending via mailjet: (%d) %r', result.status_code, result.text) raise MailFailure('Error sending via mailjet!') try: j = result.json() except Exception: app.logger.error('Error sending via mailjet: %r', result.text) raise MailFailure('Error sending via mailjet!') if j['Messages'][0]['Status'] != 'success': app.logger.error('Error sending via mailjet: %r', j) raise MailFailure('Error sending via mailjet!')
def send_email_mailjet(to, body): mailjet = mailjet_rest.Client(auth=(MJ_API_KEY, MJ_API_SECRET), version='v3.1') data = { 'Messages': [{ "From": { "Email": "*****@*****.**", "Name": "6pm.com checker" }, "To": [{ "Email": to }], "Subject": "6pm.com updates", "HTMLPart": body }] } result = mailjet.send.create(data=data) if result.status_code == 200: logging.info('Send email to ' + to) else: logging.error('Send email failed to {}: {}'.format(to, result.json()))
def send_message(to): client = mailjet_rest.Client( auth=(MAILJET_API_KEY, MAILJET_API_SECRET), version='v3.1') data = { 'Messages': [{ "From": { "Email": MAILJET_SENDER, "Name": 'App Engine Standard Mailjet Sample' }, "To": [{ "Email": to }], "Subject": 'Example email.', "TextPart": 'This is an example email.', "HTMLPart": 'This is an <i>example</i> email.' }] } result = client.send.create(data=data) return result.json()
def send_email(to_user: dict, subject: str, html_message: str) -> int: """ Sends an email to the provided user with the provided info. """ with open(CREDENTIALS_PATH) as fp: content = fp.readline() # get keys secret_keys = json.loads(content) api_key = secret_keys["mailjet_keys"]["api_key"] api_secret = secret_keys["mailjet_keys"]["api_secret"] # package data mailjet = mailjet_rest.Client(auth=(api_key, api_secret), version='v3.1') data = { 'Messages': [{ "From": { "Email": "*****@*****.**", "Name": "Achieve System" }, "To": [{ "Email": to_user["email"], "Name": to_user["first_name"] + " " + to_user["last_name"] }], "Subject": subject, # "TextPart": "My first Mailjet email", "HTMLPart": html_message, "CustomID": "PasswordReset" }] } # send email result = mailjet.send.create(data=data) return result.status_code
def __init__(self, api_key, secret_key): self.client = mailjet_rest.Client(auth=(api_key, secret_key), version='v3.1')
def __init__(self, *, api_key: str, api_secret: str): self.client = mailjet.Client(auth=(api_key, api_secret), version='v3.1') # type: mailjet.Client
def _get_api_client(): api_key = settings.MAILJET_API_KEY secret_key = settings.MAILJET_SECRET_KEY return mailjet.Client(auth=(api_key, secret_key))
}, 'data': { 'keyname': 'shrini' }, 'to': '/topics/fte_books' } data = json.dumps(data, ensure_ascii=False) data_json = json.loads(data) api = "https://fcm.googleapis.com/fcm/send" r = requests.post(api, json=data_json, headers=header_json) #print(r.json()) mailjet = mailjet_rest.Client(auth=(mailjet_api_key, mailjet_api_secret), version='v3.1') if len(artist_email.strip()) < 2: artist_email = "*****@*****.**" if len(artist.strip()) < 2: artist = "Kaniyam Foundation" if len(translator_email.strip()) < 2: translator_email = "*****@*****.**" if len(translator.strip()) < 2: translator = "Kaniyam Foundation" if len(ebook_maker_email.strip()) < 2: ebook_maker_email = "*****@*****.**"
def _mailjet_client(): return mailjet_rest.Client(auth=(_MAILJET_APIKEY_PUBLIC, _MAILJET_SECRET))
def __init__(self): super().__init__() auth = (settings.MAILJET_API_KEY, settings.MAILJET_API_SECRET) self.mailjet_client = mailjet_rest.Client(auth=auth, version="v3")
def _mailjet_client(version: Optional[str] = None) -> mailjet_rest.Client: return mailjet_rest.Client(auth=(_MAILJET_APIKEY_PUBLIC, _MAILJET_SECRET), version=version)
def client(self): return mailjet.Client( auth=(settings.MAILJET_API_KEY, settings.MAILJET_SECRET_KEY), version='v3', )
import mailjet_rest import os username = os.environ['mailjet_username'] password = os.environ['mailjet_password'] client = mailjet_rest.Client(auth=(username, password), version='v3') def send_invite_email(invitor, email): data = { 'FromName': 'LiveSWOT', 'FromEmail': '*****@*****.**', 'Subject': 'Test Email', 'HTML-Part': ''.join([ '<html><body>', '<p>Hey there!<p>', '<p>Your college {} has invited to contribute to a swot.</p>'. format(invitor), '<p>Signup <a href=\'http://localhost:3000/login/\'>here</a> to join the swot</p>', '<p>Cheers,</p>', '<p>liveSWOT team</p>', '</body></html>' ]), 'Recipients': [{ 'Email': email }] } client.send.create(data)