Beispiel #1
0
def send(sender_instance):
    """Send a transactional email using SendInBlue API.

    Site: https://www.sendinblue.com
    API: https://apidocs.sendinblue.com/
    """
    m = Mailin("https://api.sendinblue.com/v2.0",
               sender_instance._kwargs.get("api_key"))
    data = {
        "to": email_list_to_email_dict(sender_instance._recipient_list),
        "cc": email_list_to_email_dict(sender_instance._cc),
        "bcc": email_list_to_email_dict(sender_instance._bcc),
        "from": email_address_to_list(sender_instance._from_email),
        "subject": sender_instance._subject,
    }
    if sender_instance._template.is_html:
        data.update({
            "html": sender_instance._message,
            "headers": {
                "Content-Type": "text/html; charset=utf-8"
            }
        })
    else:
        data.update({"text": sender_instance._message})
    if "attachments" in sender_instance._kwargs:
        data["attachment"] = {}
        for attachment in sender_instance._kwargs["attachments"]:
            data["attachment"][attachment[0]] = base64.b64encode(attachment[1])
    result = m.send_email(data)
    if result["code"] != "success":
        raise SendInBlueError(result["message"])
Beispiel #2
0
    def get(self, request, email, format=None):
        try:
            account = User.objects.get(email=email)
            print("it worked")
        except:
            print("It didnt work")
            return Response({'account_found': False})

        # account = account.first()
        if account:
            password_token = ''.join(
                random.choice(string.ascii_uppercase + string.digits)
                for _ in range(6))
            account.profile.password_reset_token = password_token
            account.profile.save(update_fields=['password_reset_token'])
            m = Mailin("https://api.sendinblue.com/v2.0",
                       config('SENDINBLUE_V2_KEY'))
            data = {
                "to": {
                    email: "to whom!"
                },
                "from": ["*****@*****.**", "Password Reset"],
                "subject":
                "Password Reset",
                "html":
                "<h1>Password Reset</h1>\n\
				Here is your password reset token: <strong>" + password_token + "</strong>"
            }
            result = m.send_email(data)
            return Response({'account_found': True})
        return Response({'account_found': False})
Beispiel #3
0
    def post_to_sendinblue(self, payload, message):
        """Post payload to correct SendinBlue send API endpoint, and return the response.

        payload is a dict to use as SendinBlue send data
        return should be a requests.Response

        Can raise NotSerializableForSendinBlueError if payload is not serializable
        Can raise DJBlueAPIError for HTTP errors in the post
        """
       
        msg = Mailin(self.api_url,self.api_key)
        if not getattr(message, 'template_id', False):
            payload.update({'text':message.body})

            response,content = msg.send_email(payload)
        else:
            payload['to'] = payload['to'].keys()[0]
            response,content = msg.send_transactional_template(payload)

        

        # response = self.session.post(self.api_url, data=json_payload)
        if response.status != 200:
            raise DJBlueAPIError(email_message=message, payload=payload, response=response)
        return content
Beispiel #4
0
def send(sender_instance):
    """Send a transactional email using SendInBlue API.

    Site: https://www.sendinblue.com
    API: https://apidocs.sendinblue.com/
    """
    m = Mailin("https://api.sendinblue.com/v2.0", sender_instance._kwargs.get("api_key"))
    data = {
        "to": email_list_to_email_dict(sender_instance._recipient_list),
        "cc": email_list_to_email_dict(sender_instance._cc),
        "bcc": email_list_to_email_dict(sender_instance._bcc),
        "from": email_address_to_list(sender_instance._from_email),
        "subject": sender_instance._subject,
    }
    if sender_instance._template.is_html:
        data.update({"html": sender_instance._message, "headers": {"Content-Type": "text/html; charset=utf-8"}})
    else:
        data.update({"text": sender_instance._message})
    if "attachments" in sender_instance._kwargs:
        data["attachment"] = {}
        for attachment in sender_instance._kwargs["attachments"]:
            data["attachment"][attachment[0]] = base64.b64encode(attachment[1])
    result = m.send_email(data)
    if result["code"] != "success":
        raise SendInBlueError(result["message"])
Beispiel #5
0
def send_email(email_type, user_email):
    try:
        if email_type=="f":
            subject = "Reset Password Link"
            body = 'tweet_account/forgot_password.html'
            string_content = html_to_string(body, user_email, "f")

        elif email_type =="a":

            subject = "Verify Your Email"
            body = 'tweet_account/activation_email.html'
            string_content = html_to_string(body, user_email, "a")

        elif email_type =="w":

            subject = "Welcome To Social Media Villa"
            body = 'tweet_account/welcome_email.html'
            string_content = html_to_string(body, user_email, "w")

        else:
            return False

        email = Mailin("https://api.sendinblue.com/v2.0", settings.MAILIN_SECRET_KEY)
        email.send_email({
            "to": {user_email: "to "+user_email},
            "from": ["*****@*****.**", "Social Media Villa"],
            "subject": subject,
            "html": string_content,
            "attachment": []
        })
        return email
    except Exception as e:
        traceback.print_exc()
        return False
Beispiel #6
0
def email(user_obj, email_type):
    """ Utility email function
		* template: takes a the file name of a email template in the templates directory, email dir is appended already
		* kwargs: takes a object with keys appropriate to the message
	"""
    user_email = user_obj.email

    if config('EMAIL_ON', default=False, cast=bool):
        try:
            auth_token = ""
            if True:
                auth_token = ''.join(
                    random.choice(string.ascii_uppercase + string.digits)
                    for _ in range(6))
                user_obj.profile.email_auth_token = auth_token
                user_obj.profile.save(update_fields=['email_auth_token'])
            m = Mailin("https://api.sendinblue.com/v2.0",
                       config('SENDINBLUE_V2_KEY'))
            data = {
                "to": {
                    user_email: "to whom!"
                },
                "from": ["*****@*****.**", "Welcome to Granite!"],
                "subject":
                "Account Authentication",
                "html":
                "<h1>Welcome to Granite!</h1>\nYour account has been successfully registered!\n\
				 Please visit https://www.granite.gg/authentication and enter in <strong>"
                + auth_token + "</strong> to authenticate your account"
            }
            result = m.send_email(data)
        except:
            print("Email error")
Beispiel #7
0
def send_email_async(subject, to_email, content):
    m = Mailin("https://api.sendinblue.com/v2.0",
               os.getenv('SENDINBLUE_API_KEY'))
    data = {
        "to": {
            to_email: "to maintainer!"
        },
        "from": [os.getenv('PROJECT_MAINTAINER'), "from email!"],
        "subject": subject,
        "html": "<h1>" + content + "</h1>",
    }
    m.send_email(data)
Beispiel #8
0
def emailfunc2(email, name):
    m = Mailin("https://api.sendinblue.com/v2.0", "f3zYcrFqMjtUxn5T")

    data = {
        "to": {
            email: name
        },
        "from": ["*****@*****.**", "Camelot Wellness"],
        "subject": "Thanks",
        "html": "Thank you for contacting us!!. Happy to help you...."
    }

    result = m.send_email(data)
    print(result)
Beispiel #9
0
    def sendinblue_email(to, from_address, subject, text):
        m = Mailin("https://api.sendinblue.com/v2.0", "fTUanjNP10bYs2yV")
        data = {
            "to": {
                to: "to maddy!"
            },
            "from": [from_address, "from email!"],
            "subject": subject,
            "html": text
        }

        result = m.send_email(data)
        print(result)
        return result
def emailfunc1(email, name):
    m = Mailin("https://api.sendinblue.com/v2.0", "f3zYcrFqMjtUxn5T")

    data = {
        "to": {
            email: name
        },
        "from": ["*****@*****.**", "Camelot Wellness"],
        "subject": "Register",
        "html": "Hi register"
    }

    result = m.send_email(data)
    print(result)
Beispiel #11
0
def post_send(sender, **kwargs):

    from mailin import Mailin
    from django.conf import settings
    from blog.models import Profile
    from django.template.loader import render_to_string
    from datetime import datetime

    page = kwargs['instance']

    is_sent = bool(False) if page.sent_date is None else bool(True)
    if is_sent is True:
        return None

    subject = page.title + ' | ' + page.intro

    root_url = 'https://www.hannahandkevin.net'
    homepage_url = root_url + "?utm_source=post-send&utm_medium=email"
    post_url = root_url + page.get_url() + "?utm_source=post-send&utm_medium=email"

    banner_image = page.banner_image.get_rendition('fill-580x280').url
    aws_url = settings.AWS_CLOUDFRONT_URL
    old_url = settings.MEDIA_URL + 'images/'
    banner_image_url = banner_image.replace(old_url, aws_url)

    context = {"banner_image_url": banner_image_url, "homepage_url": homepage_url, "post_url": post_url, "root_url": root_url}

    body = render_to_string('post_email.html', context)

    recipients = Profile.objects.filter(active=True, email_per_post=True)

    for receiver in recipients:

        to = receiver.first_name + ' ' + receiver.last_name
        email = receiver.email

        m = Mailin("https://api.sendinblue.com/v2.0", settings.EMAIL_KEY)
        data = {"to": {email: to},
                "from": ["*****@*****.**", "H&K Away"],
                "replyto": ["*****@*****.**", "H&K Away"],
                "subject": subject,
                "html": body,
                }
        result = m.send_email(data)

    page = page.specific
    page.sent_date = datetime.now()
    page.save()

    return None
Beispiel #12
0
def sendmail():
    name = request.json['name']
    email = request.json['email']
    car_types = request.json['car_types']
    start_date = request.json['start_date']
    end_date = request.json['end_date']
    message = request.json['message']

    car_list = car_types.split(",")
    car_name = ""
    for i, car in enumerate(car_list):
        if car == "1":
            car_name += "Pequeno utilitário"
        elif car == "2":
            car_name += "Utilitário"
        elif car == "3":
            car_name += "Utilitário económico"
        elif car == "4":
            car_name += "Carrinha"
        elif car == "5":
            car_name += "Monovolume"

        if i != len(car_list) - 1:
            car_name += ", "

    body = "Tipo de carro: " + car_name + "<br/>"
    body += "Data: " + start_date + " até " + end_date + "<br/>"
    body += "Mensagem: " + message + "<br/>"

    # [email protected]
    m = Mailin("https://api.sendinblue.com/v2.0", "NgycrTYUqFICXhBv")
    data = {
        "to": {
            "*****@*****.**": "Seguros Parente"
        },
        "from": [email, name],
        "subject": "Rent a Car - Pedido de Simulação",
        "html": body
    }

    result = m.send_email(data)
    if result['code'] == 'success':
        return json.dumps({'success': True}), 200, {
            'ContentType': 'application/json'
        }
    else:
        return json.dumps({'error': True}), 500, {
            'ContentType': 'application/json'
        }
def emailfunc3():
    m = Mailin("https://api.sendinblue.com/v2.0", "f3zYcrFqMjtUxn5T")

    data = {
        "to": {
            "*****@*****.**": "Aditya",
            "*****@*****.**": "Archish"
        },
        "from": ["*****@*****.**", "Camelot Wellness"],
        "subject": "New Request",
        "html": "You got a contact us request... check the same by logging in"
    }

    result = m.send_email(data)
    print(result)
def emailfunc4(email, name, link):
    m = Mailin("https://api.sendinblue.com/v2.0", "f3zYcrFqMjtUxn5T")

    kk = "127.0.0.1:5000/Reset/"
    kk += link

    data = {
        "to": {
            email: name
        },
        "from": ["*****@*****.**", "Camelot Wellness"],
        "subject": "Password Reset Link",
        "html": "Click on the link to reset " + kk,
    }

    result = m.send_email(data)
    print(result)
Beispiel #15
0
def send_query(create_id, email1, subject, content):
    try:
        contact_obj = ContactUs.objects.get(id=create_id)
        email = Mailin("https://api.sendinblue.com/v2.0", settings.MAILIN_SECRET_KEY)
        email.send_email({
            "to": {"*****@*****.**": "to Social Media Villa"},
            "from": [email1, email1],
            "subject": "Request For Pricing",
            "html": content,
            "attachment": []
        })
        #contact_obj.status = email
        #contact_obj.save()
        return email

    except Exception as e:
        traceback.print_exc()
        return str(e)
Beispiel #16
0
def Send_registration_email(emailAddress, activation_url):
	file = open('/var/www/html/ShotForTheHeart/ShotForTheHeart/Credentials').read()
	credentials = eval(file)
	mailSystem = Mailin("https://api.sendinblue.com/v2.0", credentials['email'])
	message = {
		'to' : {'*****@*****.**':'Rick Knoop'},
		'from' : ['*****@*****.**' , 'Shot for the heart Guelph'],
		'subject' : 'Activate your account',
		'html' : 'Hello<br>You recently decided to register for an account at the Shot for the Heart website. Please click the link below to activate your account.<br><br>http://shotfortheheart.ca/register/'+activation_url+'<br><br>Thanks,<br>Shot for the Heart system administator.',
	}
	result = mailSystem.send_email(message)
	if 'failure' in result['code']:
		try:
			file = open('/var/www/html/ShotForTheHeart/emailError.log', 'w+')
			file.write(str(timezone.now)+' email address: '+str(user_email)+' Error information: '+str(result)+'\n\n')
			file.close()
		except:
			pass
		return {'ERROR': 'Your account was created correctly, but the email failed. Please contact [email protected]'}
	else:
		return {'VALID': 'Everything worked succesfully'}
Beispiel #17
0
def send_mail(link, dest_mail, dest_name):
    '''
    Gère l'envoie du mail en template et du lien pour le téléchargement du fichier

    :param link:
    :type link: str
    :param dest_mail:
    :param dest_name:
    :return:
    :rtype:
    '''

    # Instantiate the client\
    m = Mailin(base_url="https://api.sendinblue.com/v2.0",
               api_key=config().get('mailer', 'apikey'))

    # Define the campaign settings\
    data = {
        "subject":
        "Votre recherche sur Ansène.eu",
        "to": {
            dest_mail: dest_name
        },
        "from": ["*****@*****.**", "Ansène!"],
        "html":
        "Vous pouvez dès à présent télécharger le résultat de votre recherche ici: {0}"
        .format(link)
    }

    # curl - H    'api-key:S8LaGpt4HUxP5XOQ' - X
    # POST - d    '{"to":{"*****@*****.**":"Client"}, "from":["*****@*****.**","Ansene"],' \
    #             ' "subject":"First email", "html":"This is the <h1>HTML</h1>"}'\
    #             'https://api.sendinblue.com/v2.0/email'

    # Make the call to the client\
    result = m.send_mail(data)

    return result
Beispiel #18
0
def email(request):

    from mailin import Mailin
    from django.conf import settings

    to = 'Lil Kev'
    email = '*****@*****.**'

    subject = 'SiB Web Hook'
    body = str(request.body)

    m = Mailin("https://api.sendinblue.com/v2.0", settings.EMAIL_KEY)
    data = {
        "to": {
            email: to
        },
        "from": ["*****@*****.**", "H&K Away"],
        "replyto": ["*****@*****.**", "H&K Away"],
        "subject": subject,
        "html": body,
    }
    result = m.send_email(data)

    return HttpResponse('OK')
Beispiel #19
0
from mailin import Mailin

m = Mailin("https://api.sendinblue.com/v1.0", "access key", "secret key")
campaigns = m.get_campaigns("classic")  # to retrieve all campaigns of type 'classic'
campaigns = m.get_campaigns("")  # to retrieve all campaigns
Beispiel #20
0
import requests
import json
import datetime
import redis
from apscheduler.schedulers.blocking import BlockingScheduler
import logging
from mailin import Mailin
import ConfigParser

# Init Parser
parser = ConfigParser.RawConfigParser()

# Email TODO - api key needs to be changed
mail_conf_path = r'/var/xrp_config/xrp_mailin.ini'
parser.read(mail_conf_path)
m = Mailin(parser.get('mailin', 'url'), parser.get('mailin', 'key'))

# Node Connection
xrp_node_conf_path = r'/var/xrp_config/xrp_node.ini'
parser.read(xrp_node_conf_path)
URL = parser.get('ripple_node', 'url')

# Redis Connection
xrp_redis_conf_path = r'/var/xrp_config/xrp_redis.ini'
parser.read(xrp_redis_conf_path)
pool = redis.ConnectionPool(host=parser.get('redis', 'host'),
                            port=int(parser.get('redis', 'port')),
                            db=int(parser.get('redis', 'db')))
r = redis.Redis(connection_pool=pool)

# Reference
Beispiel #21
0
from mailin import Mailin

m = Mailin("https://api.sendinblue.com/v1.0", "access key", "secret key")
campaigns = m.get_campaigns(
    'classic')  # to retrieve all campaigns of type 'classic'
campaigns = m.get_campaigns('')  # to retrieve all campaigns
Beispiel #22
0
def trigger_email(request, page):

    from mailin import Mailin
    from django.conf import settings
    from blog.models import BlogEmailPage, Profile
    from django.template.loader import render_to_string
    from django.http import HttpRequest
    from datetime import datetime

    is_email = bool(True) if page.specific_class == BlogEmailPage else bool(
        False)
    if not is_email:
        return None

    is_publishing = bool(request.POST.get('action-publish'))
    if is_publishing is False:
        return None

    is_sent = bool(False) if page.sent_date is None else bool(True)
    if is_sent is True:
        return None

    request = HttpRequest()
    request.method = 'GET'

    template = page.get_template(request)
    context = page.get_context(request)

    recipients = Profile.objects.filter(active=True)

    for receiver in recipients:
        to = receiver.first_name + ' ' + receiver.last_name
        email = receiver.email

        if page.debug_mode:
            if to != 'Preston Davis':
                continue
        else:
            if to == 'Preston Davis':
                continue

        subject = page.title
        context['secret_key'] = receiver.secret_key

        body = render_to_string(template, context)

        m = Mailin("https://api.sendinblue.com/v2.0", settings.EMAIL_KEY)
        data = {
            "to": {
                email: to
            },
            "from": ["*****@*****.**", "H&K Away"],
            "replyto": ["*****@*****.**", "H&K Away"],
            "subject": subject,
            "html": body,
        }
        result = m.send_email(data)

    page = page.specific
    page.sent_date = datetime.now()
    page.save()

    return None
Beispiel #23
0
def contact(request):

    import time
    import requests
    from mailin import Mailin
    from django.conf import settings

    from blog.forms import ContactForm
    from django.shortcuts import render, redirect
    from django.utils.html import linebreaks

    if request.method == 'POST':
        form = ContactForm(request.POST)
        if form.is_valid():
            ''' Begin reCAPTCHA validation '''
            recaptcha_response = request.POST.get('g-recaptcha-response')
            data = {
                'secret': settings.CAPTCHA_KEY,
                'response': recaptcha_response
            }
            r = requests.post(
                'https://www.google.com/recaptcha/api/siteverify', data=data)
            result = r.json()
            ''' End reCAPTCHA validation '''

            now = time.time()
            last_comment = request.session.get('last_comment', 0)
            request.session['last_comment'] = now

            if not result['success']:
                error = 'Are you a robot? Google seems to think so...'
                context = {'error': error}
                return render(request, 'error.html', context)

            if now - last_comment > 60:
                to = {
                    '*****@*****.**': 'Kevin',
                    '*****@*****.**': 'Hannah'
                }
                from_name = form.cleaned_data.get('name')
                from_email = form.cleaned_data.get('email')
                subject = form.cleaned_data.get('subject')
                body = linebreaks(form.cleaned_data.get('message'))

                m = Mailin("https://api.sendinblue.com/v2.0",
                           settings.EMAIL_KEY)
                data = {
                    "to": to,
                    "from": ["*****@*****.**", from_name],
                    "replyto": [from_email, from_name],
                    "subject": subject,
                    "html": body,
                }
                result = m.send_email(data)
                return redirect('https://www.hannahandkevin.net')
            else:
                error = 'There is a one minute wait timer between sends. Please go back, wait a moment, and try again.'
                context = {'error': error}
                return render(request, 'error.html', context)

    else:
        form = ContactForm()

    return render(request, 'contact.html', {'form': form})
Beispiel #24
0
from mailin import Mailin
from flask import request

import config

m = Mailin("https://api.sendinblue.com/v2.0", config.send_in_blue)


def send_mail(name, email, subject, body):
    data = {
        "to": {
            email: name
        },
        "from": ["*****@*****.**", "🔥 Matcha 🔥"],
        "subject": subject,
        "html": body
    }

    return m.send_email(data)


def send_validation_email(user, code):

    base = config.frontend_uri
    name = "{0} {1}".format(user.fname, user.lname)

    html = """
    <div>
      <h3>Hello {name}, welcome to Matcha</h3>
      <p>Please validate your email by clicking the link below</p>
      <a href="{base}/validate?code={code}">Verify Email</a>
from mailin import Mailin

m = Mailin("https://api.sendinblue.com/v2.0","access key")
campaigns = m.get_campaigns_v2('classic') # to retrieve all campaigns of type 'classic'
campaigns = m.get_campaigns_v2('') # to retrieve all campaigns
from mailin import Mailin

m = Mailin("https://api.sendinblue.com/v2.0", "access key")

# to retrieve all campaigns of type 'classic' & status 'queued'
data = {"type": "classic", "status": "queued", "page": 1, "page_limit": 10}

campaigns = m.get_campaigns_v2(data)
Beispiel #27
0
from mailin import Mailin

m = Mailin("https://api.sendinblue.com/v2.0","access key")

# to retrieve all campaigns of type 'classic' & status 'queued'
data = { "type":"classic",
	"status":"queued",
	"page":1,
	"page_limit":10
}

campaigns = m.get_campaigns_v2(data)