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 #2
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 #3
0
def test_smtp_connection(request):
    """ Tests smtp connection """
    mail_backend = EmailBackend(
        host=request.user.email_settings.smtp_host,
        port=request.user.email_settings.smtp_port,
        password=request.user.email_settings.smtp_password,
        username=request.user.email_settings.smtp_username,
        use_tls=True,
        timeout=10,
    )
    try:
        mail_backend.open()
        mail_backend.close()
        messages.success(
            request,
            _("SMTP settings are correct. Now you are using it for email sending"
              ),
        )
    except SMTPException:
        messages.warning(
            request,
            _("SMTP settings are not correct. Please provide correct credentials \
                and make sure that your smtp is running"),
        )
    return redirect("email_settings")
Beispiel #4
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 #5
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 #6
0
    def deliver(self, recipient, sender, notice_type, extra_context):
        # TODO: require this to be passed in extra_context

        context = self.default_context()
        context.update({
            "recipient": recipient,
            "sender": sender,
            "notice": ugettext(notice_type.display),
        })
        context.update(extra_context)

        from_email = settings.DEFAULT_FROM_EMAIL
        connection = None
        agent = None
        if 'context_agent' in context:
            agent = context['context_agent']
            if not agent:
                raise ValidationError("context agent is in context but agent is none?? "+str(context))

            if not agent.email:
                logger.info("The project sending this notice is missing an email address! agent:"+str(agent)+", using:"+str(from_email))
            else:
                from_email = agent.email

            obj = agent.project.custom_smtp()
            if obj and obj['host']:
                try:
                    connection = CoreEmailBackend(host=obj['host'], port=obj['port'], username=obj['username'], password=obj['password'], use_tls=obj['use_tls'])
                    #from_email = obj['username']
                except:
                    raise
            else:
                logger.warning("There's no custom email object (or no 'host') for project: "+str(agent.project))
        else:
            logger.warning("There's no context_agent related this notice? "+str(notice_type)+" context:"+str(context))

        messages = self.get_formatted_messages((
            "short.txt",
            "full.txt"
        ), notice_type.label, context)

        context.update({
            "message": messages["short.txt"],
        })
        subject = "".join(render_to_string("pinax/notifications/email_subject.txt", context).splitlines())

        context.update({
            "message": messages["full.txt"]
        })
        body = render_to_string("pinax/notifications/email_body.txt", context)

        #logger.debug('ocp sending email from '+str(from_email)+' to '+str(recipient.email)+' - time:'+str(time.time()))
        #print 'sending email from: '+from_email
        # EmailMultiAlternatives(subject='', body='', from_email=None, to=None, bcc=None, connection=None, attachments=None,
        #                        headers=None, alternatives=None, cc=None, reply_to=None)

        if connection:
            email = EmailMultiAlternatives(subject, body, from_email=from_email, to=[recipient.email], reply_to=[from_email], connection=connection)
        else:
            email = EmailMultiAlternatives(subject, body, from_email=from_email, to=[recipient.email], reply_to=[from_email])

        #import pdb; pdb.set_trace()
        result = email.send()

        logger.info('ocp sended email from '+str(from_email)+' to '+str(recipient.email)+' agent:'+str(agent)+' result:'+str(result))

        #send_mail(subject, body, from_email, [recipient.email], connection=connection)

        if connection:
            connection.close()