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 send(email_from: str, email_to: str, subject: str, body: str, attachment: str = None) -> None: """ Sends an email using the outgoing email settings. """ email_settings = EmailSettings.get_solo() logger.debug('Email: Preparing to send email using mail server %s:%s', email_settings.host, email_settings.port) email_backend = EmailBackend(host=email_settings.host, port=email_settings.port, username=email_settings.username, password=email_settings.password, use_tls=email_settings.use_tls, use_ssl=email_settings.use_ssl) # Prevent hanging processes, ensure there is always a timeout set. email_backend.timeout = email_backend.timeout if email_backend.timeout is not None else 30 message = mail.EmailMessage( subject=subject, body=body, from_email=email_from, to=[email_to], connection=email_backend, ) if attachment: message.attach_file(attachment) logger.debug('Email backup: Sending an email to %s (%s)', email_to, subject) message.send()
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)
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)
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
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))
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)
def newsletter_add(request): if request.method == "POST": form = NewsletterForm(request.POST) if form.is_valid() and len(Email.objects.values_list('smtp', flat=True)) > 0: data = form.cleaned_data code = ''.join( random.choices(string.ascii_letters + string.digits, k=40)) url = request.build_absolute_uri( '?')[:-len('newsletter-add')] + "newsletter-confirm/" + code email = data['email'] config = instance = Email.objects.get(pk=1) Newsletter.objects.filter(email=email).delete() newsletter = Newsletter(email=email, code=code) newsletter.add() send_mail(subject=activation_title, message=activation_text.replace("{@url}", url), from_email=config.email, recipient_list=[email], auth_user=config.email, auth_password=config.password, connection=EmailBackend(host=config.smtp, port=config.sslPort, username=config.email, password=config.password, use_tls=False, use_ssl=True)) return redirect('post_list') else: form = NewsletterForm() return render(request, 'blog/newsletter_add.html', {'form': form})
def soc_send_email(self, title, content, host, username, password, use_tls, use_ssl, send_address, to): """ :param title: 标题 :param content: 内容 :param host: 服务器 :param username: 用户名 :param password: 密码 :param use_tls: tls加密 :param use_ssl: ssl加密 :param send_address: 发件人 一般和用户名一致 :param to: 收件人 :return: 构造一个smtp 然后发送邮件 返回的status不为0则为成功 """ try: port = 25 if int(use_ssl): port = 465 smtp = EmailBackend(host=host, username=username, password=password, use_ssl=bool(int(use_ssl)), use_tls=bool(int(use_tls)), port=port) status = send_mail(title, content, send_address, [to], fail_silently=False, auth_user=username, auth_password=password, connection=smtp) logger.info("send email success to %s content=%s" % (to, content)) return status, 'ok' except Exception, e: logger.warning("send email error to %s content=%s, errors=%s" % (to, content, str(e))) return 0, '发送错误'
def send_custom_email_to_admins(request): user_data = User.objects.all() var = { 'u':udata, } to = ['*****@*****.**'] edata = email_configuration.objects.get(id=1) print("Before Backend") backend = EmailBackend(host=edata.email_host,port=edata.email_port,username=edata.email_username,password=edata.email_password, use_tls=edata.use_tls,use_ssl=edata.use_ssl,fail_silently=edata.fail_silently) print("After Backend") html_body = render_to_string('email/contact_us.html',{'var':var}) text_body = strip_tags(html_body) email = EmailMultiAlternatives( "Just for Testing - 2", text_body, 'bharatlvora814', to, connection=backend ) email.attach_alternative(html_body,"text/html") # email.attach_file('Document.pdf') email.send() return True
def send_mail_to(req, emails, attachments, subject, body): # Переписать attach как список имен файлов '''Отправка письма с кодировкой''' import base64 #sample_data = data['sample_data'].copy() manager_mail = req['manager_mail'] if manager_mail == '*****@*****.**': manager_mail = '*****@*****.**' try: user = MailPass.objects.get(email=manager_mail) except: logging.debug('Не удалось найти данные почтового адреса менеджера для отправки письма') return None manager_mail_pass = base64.b64decode(user.password.encode()).decode('utf-8') em = EmailMessage(subject=subject, body=body, to=emails, from_email=manager_mail ) em.content_subtype = 'html' for attach in attachments: em.attach_file(attach) EmailBackend( host = 'mail.stardustpaints.ru', username = manager_mail, password = manager_mail_pass, #use_ssl = True, use_tls = True, port = 587 ).send_messages([em])
def get_smtp_connection(campaign): """Get SMTP connection. :param campaign: `.models.Campaign` :return: SMTP connection """ if not campaign.smtp_host: return None options = {} for attr in dir(campaign): # get smtp infos if attr.startswith('smtp_'): index = attr.replace('smtp_', '') value = getattr(campaign, attr) # if port in host: extract port if index == 'host' and ':' in value: options['port'] = int(value.split(':')[-1]) value = value.split(':')[0] # add value if value: options[index] = value return EmailBackend(**options)
def enviarpedido(request): if "is_auth" not in request.session and "user_id" not in request.session: return render(request, 'index.html', None) else: customer = Customer.objects.get(pk=request.session['user_id']) response = {'status': 'success'} if request.is_ajax(): jsondata = json.loads(request.body) productos = jsondata['productos'] for prod in productos: producto = Products.objects.get(pk=prod['id']) prod['total'] = producto.price * prod['cantidad'] prod['name'] = producto.name prod['price'] = producto.price numeroOrden = util.generarOrder(customer) newPedido = Orders(number=numeroOrden, customer=customer, send=0, date=now) newPedido.save() nombreFichero = excel.generaExcelPedido(productos, customer, newPedido) ficheroExcel = 'media/pedidos/' + str( customer.pk) + '/' + numeroOrden + "/" + nombreFichero conexionSMTP = EmailBackend(host='smtp.bernini.es', port='587', username='******', password='******', use_tls='True') try: emails = {'from_email': '*****@*****.**'} contenidoEmail = { 'titulo': customer.name + ' ' + customer.lastname + ' - Resumen de pedido' } contenidoEmail['productos'] = productos util.enviarEmailAdjuntos(customer, 'envio-pedido.html', conexionSMTP, emails, ficheroExcel, contenidoEmail) newPedido.send = 1 newPedido.save() response = {'status': 'success'} except Exception as e: print(e) response = {'status': 'error'} return HttpResponse(json.dumps(response), content_type="application/json")
def send_mail(self, subject, body): if not self.email_is_configured: return False try: backend = EmailBackend( host=self.smtp_host, port=self.smtp_port, username=self.smtp_host_user, password=self.smtp_host_password, use_tls=self.smtp_use_tls, fail_silently=False, ) email = EmailMessage( subject=subject, body=body, from_email=self.smtp_host_user, to=self.email_alert_recipients, connection=backend, ) email.send() except Exception as e: logger.error(f"Sending email failed with error: {e}")
def admin_password_reset(email): user_data = User.objects.get(email=email) slug = (email.split('@')[0]) password = '******'.format(slug) # print("++++++++,",password,",+++++++") user_data.set_password(password) user_data.save() var = { 'password':password, 'username': user_data.username, } sub = "Password Reset Successfully" to = [email] edata = email_configuration.objects.get(id=1) backend = EmailBackend(host=edata.email_host,port=edata.email_port,username=edata.email_username,password=edata.email_password, use_tls=edata.use_tls,use_ssl=edata.use_ssl,fail_silently=edata.fail_silently) html_body = render_to_string('email/password_reset.html',{'var':var}) text_body = strip_tags(html_body) email = EmailMultiAlternatives( sub, text_body, '*****@*****.**', to, connection=backend ) email.attach_alternative(html_body,"text/html") # email.attach_file('Document.pdf') email.send() return True
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
def soc_send_email(title, content, host, username, password, use_tls, use_ssl, send_address, to): """ :param title: 标题 :param content: 内容 :param host: 服务器 :param username: 用户名 :param password: 密码 :param use_tls: tls加密 :param use_ssl: ssl加密 :param send_address: 发件人 一般和用户名一致 :param to: 收件人 :return: 构造一个smtp 然后发送邮件 返回的status不为0则为成功 """ try: smtp = EmailBackend(host=host, username=username, password=password, use_ssl=bool(int(use_ssl)), use_tls=bool(int(use_tls))) status = send_mail(title, content, send_address, [to], fail_silently=False, auth_user=username, auth_password=password, connection=smtp) return status, 'ok' except Exception, e: return 0, str(e)
def send_email_using_settings(subject, message, recipient_list): """Send an email using the SAEF email server settings.""" settings = Settings.objects.get() # Use the email information in the SAEF settings, if specified. if settings.email_host_user: email_backend = EmailBackend(host=settings.email_host, port=settings.email_port, use_tls=settings.email_use_tls, username=settings.email_host_user, password=settings.email_host_password) send_mail(subject=subject, message=message, from_email=settings.email_host_user, recipient_list=recipient_list, auth_user=settings.email_host_user, auth_password=settings.email_host_password, connection=email_backend) # If not specified in the SAEF settings, use the default email information from the django settings. else: send_mail(subject=subject, message=message, from_email=settings.email_host_user, recipient_list=recipient_list)
def send_email(title, content, notify_level, to_list, fail_silently=False, attachment=None, cc_recipient=None, template='email_template.html'): notification_rule = NotificationRule.objects.get_active_notification_rule() if notification_rule: backend = EmailBackend(host=notification_rule.email_host, port=notification_rule.email_port, username=notification_rule.email_host_user, password=notification_rule.email_host_password, use_tls=notification_rule.email_user_ssl, fail_silently=fail_silently) if template: html_content = loader.render_to_string(template, content) else: html_content = content subject = f'({notify_level}) {title}' send_html_email = SendHtmlEmail(subject, html_content, to_list, fail_silently, attachment, cc_recipient, backend) send_html_email.run() return True else: return False
def postcommentsmtp(request): if request.is_ajax(): data = request.body jsondata = json.loads(data) userlist = jsondata.get('userlist') toemails = [] usrlist = User.objects.filter(id__in=userlist) for usr in usrlist: toemails.append(usr.email) comments = jsondata.get('comments') orgid = jsondata.get('orgid') smtpdtl = SMTPDetails.objects.get(organizationid=orgid) print('toemails-->', toemails) print('comments-->', comments) print('smtpdtl-->', smtpdtl) if len(toemails) >= 1: backend = EmailBackend(host=smtpdtl.host, port=smtpdtl.port, username=smtpdtl.username, password=smtpdtl.passwrd, use_tls=True, fail_silently=False) # backend = EmailBackend(host='smtp.gmail.com', port=587, username='******', # password='******', use_tls=True , fail_silently=False) email = EmailMessage(subject='CDASH - Post Comments message !', body=comments, from_email=smtpdtl.username, to=toemails, connection=backend) email.send() return HttpResponse(json.dumps(json_response), content_type='application/json')
def enviar_email_mp(assunto, mensagem, csv): try: config = DynamicEmailConfiguration.get_solo() email_mp = EmailMercadoPago.objects.first() email_novo = None email_ja_enviado = LogEmailMercadoPago.objects.filter( enviar_para=email_mp.email, assunto=assunto, enviado=False, csv=csv) if not email_ja_enviado: email_novo = LogEmailMercadoPago.objects.create( enviar_para=email_mp.email, assunto=assunto, mensagem=mensagem, csv=csv) msg = EmailMessage(subject=assunto, body=mensagem, from_email=config.from_email or None, bcc=(email_mp.email, ), connection=EmailBackend(**config.__dict__)) msg.send() if email_ja_enviado.exists(): email_ja_enviado.update(enviado=True) elif email_novo: email_novo.enviado = True email_novo.save() except Exception as err: logger.error(str(err))
def get_smtp_connection(self): """Get SMTP connection. :return: SMTP connection """ if not self.smtp_host: return None options = { 'use_ssl': self.smtp_use_ssl } # add host / port infos if ':' in self.smtp_host: host, port = self.smtp_host.split(':') options['host'] = host options['port'] = int(port) else: options['host'] = self.smtp_host # add cred infos if self.smtp_username: options['username'] = self.smtp_username if self.smtp_password: options['password'] = self.smtp_password return EmailBackend(**options)
def newsletter_send(request): if request.method == "POST": form = SendNewsletterForm(request.POST) if form.is_valid() and request.user.is_authenticated and len( Email.objects.values_list('smtp', flat=True)) > 0: data = form.cleaned_data text = data['text'] title = data['title'] message = Message(text=text, title=title) message.save() config = instance = Email.objects.get(pk=1) recipients = Newsletter.objects.filter(confirmed=True) for recipient in recipients: url = request.build_absolute_uri('?')[:-len( 'newsletter-send')] + "newsletter-remove/" + recipient.code send_mail(subject=title, message="Aby odczytać wiadomość włącz obsługę html.", html_message=text + " " + unsubscribe_text.replace("{@url}", url), from_email=config.email, recipient_list=[recipient.email], auth_user=config.email, auth_password=config.password, connection=EmailBackend(host=config.smtp, port=config.sslPort, username=config.email, password=config.password, use_tls=False, use_ssl=True)) return redirect('post_list') else: form = SendNewsletterForm() return render(request, 'blog/newsletter_send.html', {'form': form})
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
def send_email( recipient, subject, body_text, user_email, user_password, host, port, use_tls, fail_silently=False, body_html=None, ): # Create custom backend backend = EmailBackend( host=host, port=port, username=user_email, password=user_password, use_tls=use_tls, fail_silently=fail_silently, ) # Create email object email = EmailMultiAlternatives( subject, # email subject body_text, # the body txt user_email, # send from [recipient], # the recipient connection=backend, # use the custom backend ) if body_html: # Attach html body email.attach_alternative(body_html, "text/html") # Send the email email.send()
def save_user(form, client): list_mail = dict() name = form.cleaned_data['name'] email = form.cleaned_data['email'] user = form.cleaned_data['user'].upper() groups = form.cleaned_data['groups'] user_ldap = form.cleaned_data['ldap_user'] if form.cleaned_data[ 'is_ldap'] else None list_mail['nome'] = name list_mail['user'] = user password = make_random_password() list_mail['pass'] = password new_user = client.create_usuario().inserir(user, password, name, email, user_ldap) for group in groups: client.create_usuario_grupo().inserir( new_user.get('usuario')['id'], group) if user_ldap is None: connection = EmailBackend(username=EMAIL_HOST_USER, password=EMAIL_HOST_PASSWORD) send_email = EmailMessage('Novo Usuário CadVlan-Globo.com', loader.render_to_string( MAIL_NEW_USER, list_mail), EMAIL_FROM, [email], connection=connection) send_email.content_subtype = "html" send_email.send()
def on_answer_to_answer_create(sender, instance, created, **kwargs): if not created or not instance.reply_to: return try: answer = ReviewAnswer.objects.get(pk=instance.reply_to.pk, get_notification=True) except ObjectDoesNotExist: return to_email = answer.email or answer.user.email conf = Site.objects.get(pk=instance.site.pk).config backend = EmailBackend(host=conf.email_host, port=conf.email_port, username=conf.email_username, password=conf.email_password, use_tls=conf.email_use_tls, fail_silently=True) message = 'Кто-то оставил коментарий на ваш отзыв. Что бы просмотреть этот коментарий ' \ 'перейдите, пожалуйста, по ссылке http://{0}/{1}'.format( instance.site.domain, instance.reply_to.review.product.get_absolute_url()) email = EmailMessage(subject='Оповещение об ответе на ваш отзыв', body=message, from_email=settings.DEFAULT_FROM_EMAIL, to=[to_email], connection=backend) email.send()
def connect(self): """Connect the SMTP Server""" from django.core.mail.backends.smtp import EmailBackend smtp = EmailBackend( host=smart_str(self.host), port=int(self.port), username=smart_str(self.user), password=smart_str(self.password), use_tls=self.tls, use_ssl=self.ssl, ) smtp.open() return smtp.connection
def send(email_from, email_to, subject, body, attachment=None): """ Sends an email using the outgoing email settings. """ email_settings = EmailSettings.get_solo() logger.debug('Email: Preparing to send email using mail server %s:%s', email_settings.host, email_settings.port) email_backend = EmailBackend(host=email_settings.host, port=email_settings.port, username=email_settings.username, password=email_settings.password, use_tls=email_settings.use_tls, use_ssl=email_settings.use_ssl) # Force translations. message = mail.EmailMessage( subject=subject, body=body, from_email=email_from, to=[email_to], connection=email_backend, ) if attachment: message.attach_file(attachment) logger.debug('Email backup: Sending an email to %s (%s)', email_to, subject) message.send()
def getEmailConfiguration(user): from accounts.models import DatabaseUser from django.core.mail.backends.smtp import EmailBackend import database.GPGPass as GPGPass _row = DatabaseUser.objects.get(username = user) if _row.email_host: if _row.email_host_pass[0:23] == "§ENCRYPTED_ONECORPSEC¤=": _gh = GPGPass.GPGPass() _password = _gh.decrypt(_row.email_host_pass[23:]) else: _password = _row.email_host_pass return EmailBackend( host = _row.email_host, port = _row.email_port, username = _row.email_host_user, password = _password, use_tls = _row.email_tls, ) # we return False instead of None # so that we flag that we have already checked and the user has no custom email host return False
def post(self, request, *args, **kwargs): form = self.get_form() if form.is_valid(): email = form.cleaned_data['email'] users = User.objects.filter(email = email) if users.exists(): for user in users: uid = urlsafe_base64_encode(force_bytes(user.pk)) token = default_token_generator.make_token(user) c = { 'request': request, 'title': _('Recover Password'), 'email': user.email, 'domain': request.build_absolute_uri(reverse("users:reset_password_confirm", kwargs = {'uidb64': uid, 'token':token})), #or your domain 'site_name': 'Amadeus', 'user': user, 'protocol': 'http', } subject_template_name = 'registration/password_reset_subject.txt' email_template_name = 'recover_pass_email_template.html' subject = loader.render_to_string(subject_template_name, c) # Email subject *must not* contain newlines subject = ''.join(subject.splitlines()) email = loader.render_to_string(email_template_name, c) mailsender = MailSender.objects.latest('id') if mailsender.hostname == "example.com": send_mail(subject, email, settings.DEFAULT_FROM_EMAIL , [user.email], fail_silently=False) else: if mailsender.crypto == 3 or mailsender.crypto == 4: tls = True else: tls = False backend = EmailBackend( host = mailsender.hostname, port = mailsender.port, username = mailsender.username, password = mailsender.password, use_tls = tls ) mail_msg = EmailMessage(subject = subject, body = email, to = [user.email], connection = backend) mail_msg.send() result = self.form_valid(form) messages.success(request, _("Soon you'll receive an email with instructions to set your new password. If you don't receive it in 24 hours, please check your spam box.")) return result messages.error(request, _('No user is associated with this email address')) result = self.form_invalid(form) return result
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 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")
def clean(self): cleaned_data = super().clean() smtp_email_backend = EmailBackend( host=cleaned_data.get('smtp_host'), port=cleaned_data.get('smtp_port'), username=cleaned_data.get('smtp_username'), password=cleaned_data.get('smtp_password'), use_tls=cleaned_data.get('smtp_use_tls'), fail_silently=False, use_ssl=cleaned_data.get('smtp_use_ssl'), timeout=cleaned_data.get('smtp_timeout'), ssl_keyfile=cleaned_data.get('smtp_ssl_keyfile'), ssl_certfile=cleaned_data.get('smtp_ssl_certfile') ) try: smtp_email_backend.open() except ConnectionRefusedError: raise ValidationError(_('Connection refused'), code='connection_refused') except SMTPAuthenticationError as err: raise ValidationError(str(err), code='auth_error') return cleaned_data
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 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()