Beispiel #1
0
class MultipleSMTPEmailBackend(BaseEmailBackend):
    def __init__(self, host=None, fail_silently=False, **kwargs):
        super(MultipleSMTPEmailBackend, self).__init__(fail_silently=fail_silently)

        self.bulk = SMTPEmailBackend(host=settings.EMAIL_HOST['bulk']['host'],
                port=settings.EMAIL_HOST['bulk']['port'],
                fail_silently=fail_silently, **kwargs)
        self.transactional = SMTPEmailBackend(host=settings.EMAIL_HOST['transactional']['host'],
                port=settings.EMAIL_HOST['transactional']['port'],
                fail_silently=fail_silently, **kwargs)

    def open(self):
        return self.bulk.open() and self.transactional.open()

    def close(self):
        self.bulk.close()
        self.transactional.close()

    def split_messages(self, email_messages):
        """Split messages list to send in 2 groups regarding their from_email field."""
        bulk, transactional = [], []
        for message in email_messages:
            from_email = sanitize_address(message.from_email, message.encoding)
            if settings.BULK_EMAIL_DEFAULT_FROM_EMAIL in from_email:
                bulk.append(message)
            else:
                transactional.append(message)
        return bulk, transactional

    def send_messages(self, email_messages):
        bulk_messages, transactional_messages = self.split_messages(email_messages)

        return ((self.bulk.send_messages(bulk_messages) or 0)
                + (self.transactional.send_messages(transactional_messages) or 0))
Beispiel #2
0
def recruiters(request):
	from social.forms import RecruiterInterestForm
	# check to see if email submitted
	if request.POST:
		form = RecruiterInterestForm(request.POST)
		
		
		# validate form
		
		if form.is_valid():
			from django.core.mail.backends.smtp import EmailBackend
			from django.core.mail import EmailMultiAlternatives
			backend = EmailBackend()
			msg = EmailMultiAlternatives("ProsperMe: New recruiter signup","New signup: " + form.cleaned_data['email'],"*****@*****.**",["*****@*****.**"])
			try:
				backend.send_messages([msg])
				logger.info("New recruiter added: "+form.cleaned_data['email'])
			except:
				logger.error("Failed to email new recruiter: "+form.cleaned_data['email'])
			return HttpResponseRedirect("/recruiters/thanks/")

	else:
		form = RecruiterInterestForm()

	return render_to_response("recruiters.html",{'form':form},context_instance=RequestContext(request))
def myView(request):
    try:
        backend = EmailBackend(
          host='EMAIL_HOST',
          # Port 587 recomended for SMTP
          port=587,
          username='******',
          password='******',
          use_tls=True
        )
        backend.open()
        subject = 'My subject'
        '''
          If you want html message can do:
          from django.template.loader import render_to_string
          message = render_to_string('template.html')
        '''
        message = 'Hi!'
        sender = '*****@*****.**'
        # List of recipients
        recipients = ['*****@*****.**']
        email = EmailMessage(subject, message, sender, recipients)
        email.content_subtype = "html"
        backend.send_messages([email])
        backend.close()
    except Exception,e:
        print(e)
        return render(request, "error.html")
Beispiel #4
0
class EmailBackend(BaseEmailBackend):
    def __init__(self, *args, **kwargs):
        self._smtpBackend = SmtpEmailBackend(*args, **kwargs)
        self._consoleBackend = ConsoleEmailBackend(*args, **kwargs)
        super().__init__(**kwargs)

    def send_messages(self, email_messages):
        self._smtpBackend.send_messages(email_messages)
        if settings.DEBUG:
            self._consoleBackend.send_messages(email_messages)
Beispiel #5
0
def send_mail(subject, body):

    try:
        mailob = AlertMailModel.objects.first()

        con = mail.get_connection(host=mailob.host_smtpaddress,
                                  port=mailob.port,
                                  fail_silently=False)
        try:
            con.open()
            print('Django connected to the SMTP server')

        except Exception as e:
            print(e.errno, e.strerror)

        ferob = Fernet(settings.FERNET_SECRET_KEY)

        # host = 'smtp.gmail.com'
        # host_user = '******'
        # host_pass = '******'
        # host_port = 587

        host = mailob.host_smtpaddress
        host_user = mailob.host_mail
        host_pass = ferob.decrypt(mailob.mail_host_password.encode()).decode()
        host_port = mailob.port
        tls = mailob.use_tls

        mail_obj = EmailBackend(host=host,
                                port=host_port,
                                password=host_pass,
                                username=host_user,
                                use_tls=True,
                                timeout=10)

        msg = mail.EmailMultiAlternatives(
            subject=subject,
            body=strip_tags(body),
            from_email=host_user,
            to=[mailob.receipient_mail],
            connection=con,
        )
        msg.attach_alternative(body, "text/html")
        mail_obj.send_messages([msg])
        print('Message has been sent.')

        mail_obj.close()
        print('SMTP server closed')
        return True

    except Exception as _error:
        print(_error)
        print('Error in sending mail >> {} {}'.format(
            str(_error.smtp_code), _error.smtp_code.decode()))
        return False
Beispiel #6
0
class BaseMailer():
    def __init__(self, message_to, context, subject, template, sndr_host,
                 sndr_username, sndr_pass, sndr_port, sndr_tls,
                 **substitutions):

        self.con = mail.get_connection()

        self.message_to = message_to
        self.subject = subject
        self.body_msg = render_to_string(template, context)

        self.sndr_host = sndr_host
        self.sndr_port = sndr_port
        self.sndr_username = sndr_username
        self.sndr_pass = sndr_pass
        self.sndr_tls = sndr_tls

        # sth like request o algo asi xd
        self.substitutions = {}

        for key in substitutions:
            self.substitutions.update({key: substitutions[key]})

    def create_email(self):
        # creating connection
        self.con.open()

        #filling the connection (EmailBackend) object
        self.mail_obj = EmailBackend(host=self.sndr_host,
                                     port=self.sndr_port,
                                     username=self.sndr_username,
                                     password=self.sndr_pass,
                                     use_tls=self.sndr_tls)

        # filling the EmailMessage object
        self.mail = mail.EmailMessage(subject=self.subject,
                                      body=self.body_msg,
                                      from_email=self.sndr_username,
                                      to=[self.message_to],
                                      connection=self.con)

    def send_email(self):
        self.create_email()
        try:
            self.mail.content_subtype = 'html'
            # self.con.send_messages([self.mail]) #sending email with the current connection, this is intended to send messages to multiple mails w/ the same conn
            # self.mail.send(self.mail) #sending email with the EmailMessage object
            self.mail_obj.send_messages([self.mail
                                         ])  #sending email with EmailBackend
            self.con.close()
            return True
        except Exception as e:
            print(f'\n\n# --- PY: Error sending email: --- #\n{e}')
            return False
Beispiel #7
0
    def send_messages(self, email_messages):
        """
        Intercept emails originating from SERVER_EMAIL and send them
        through SMTPBackend to notify ADMINS.
        """
        server_email = getattr(settings, 'SERVER_EMAIL', None)

        admin_messages = filter(lambda x: x.from_email == server_email,
                                email_messages)

        if admin_messages:
            smtp_backend = SMTPBackend()
            smtp_backend.send_messages(admin_messages)

        return super(DevEmailBackend, self).send_messages(email_messages)
Beispiel #8
0
    def send_messages(self, email_messages):
        """
        Intercept emails originating from SERVER_EMAIL and send them
        through SMTPBackend to notify ADMINS.
        """
        server_email = getattr(settings, 'SERVER_EMAIL', None)

        admin_messages = filter(lambda x: x.from_email == server_email,
                                email_messages)

        if admin_messages:
            smtp_backend = SMTPBackend()
            smtp_backend.send_messages(admin_messages)

        return super(DevEmailBackend, self).send_messages(email_messages)
class DevEmailBackend:
    """
        Custom mail backend that uses MailCatcher but falls back to console if
        MailCatcher server is not running.
        Your dev settings should include the following to work with MailCatcher.
        EMAIL_HOST = '127.0.0.1'
        EMAIL_PORT = 1025
    """
    def __init__(self, *args, **kwargs):
        self.email_backend = DjangoEmailBackend(*args, **kwargs)
        self.console_backend = DjangoConsoleBackend(*args, **kwargs)

    def send_messages(self, email_messages):
        try:
            return self.email_backend.send_messages(email_messages)
        except Exception:
            return self.console_backend.send_messages(email_messages)

    def open(self):
        """
        Stub method that allows the Wagtail backend to not fatal error
        when it's trying to send emails, such as moderation emails.
        """
        pass

    def close(self):
        """
        Stub method that allows the Wagtail backend to not fatal error
        when it's trying to send emails, such as moderation emails.
        """
        pass
Beispiel #10
0
class EmailBackend(SmtpEmailBackend):
    def __init__(self, *args, **kwargs):
        fail_silently = kwargs.pop('fail_silently', False)
        kwargs['fail_silently'] = False
        super(EmailBackend, self).__init__(*args, **kwargs)
        kwargs['fail_silently'] = fail_silently

        host = getattr(settings, 'ALTERNATIVE_EMAIL_HOST', None)
        port = getattr(settings, 'ALTERNATIVE_EMAIL_PORT', None)

        if host is not None and port is not None:
            kwargs['username'] = getattr(settings,
                                         'ALTERNATIVE_EMAIL_HOST_USER',
                                         self.username)
            kwargs['password'] = getattr(settings,
                                         'ALTERNATIVE_EMAIL_HOST_PASSWORD',
                                         self.password)
            kwargs['use_tls'] = getattr(settings, 'ALTERNATIVE_EMAIL_USE_TLS',
                                        self.use_tls)
            self._alternative_backend = SmtpEmailBackend(host=host,
                                                         port=port,
                                                         **kwargs)
        else:
            self._alternative_backend = None

    def send_messages(self, email_messages):
        try:
            return super(EmailBackend, self).send_messages(email_messages)
        except Exception as e:
            if self._alternative_backend:
                return self._alternative_backend.send_messages(email_messages)
            else:
                raise e
class EmailBackend(SmtpEmailBackend):
    def __init__(self, *args, **kwargs):
        fail_silently = kwargs.pop('fail_silently', False)
        kwargs['fail_silently'] = False
        super(EmailBackend, self).__init__(*args, **kwargs)
        kwargs['fail_silently'] = fail_silently

        host = getattr(settings, 'ALTERNATIVE_EMAIL_HOST', None)
        port = getattr(settings, 'ALTERNATIVE_EMAIL_PORT', None)

        if host is not None and port is not None:
            kwargs['username'] = getattr(settings, 'ALTERNATIVE_EMAIL_HOST_USER', self.username)
            kwargs['password'] = getattr(settings, 'ALTERNATIVE_EMAIL_HOST_PASSWORD', self.password)
            kwargs['use_tls'] = getattr(settings, 'ALTERNATIVE_EMAIL_USE_TLS', self.use_tls)
            self._alternative_backend = SmtpEmailBackend(
                host=host,
                port=port,
                **kwargs
            )
        else:
            self._alternative_backend = None

    def send_messages(self, email_messages):
        try:
            return super(EmailBackend, self).send_messages(email_messages)
        except Exception as e:
            if self._alternative_backend:
                return self._alternative_backend.send_messages(email_messages)
            else:
                raise e
Beispiel #12
0
def sending_mail(subject, message, contact_list):

    try:
        con = mail.get_connection()
        con.open()
        print('Django connected to the SMTP server')

        mail_setting = models.SmtpEmailSettings.objects.last()
        host = mail_setting.smtp_email_host
        host_user = mail_setting.smtp_email_host_user
        host_pass = mail_setting.smtp_email_host_password
        host_port = mail_setting.smtp_email_host_port
        host_sender_email = mail_setting.smtp_email_host_sender_address
        host_tls = mail_setting.smtp_use_tls
        host_ssl = mail_setting.smtp_use_ssl
        host_timeout = mail_setting.smtp_timeout

        mail_obj = EmailBackend(host=host,
                                port=host_port,
                                password=host_pass,
                                username=host_user,
                                use_tls=host_tls,
                                use_ssl=host_ssl,
                                timeout=host_timeout)

        msg = mail.EmailMessage(
            subject=subject,
            body=message,
            from_email=host_sender_email,
            to=[contact_list],
            connection=con,
        )

        msg.content_subtype = "html"
        mail_obj.send_messages([msg])
        print('Message has been sent.')

        mail_obj.close()
        print('SMTP server closed')
        return True

    except Exception as _error:
        print('Error in sending mail >> {}'.format(_error))
        return False
Beispiel #13
0
class InternalOnlyBackend(object):
    def __init__(self, *args, **kwargs):
        self.file_backend = FileBackend(*args, **kwargs)
        self.smtp_backend = SmtpBackend(*args, **kwargs)
        self.white_listed_addresses = getattr(settings,
                                              "EMAIL_NOTIFICATION_RECEIVERS",
                                              [])

    def get_whitelisted(self, addresses):
        clean = []
        for x in addresses:
            # addresses might be in form Name <email>
            start, end = x.find("<"), x.find(">")
            if start != -1 and end != -1:
                trimmed = x[start + 1:end]
                if trimmed in self.white_listed_addresses:
                    clean.append(x)
                else:
                    for white_listed in self.white_listed_addresses:
                        if trimmed.endswith(white_listed):
                            clean.append(x)
                            break
            elif x in self.white_listed_addresses:
                clean.append(x)
            else:
                for white_listed in self.white_listed_addresses:
                    if x.endswith(white_listed):
                        clean.append(x)
                        break
        return clean

    def send_messages(self, email_messages):
        try:
            self.file_backend.send_messages(email_messages)
        except:
            pass
        for message in email_messages:
            message.to = self.get_whitelisted(message.to)
            message.bcc = self.get_whitelisted(message.bcc)
            message.cc = self.get_whitelisted(message.cc)
        self.smtp_backend.send_messages(email_messages)
Beispiel #14
0
def send_single_html_mail(vector_email_id, fail_silently=False):
    try:
        vector_email = VectorEmail.objects.get(id=vector_email_id)
    except VectorEmail.DoesNotExist:
        # Prevents Celery log spam for the defunct task.
        ptask_identifier = 'send_vemail__v{}_'.format(vector_email_id)
        ptask = PeriodicTask.objects.get(name__contains=ptask_identifier)
        send_error_log_template = ('VE #{} not found while sending.'
                                   ' PeriodicTask #{}, {}, has been deleted.')
        logger.info(
            send_error_log_template.format(vector_email_id, ptask.id,
                                           ptask.name))
        ptask.delete()
        raise Ignore()

    engagement = vector_email.engagement
    target = Target.objects.get(vector_email=vector_email)

    if vector_email.send_at_passed is True:
        vector_email.set_state(VectorEmail.SEND_MISSED)
        engagement.check_for_completion()

        send_missed_log_template = 'VE #{} send_at MISSED: {}, Target TZ {}'
        logger.info(
            send_missed_log_template.format(vector_email.id,
                                            vector_email.send_at,
                                            target.get_timezone()))
        return

    sending_log_template = 'Sending VE #{} with send_at {}, Target TZ {}'
    logger.info(
        sending_log_template.format(vector_email.id, vector_email.send_at,
                                    target.get_timezone()))

    email_server = engagement.email_server
    connection = EmailBackend(host=email_server.host,
                              port=int(email_server.port),
                              username=email_server.login,
                              password=email_server.password,
                              use_tls=email_server.use_tls)

    datatuple = generateContent(target, engagement)
    subject, text, html, from_email, recipient, from_address = datatuple
    message = EmailMultiAlternatives(subject,
                                     text,
                                     from_email,
                                     recipient,
                                     headers={'Reply-To': from_address})
    message.attach_alternative(html, 'text/html')

    sent = 0
    try:
        sent = connection.send_messages((message, ))
        server_tz = dj_tz.get_default_timezone()
        server_now = server_tz.localize(datetime.datetime.now())
        vector_email.sent_timestamp = server_now
        vector_email.error = ''
        vector_email.save()
        vector_email.set_state(VectorEmail.SENT)
        engagement.check_for_completion()
    except Exception as e:
        vector_email.set_state(VectorEmail.ERROR)
        vector_email.error = interpret_email_error(e)
        vector_email.save()
        engagement.set_state(Engagement.ERROR)
        send_error_log_template = 'VE #{} task had an error: {}'
        logger.info(send_error_log_template.format(vector_email.id, e))
        raise Ignore()
    return sent
Beispiel #15
0
class BaseMassiveMailer():
    def __init__(self, message_to, context, subject, template, sndr_host,
                 sndr_username, sndr_pass, sndr_port, sndr_tls,
                 **substitutions):

        self.con = mail.get_connection()

        self.subject = subject
        self.message_to = message_to  #A list of emails

        self.template = template
        self.context = context

        self.sndr_host = sndr_host
        self.sndr_port = sndr_port
        self.sndr_username = sndr_username
        self.sndr_pass = sndr_pass
        self.sndr_tls = sndr_tls

        self.substitutions = {}

        for key in substitutions:
            self.substitutions.update({key: substitutions[key]})

    def create_emails(self):
        # creating connection
        self.con.open()

        #filling the connection (EmailBackend) object
        self.mail_obj = EmailBackend(host=self.sndr_host,
                                     port=self.sndr_port,
                                     username=self.sndr_username,
                                     password=self.sndr_pass,
                                     use_tls=self.sndr_tls)

        self.mails = []

        # filling the EmailMessage objects
        for email in self.message_to:
            for k, v in self.context.items():
                if k == email:
                    ctxt = {
                        'email': k,
                        'unsubscribe_url': v,
                        'index_url': self.substitutions["index_url"],
                        'post_title': self.substitutions["post_title"],
                        'post_url': self.substitutions["post_url"],
                        'post_preview': self.substitutions["post_preview"],
                        'post_bg_img': self.substitutions["post_bg_img"],
                        'privacy_url': self.substitutions["privacy_url"],
                    }
                    body_msg = render_to_string(self.template, ctxt)
                    new_mail_msg = mail.EmailMessage(
                        subject=self.subject,
                        body=body_msg,
                        from_email=self.sndr_username,
                        to=[email],
                        connection=self.con)

                    self.mails.append(new_mail_msg)

    def send_massive_email(self):
        self.create_emails()
        try:
            for mail in self.mails:
                mail.content_subtype = 'html'
            self.mail_obj.send_messages(self.mails)
            self.con.close()
            return True
        except Exception as e:
            print(f'\n\n# --- PY: Error sending massive emails: --- #\n{e}')
            return False