Python django.conf.settings.EMAIL_HOST_USER Examples

The following are 21 code examples for showing how to use django.conf.settings.EMAIL_HOST_USER(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module django.conf.settings , or try the search function .

Example 1
Project: Servo   Author: fpsw   File: cron.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
def send_table(sender, recipient, subject, table, send_empty=False):
    if send_empty is False and table.has_body() is False:
        return

    try:
        validate_email(sender)
        validate_email(recipient)
    except Exception:
        return

    config = Configuration.conf()
    host, port = Configuration.get_smtp_server()

    settings.EMAIL_HOST = host
    settings.EMAIL_PORT = int(port)
    settings.EMAIL_USE_TLS = config.get('smtp_ssl')
    settings.EMAIL_HOST_USER = config.get('smtp_user')
    settings.EMAIL_HOST_PASSWORD = config.get('smtp_password')

    send_mail(subject, unicode(table), sender, [recipient], fail_silently=False) 
Example 2
Project: GTDWeb   Author: lanbing510   File: smtp.py    License: GNU General Public License v2.0 6 votes vote down vote up
def __init__(self, host=None, port=None, username=None, password=None,
                 use_tls=None, fail_silently=False, use_ssl=None, timeout=None,
                 ssl_keyfile=None, ssl_certfile=None,
                 **kwargs):
        super(EmailBackend, self).__init__(fail_silently=fail_silently)
        self.host = host or settings.EMAIL_HOST
        self.port = port or settings.EMAIL_PORT
        self.username = settings.EMAIL_HOST_USER if username is None else username
        self.password = settings.EMAIL_HOST_PASSWORD if password is None else password
        self.use_tls = settings.EMAIL_USE_TLS if use_tls is None else use_tls
        self.use_ssl = settings.EMAIL_USE_SSL if use_ssl is None else use_ssl
        self.timeout = settings.EMAIL_TIMEOUT if timeout is None else timeout
        self.ssl_keyfile = settings.EMAIL_SSL_KEYFILE if ssl_keyfile is None else ssl_keyfile
        self.ssl_certfile = settings.EMAIL_SSL_CERTFILE if ssl_certfile is None else ssl_certfile
        if self.use_ssl and self.use_tls:
            raise ValueError(
                "EMAIL_USE_TLS/EMAIL_USE_SSL are mutually exclusive, so only set "
                "one of those settings to True.")
        self.connection = None
        self._lock = threading.RLock() 
Example 3
Project: django-polaris   Author: stellar   File: integrations.py    License: Apache License 2.0 6 votes vote down vote up
def send_confirmation_email(user: PolarisUser, account: PolarisStellarAccount):
    """
    Sends a confirmation email to user.email

    In a real production deployment, you would never want to send emails
    as part of the request/response cycle. Instead, use a job queue service
    like Celery. This reference server is not intended to handle heavy
    traffic so we are making an exception here.
    """
    args = urlencode({"token": account.confirmation_token, "email": user.email})
    url = f"{settings.HOST_URL}{reverse('confirm_email')}?{args}"
    try:
        send_mail(
            _("Reference Anchor Server: Confirm Email"),
            # email body if the HTML is not rendered
            _("Confirm your email by pasting this URL in your browser: %s") % url,
            server_settings.EMAIL_HOST_USER,
            [user.email],
            html_message=render_to_string(
                "confirmation_email.html",
                {"first_name": user.first_name, "confirmation_url": url},
            ),
        )
    except SMTPException as e:
        logger.error(f"Unable to send email to {user.email}: {e}") 
Example 4
Project: eLearning   Author: avuletica   File: views.py    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
def contact(request):
    contact_form = Contact(request.POST or None)

    context = {
        "title": "Contact",
        "contact_form": contact_form,
    }

    if contact_form.is_valid():
        sender = contact_form.cleaned_data.get("sender")
        subject = contact_form.cleaned_data.get("subject")
        from_email = contact_form.cleaned_data.get("email")
        message = contact_form.cleaned_data.get("message")
        message = 'Sender:  ' + sender + '\nFrom:  ' + from_email + '\n\n' + message
        send_mail(subject, message, settings.EMAIL_HOST_USER, [settings.EMAIL_HOST_USER], fail_silently=True)
        success_message = "We appreciate you contacting us, one of our Customer Service colleagues will get back" \
                          " to you within a 24 hours."
        messages.success(request, success_message)

        return redirect(reverse('contact'))

    return render(request, "users/contact.html", context) 
Example 5
Project: luscan-devel   Author: blackye   File: smtp.py    License: GNU General Public License v2.0 6 votes vote down vote up
def __init__(self, host=None, port=None, username=None, password=None,
                 use_tls=None, fail_silently=False, **kwargs):
        super(EmailBackend, self).__init__(fail_silently=fail_silently)
        self.host = host or settings.EMAIL_HOST
        self.port = port or settings.EMAIL_PORT
        if username is None:
            self.username = settings.EMAIL_HOST_USER
        else:
            self.username = username
        if password is None:
            self.password = settings.EMAIL_HOST_PASSWORD
        else:
            self.password = password
        if use_tls is None:
            self.use_tls = settings.EMAIL_USE_TLS
        else:
            self.use_tls = use_tls
        self.connection = None
        self._lock = threading.RLock() 
Example 6
Project: diting   Author: getway   File: tasks.py    License: GNU General Public License v2.0 6 votes vote down vote up
def send_mail_async(*args, **kwargs):
    """ Using celery to send email async

    You can use it as django send_mail function

    Example:
    send_mail_sync.delay(subject, message, from_mail, recipient_list, fail_silently=False, html_message=None)

    Also you can ignore the from_mail, unlike django send_mail, from_email is not a require args:

    Example:
    send_mail_sync.delay(subject, message, recipient_list, fail_silently=False, html_message=None)
    """
    if len(args) == 3:
        args = list(args)
        args[0] = settings.EMAIL_SUBJECT_PREFIX + args[0]
        args.insert(2, settings.EMAIL_HOST_USER)
        args = tuple(args)

    try:
        send_mail(*args, **kwargs)
    except Exception as e:
        logger.error("Sending mail error: {}".format(e)) 
Example 7
Project: helfertool   Author: helfertool   File: forwarder.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def connect(self):
        """
        Connect to SMTP server.
        """
        if self._connection:
            raise MailHandlerError("SMTP connection already opened")

        try:
            if settings.EMAIL_USE_SSL:
                self._connection = smtplib.SMTP_SSL(settings.EMAIL_HOST, settings.EMAIL_PORT)
            else:
                self._connection = smtplib.SMTP(settings.EMAIL_HOST, settings.EMAIL_PORT)

            if settings.EMAIL_USE_TLS:
                self._connection.starttls()
        except smtplib.SMTPException:
            raise MailHandlerError("Invalid hostname, port or TLS settings for SMTP")

        try:
            if settings.EMAIL_HOST_USER and settings.EMAIL_HOST_PASSWORD:
                self._connection.login(settings.EMAIL_HOST_USER, settings.EMAIL_HOST_PASSWORD)
        except smtplib.SMTPException:
            raise MailHandlerError("Invalid username or password for SMTP") 
Example 8
Project: django_mail_admin   Author: Bearle   File: test_mailbox_base.py    License: MIT License 6 votes vote down vote up
def setUp(self):

        self._ALLOWED_MIMETYPES = get_allowed_mimetypes()
        self._STRIP_UNALLOWED_MIMETYPES = (
            strip_unallowed_mimetypes()
        )
        self._TEXT_STORED_MIMETYPES = get_text_stored_mimetypes()

        self.mailbox = Mailbox.objects.create(from_email='from@example.com')

        self.test_account = os.environ.get('EMAIL_ACCOUNT')
        self.test_password = os.environ.get('EMAIL_PASSWORD')
        self.test_smtp_server = os.environ.get('EMAIL_SMTP_SERVER')
        self.test_from_email = 'nobody@nowhere.com'

        self.maximum_wait_seconds = 60 * 5

        settings.EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
        settings.EMAIL_HOST = self.test_smtp_server
        settings.EMAIL_PORT = 587
        settings.EMAIL_HOST_USER = self.test_account
        settings.EMAIL_HOST_PASSWORD = self.test_password
        settings.EMAIL_USE_TLS = True
        super(EmailMessageTestCase, self).setUp() 
Example 9
Project: Servo   Author: fpsw   File: note.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def send_sms_smtp(self, config, recipient):
        """
        Sends SMS through SMTP gateway
        """
        recipient = recipient.replace(' ', '')
        settings.EMAIL_HOST = config.get('smtp_host')
        settings.EMAIL_USE_TLS = config.get('smtp_ssl')
        settings.EMAIL_HOST_USER = config.get('smtp_user')
        settings.EMAIL_HOST_PASSWORD = config.get('smtp_password')

        send_mail(recipient, self.body, self.sender, [config['sms_smtp_address']]) 
Example 10
Project: django-polaris   Author: stellar   File: integrations.py    License: Apache License 2.0 5 votes vote down vote up
def track_user_activity(form: forms.Form, transaction: Transaction):
        """
        Creates a PolarisUserTransaction object, and depending on the form
        passed, also creates a new PolarisStellarAccount and potentially a
        new PolarisUser. This function ensures an accurate record of a
        particular person's activity.
        """
        if isinstance(form, KYCForm):
            data = form.cleaned_data
            user = PolarisUser.objects.filter(email=data.get("email")).first()
            if not user:
                user = PolarisUser.objects.create(
                    first_name=data.get("first_name"),
                    last_name=data.get("last_name"),
                    email=data.get("email"),
                )

            account = PolarisStellarAccount.objects.create(
                account=transaction.stellar_account, user=user
            )
            if server_settings.EMAIL_HOST_USER:
                send_confirmation_email(user, account)
        else:
            try:
                account = PolarisStellarAccount.objects.get(
                    account=transaction.stellar_account
                )
            except PolarisStellarAccount.DoesNotExist:
                raise RuntimeError(
                    f"Unknown address: {transaction.stellar_account}, KYC required."
                )

        PolarisUserTransaction.objects.get_or_create(
            account=account, transaction=transaction
        ) 
Example 11
Project: django-polaris   Author: stellar   File: integrations.py    License: Apache License 2.0 5 votes vote down vote up
def check_kyc(transaction: Transaction, post_data=None) -> Optional[Dict]:
        """
        Returns a KYCForm if there is no record of this stellar account,
        otherwise returns None.
        """
        account = PolarisStellarAccount.objects.filter(
            account=transaction.stellar_account
        ).first()
        if not account:  # Unknown stellar account, get KYC info
            if post_data:
                form = KYCForm(post_data)
            else:
                form = KYCForm()
            return {
                "form": form,
                "icon_label": _("Stellar Development Foundation"),
                "title": _("Polaris KYC Information"),
                "guidance": (
                    _(
                        "We're legally required to know our customers. "
                        "Please enter the information requested."
                    )
                ),
            }
        elif server_settings.EMAIL_HOST_USER and not account.confirmed:
            return {
                "title": CONFIRM_EMAIL_PAGE_TITLE,
                "guidance": _(
                    "We sent you a confirmation email. Once confirmed, "
                    "continue on this page."
                ),
                "icon_label": _("Stellar Development Foundation"),
            }
        else:
            return None 
Example 12
Project: zulip   Author: zulip   File: email_backends.py    License: Apache License 2.0 5 votes vote down vote up
def send_email_smtp(self, email: EmailMultiAlternatives) -> None:
        from_email = email.from_email
        to = get_forward_address()

        msg = EmailMessage()
        msg['Subject'] = email.subject
        msg['From'] = from_email
        msg['To'] = to

        text = email.body
        html = email.alternatives[0][0]

        # Here, we replace the email addresses used in development
        # with chat.zulip.org, so that web email providers like Gmail
        # will be able to fetch the illustrations used in the emails.
        localhost_email_images_base_uri = settings.ROOT_DOMAIN_URI + '/static/images/emails'
        czo_email_images_base_uri = 'https://chat.zulip.org/static/images/emails'
        html = html.replace(localhost_email_images_base_uri, czo_email_images_base_uri)

        msg.add_alternative(text, subtype="plain")
        msg.add_alternative(html, subtype="html")

        smtp = smtplib.SMTP(settings.EMAIL_HOST)
        smtp.starttls()
        smtp.login(settings.EMAIL_HOST_USER, settings.EMAIL_HOST_PASSWORD)
        smtp.send_message(msg)
        smtp.quit() 
Example 13
Project: academicstoday-django   Author: AcademicsToday   File: forgot_password.py    License: Apache License 2.0 5 votes vote down vote up
def send_email(email, new_password):
    if settings.EMAIL_HOST_USER is '' or settings.EMAIL_HOST_PASSWORD is '':
        return {'status' : 'failed', 'message' : 'cannot change password, emailer is offline, please check back later' }
    
    text = "Your new password is: " + new_password
            
    send_mail(
        "New Password",
        text,
        settings.EMAIL_HOST_USER,
        [email],
        fail_silently=False
    )
    return {'status' : 'success', 'message' : 'successfully registered' } 
Example 14
Project: academicstoday-django   Author: AcademicsToday   File: checkinbox.py    License: Apache License 2.0 5 votes vote down vote up
def handle(self, *args, **options):
        """
            Function iterates through all the messages left for us on the 
            landpage and emails these messages to the contact lists.
        """
        contact_list = ["bartlomiej.mika@gmail.com", "sibrislarenz@gmail.com", "m_poet5@hotmail.com"]
        
        try:
           messages = LandpageContactMessage.objects.all()
        except LandpageContactMessage.DoesNotExist:
           return

        # Send our messages and then delete them from the database.
        for message in messages:
            """
               Please note, since we are using gmail, we need "Access for
               less secure apps" to be "Turned On".
            """
            text = "FROM: " + message.email + "\n"
            text += "NAME: " + message.name + "\n"
            text += "PHONE: " + message.phone + "\n"
            text += "MESSAGE: " + message.message + "\n"
            
            send_mail(
                "Landpage Message",
                text,
                settings.EMAIL_HOST_USER,
                contact_list,
                fail_silently=False)

            message.delete() # Delete our message 
Example 15
Project: Django-Blog-Python-Learning   Author: agusmakmun   File: views.py    License: GNU General Public License v2.0 5 votes vote down vote up
def post(self, request, *args, **kwargs):
        context = self.get_context_data()
        if context['form'].is_valid():
            cd = context['form'].cleaned_data
            subject = cd['subject']
            from_email = cd['email']
            message = cd['message']

            try:
                send_mail(
                    subject + " from {}".format(from_email),
                    message,
                    from_email,
                    [settings.EMAIL_HOST_USER]
                )
            except BadHeaderError:
                return HttpResponse('Invalid header found.')

            ctx = {
                'success': """Thankyou, We appreciate that you've
                taken the time to write us.
                We'll get back to you very soon.
                Please come back and see us often."""
            }
            return render(request, self.template_name, ctx)
        return super(generic.TemplateView, self).render_to_response(context) 
Example 16
Project: abidria-api   Author: jordifierro   File: services.py    License: MIT License 5 votes vote down vote up
def send_ask_confirmation_mail(self, confirmation_token, email, username):
        confirmation_url = "{}?token={}".format(self.request.build_absolute_uri(reverse('email-confirmation')),
                                                confirmation_token)

        context_params = {'username': username, 'confirmation_url': confirmation_url}
        plain_text_message = get_template('ask_confirmation_email.txt').render(context_params)
        html_message = get_template('ask_confirmation_email.html').render(context_params)

        subject, origin_email, target_email = 'Abidria account confirmation', settings.EMAIL_HOST_USER, email

        mail.send_mail(subject,
                       plain_text_message,
                       origin_email, [target_email, ],
                       html_message=html_message,
                       fail_silently=False) 
Example 17
Project: abidria-api   Author: jordifierro   File: test_services.py    License: MIT License 5 votes vote down vote up
def then_django_send_mail_should_be_called_with_correct_processed_params(self):
            assert mail.outbox[0].subject == 'Abidria account confirmation'
            confirmation_url = "{}?token={}".format(self.url, self.confirmation_token)
            context_params = {'username': self.username, 'confirmation_url': confirmation_url}
            plain_text_message = get_template('ask_confirmation_email.txt').render(context_params)
            html_message = get_template('ask_confirmation_email.html').render(context_params)
            assert mail.outbox[0].body == plain_text_message
            assert mail.outbox[0].from_email == settings.EMAIL_HOST_USER
            assert mail.outbox[0].to == [self.email, ]
            assert mail.outbox[0].alternatives[0][0] == html_message
            return self 
Example 18
Project: abidria-api   Author: jordifierro   File: test_integration.py    License: MIT License 5 votes vote down vote up
def then_ask_confirmation_email_should_be_sent(self):
            assert mail.outbox[0].subject == 'Abidria account confirmation'
            confirmation_token = ORMConfirmationToken.objects.get(person_id=self.orm_person.id).token
            confirmation_reverse_url = self.response.wsgi_request.build_absolute_uri(reverse('email-confirmation'))
            confirmation_url = "{}?token={}".format(confirmation_reverse_url, confirmation_token)
            context_params = {'username': self.username, 'confirmation_url': confirmation_url}
            plain_text_message = get_template('ask_confirmation_email.txt').render(context_params)
            html_message = get_template('ask_confirmation_email.html').render(context_params)
            assert mail.outbox[0].body == plain_text_message
            assert mail.outbox[0].from_email == settings.EMAIL_HOST_USER
            assert mail.outbox[0].to == [self.email, ]
            assert mail.outbox[0].alternatives[0][0] == html_message
            return self 
Example 19
Project: ecommerce-2-api   Author: codingforentrepreneurs   File: views.py    License: MIT License 5 votes vote down vote up
def contact(request):
	title = 'Contact Us'
	title_align_center = True
	form = ContactForm(request.POST or None)
	if form.is_valid():
		# for key, value in form.cleaned_data.iteritems():
		# 	print key, value
		# 	#print form.cleaned_data.get(key)
		form_email = form.cleaned_data.get("email")
		form_message = form.cleaned_data.get("message")
		form_full_name = form.cleaned_data.get("full_name")
		# print email, message, full_name
		subject = 'Site contact form'
		from_email = settings.EMAIL_HOST_USER
		to_email = [from_email, 'youotheremail@email.com']
		contact_message = "%s: %s via %s"%( 
				form_full_name, 
				form_message, 
				form_email)
		some_html_message = """
		<h1>hello</h1>
		"""
		send_mail(subject, 
				contact_message, 
				from_email, 
				to_email, 
				html_message=some_html_message,
				fail_silently=True)

	context = {
		"form": form,
		"title": title,
		"title_align_center": title_align_center,
	}
	return render(request, "forms.html", context) 
Example 20
Project: scantron   Author: rackerlabs   File: utility.py    License: Apache License 2.0 4 votes vote down vote up
def process_scan_status_change(scheduled_scan_dict):
    """When a scan finishes, execute other tasks based off settings."""

    logger.info(f"scheduled_scan_dict: {scheduled_scan_dict}")

    # Extract values from passed ScheduleScan object.
    scheduled_scan_id = scheduled_scan_dict["id"]
    scan_status = scheduled_scan_dict["scan_status"]
    scan_binary = scheduled_scan_dict["scan_binary"]

    # Retrieve site information.
    site_name = scheduled_scan_dict["site_name"]
    site = django_connector.Site.objects.filter(site_name=site_name)[0]

    # Determine if site has email_scan_alerts enabled.
    email_scan_alerts = site.email_scan_alerts

    # 1) Does an email alert need to be sent?
    if email_scan_alerts:

        master_fqdn = settings.MASTER_FQDN
        from_address = settings.EMAIL_HOST_USER
        to_addresses = site.email_alert_addresses.split(",")
        subject = f"Scantron scan {scan_status.upper()}: {site.site_name}"

        if scan_status == "completed":

            # Provide different links based off the scan binary used.
            if scan_binary == "nmap":
                body = f"""XML: https://{master_fqdn}/results/{scheduled_scan_id}?file_type=xml
NMAP: https://{master_fqdn}/results/{scheduled_scan_id}?file_type=nmap
"""
            else:
                body = f"""Results: https://{master_fqdn}/results/{scheduled_scan_id}?file_type=json"""

        elif scan_status in ["started", "paused", "cancelled", "error"]:
            body = f""""""

        # Ignore "pending" status.  Shouldn't ever reach this branch.
        else:
            pass

        # email_sent_successfully = custom_send_email(to_addresses, subject=subject, body=body)
        email_sent_successfully = send_mail(subject, body, from_address, to_addresses, fail_silently=False,)

        if not email_sent_successfully:
            logger.error(f"Issue sending the email for Scheduled Scan ID: {scheduled_scan_id}")

        logger.info(f"Successfully sent email for Scheduled Scan ID: {scheduled_scan_id}")

    # 2 Do other stuff
    # TODO 
Example 21
Project: DeerU   Author: gojuukaze   File: email.py    License: GNU General Public License v3.0 4 votes vote down vote up
def _send(subject, message, recipient_list,
          email_config=None, html_message=None, fail_silently=False):
    if not email_config:
        blog_config = get_config_by_name(v2_app_config_context['v2_blog_config']).v2_real_config
        email_config = blog_config['email']

    username = email_config.get('username', None) or settings.EMAIL_HOST_USER
    password = email_config.get('password', None)
    if password:
        password = descrypt(unsign(password))
    else:
        password = settings.EMAIL_HOST_PASSWORD
    smtp = email_config.get('smtp', None) or settings.EMAIL_HOST
    port = email_config.get('port', None) or settings.EMAIL_PORT
    secure = email_config.get('secure', None)
    if not secure:
        if settings.EMAIL_USE_TLS:
            secure = 'tls'
        elif settings.EMAIL_USE_SSL:
            secure = 'ssl'
    if not username or not password or not smtp or not port:
        return

    kwargs = {
        'host': smtp,
        'port': port,
        'username': username,
        'password': password,
        'fail_silently': fail_silently

    }
    if secure == 'tls':
        kwargs['use_tls'] = True
    elif secure == 'ssl':
        kwargs['use_ssl'] = True

    connection = EmailBackend(**kwargs)
    mail = EmailMultiAlternatives(subject, message, username, recipient_list, connection=connection)
    if html_message:
        mail.attach_alternative(html_message, 'text/html')

    a= mail.send()
    print(a)