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 audit_event_catch(instance=None, created=False, **kwargs): if instance.audited: return bad_phrases = phrases_query() name_search_result = re.findall(bad_phrases, instance.name, re.I) description_search_result = re.findall(bad_phrases, instance.description, re.I) if name_search_result or description_search_result: audit_event = AuditEvent( event_ptr_id=instance.pk ) audit_event.__dict__.update(instance.__dict__) audit_event.save() phrases = AuditPhrase.objects.filter( phrase__in=(name_search_result + description_search_result) ) for phrase in phrases: audit_event.phrases.add(phrase) current_site = Site.objects.get_current().domain subject = 'Bad phrases have been caught!' message = render_to_string('audit/bad_phrases_email.txt', { 'site': current_site, 'event': audit_event, 'phrases': phrases }) msg = EmailMessage(subject, message, DEFAULT_FROM_EMAIL, map(lambda x: x[1], settings.ADMINS)) msg.content_subtype = 'html'
def _log_to_email(email_to, email_from, output, req_string): em = EmailMessage('Slow Request Watchdog: %s' % req_string.encode('utf-8'), output, email_from, (email_to,)) em.send(fail_silently=True)
def test_substitution_data(): email_message = EmailMessage( to=[ { "address": "*****@*****.**", "substitution_data": { "key": "value" } } ], from_email='*****@*****.**' ) email_message.template = 'template-id' email_message.substitution_data = {"key2": "value2"} actual = SparkPostMessage(email_message) expected = dict( recipients=[ { "address": "*****@*****.**", "substitution_data": { "key": "value" } } ], from_email='*****@*****.**', template='template-id', substitution_data={"key2": "value2"} ) assert actual == expected
def contact(request): if request.method == 'POST': form = ContactForm(request.POST, initial={ 'captcha': request.META['REMOTE_ADDR']}) if form.is_valid(): if form.cleaned_data['sender']: headers = { 'Reply-To': form.cleaned_data['sender']} else: headers = {} email = EmailMessage( subject=form.cleaned_data['subject'], body="%s\n\nfrom: %s" % (form.cleaned_data['message'], form.cleaned_data['sender']), from_email='*****@*****.**', to=('*****@*****.**', '*****@*****.**'), headers=headers, ) email.send() # Redirect after POST return HttpResponseRedirect(reverse('contact_sent')) else: form = ContactForm() # An unbound form # request context required for CSRF return render_to_response('dnd/contacts/contact.html', { 'request': request, 'form': form, }, context_instance=RequestContext(request), )
def send_csv(self, emails=[]): filename, csv_file = self.create_csv() message = EmailMessage(subject='{} LEVEL ASSORTMENT REPORT'.format(self.level.upper()), from_email=EMAIL_HOST_USER, to=emails) message.attach(filename, csv_file.getvalue(), 'text/csv') print message.send()
def payment_notification(sender, **kwargs): ipn_obj = sender if ipn_obj.payment_status == ST_PP_COMPLETED: # payment was successful order = get_object_or_404(Order, id=ipn_obj.invoice) # mark the order as paid order.paid = True order.save() # create invoice e-mail subject = 'My Shop - Invoice no. {}'.format(order.id) message = 'Please, find attached the invoice for your recent purchase.' email = EmailMessage(subject, message, '*****@*****.**', [order.email]) # generate PDF html = render_to_string('orders/order/pdf.html', {'order': order}) out = BytesIO() css_path = os.path.join(settings.STATICFILES_DIRS[0], 'css/pdf.css') weasyprint.HTML(string=html).write_pdf(out, stylesheets=[weasyprint.CSS(css_path)]) # attach PDF file email.attach('order_{}.pdf'.format(order.id), out.getvalue(), 'application/pdf') # send e-mail email.send()
def emit(self, record): import traceback if not settings.ADMINS: return try: # Hack to try to get request from context request = record.exc_info[2].tb_frame.f_locals['context']['request'] request_repr = repr(request) request_path = request.path except Exception: request_repr = "Request unavailable" request_path = 'Unknown URL' if record.exc_info: stack_trace = '\n'.join(traceback.format_exception(*record.exc_info)) else: stack_trace = 'No stack trace available' message = "%s\n\n%s" % (stack_trace, request_repr) msg = EmailMessage( '[sorl-thumbnail] %s: %s' % (record.levelname, request_path), message, settings.SERVER_EMAIL, [a[1] for a in settings.ADMINS], connection=None ) msg.send(fail_silently=True)
def bug_report(self, couch_user, error_id): error = PillowError.objects.get(id=error_id) context = { 'error': error, 'url': "{}{}?error={}".format(get_url_base(), reverse(EditPillowError.urlname), error_id) } message = render_to_string('hqpillow_retry/fb.txt', context) subject = 'PillowTop error: {} - {}'.format(error.pillow, error.error_type) reply_to = u'"{}" <{}>'.format(couch_user.full_name, couch_user.get_email()) email = EmailMessage( subject=subject, body=message, to=settings.BUG_REPORT_RECIPIENTS, headers={'Reply-To': reply_to} ) # only fake the from email if it's an @dimagi.com account if re.search('@dimagi\.com$', couch_user.username): email.from_email = couch_user.username else: email.from_email = settings.CCHQ_BUG_REPORT_EMAIL email.send(fail_silently=False)
def activate(request, token): aux1=YoungInvestigator.objects.filter(token=token) aux2=PrincipalInvestigator.objects.filter(token=token) aux=[] if len(aux1)==1: aux=aux1 if len(aux2)==1: aux=aux2 if len(aux)==1: reg1=aux[0] user1=User.objects.filter(id=reg1.user.id)[0] user1.is_active=1 user1.save() reg1.activation_key="ALREADY_ACTIVATED" reg1.save() ##correo para informar de la activacion contenido="Thanks for trust in ScienceWeb.\n You can access with your account.\n\nUsername: "******"\n http://www.peerland.org/" correo = EmailMessage("ScienceWeb: Your Account is already activated", contenido, to=[user1.email]) correo.send() return render_to_response('users/activation_complete.html',context_instance = RequestContext(request)) else: return render_to_response('users/activate.html')
def wyslij_biuletyn(request): if request.is_ajax(): subscribers = Newsletter.objects.all() response_message = "success" from_email = '*****@*****.**' connection = mail.get_connection() connection.open() subject = 'Hotel Messiah Newsletter!' for subscriber in subscribers: try: message_html = request.GET['message']+"<a href='"+request.build_absolute_uri(reverse('hotel:newsletter_anuluj', args=[subscriber.news_kod]))+"'>"+"Anuluj newsletter"+"</a>" to_email = subscriber.news_email #to_email_bcc = Newsletter.objects.values_list('news_email', flat=True) if subject and message_html and from_email: try: msg = EmailMessage(subject, message_html, from_email, [to_email]) msg.content_subtype = "html" msg.send() except KeyError: response_message = "site_error" else: response_message = "empty_field" except KeyError: raise Http404 connection.close() return HttpResponse(response_message) else: raise Http404
def notify(self): base_url = "http://%s" % Site.objects.get_current().domain text = render_to_string("harvester/notification.html", dict(base_url=base_url, job=self)) message = EmailMessage(u"Harvesting job is complete", text, settings.DEFAULT_FROM_EMAIL, [self.email]) message.content_subtype = "html" message.send()
def remind_account_about_deleted_events_with_email(account, single_events): if account.reminder_email: featured_events = Event.featured_events_for_region(account.native_region)[:4] subject = 'Deleted events from cityfusion' message = render_to_string('accounts/emails/reminder_deleted_event_email.html', { "featured_events": featured_events, "events": single_events, "STATIC_URL": "/static/", "advertising_region": account.advertising_region, "site": "http://%s" % Site.objects.get_current().domain }) try: msg = EmailMessage(subject, message, "*****@*****.**", [account.reminder_email]) msg.content_subtype = 'html' msg.send() except: logger.error("Invalid email %s" % account.reminder_email) return message else: return ""
def remind_account_about_events_with_email(account, single_events): if account.reminder_email: featured_events = Event.featured_events_for_region(account.native_region)[0:4] similar_events = find_similar_events( Event.future_events.filter(id__in=single_events.values_list("event_id", flat=True)) ) subject = "Upcoming events from cityfusion" message = render_to_string('accounts/emails/reminder_email.html', { "featured_events": featured_events, "events": single_events, "similar_events": similar_events, "STATIC_URL": "/static/", "advertising_region": account.advertising_region, "site": "http://%s" % Site.objects.get_current().domain }) try: msg = EmailMessage(subject, message, "*****@*****.**", [account.reminder_email]) msg.content_subtype = 'html' msg.send() except: logger.error("Invalid email %s" % account.reminder_email) return message else: return ""
def wyslij_email(request, pk): if request.is_ajax(): response_message = "success" wiadomosc = Wiadomosc.objects.get(id=pk) subject = 'Hotel Messiah' try: message = request.GET['message'] message_html = '<h3>' + _('Twoje pytanie') + ': </h3><p>' + wiadomosc.tresc + \ '</p><h3>' + _('Nasza odpowiedz') + ': </h3><p>' + request.GET['message'] + "</p>" from_email = '*****@*****.**' to_email = request.GET['email_address'] if subject and message and from_email: try: # send_mail(subject, message, from_email, [to_email]) msg = EmailMessage(subject, message_html, from_email, [to_email]) msg.content_subtype = "html" msg.send() except KeyError: response_message = "site_error" else: response_message = "empty_field" if response_message == "success": wiadomosc.wyslano_odpowiedz = True wiadomosc.odpowiedz = message wiadomosc.save() except KeyError: raise Http404 return HttpResponse(response_message) else: raise Http404
def send_activation_mail(user): key = SecretKey.objects.get_or_create(user=user).secretkey context = {'username': user.username, 'security_key': key} html_content = render_to_string('massage.html', context) msg = EmailMessage('submit registration', html_content, '*****@*****.**', [user.email]) msg.content_subtype = "html" msg.send()
def inform_account_about_events_with_tag_with_email(account, events, tags_in_venues): featured_events = Event.featured_events_for_region(account.native_region)[:4] similar_events = find_similar_events(events) subject = "New Events in cityfusion" message = render_to_string( "accounts/emails/in_the_loop_email.html", { "featured_events": featured_events, "events": events, "similar_events": similar_events, "STATIC_URL": "/static/", "site": "http://%s" % Site.objects.get_current().domain, "tags_in_venues": tags_in_venues, "advertising_region": account.advertising_region, }, ) msg = EmailMessage(subject, message, "*****@*****.**", [account.in_the_loop_email]) msg.content_subtype = "html" msg.send() return message
def send_pdf_to_user(self, user): report = self.report.get_path_to_pdf(user, self.view_args) title = self.report.email_subject(user, self.view_args) email = EmailMessage(title, 'See attachment', settings.EMAIL_LOGIN, [user.email]) email.attach_file(report) email.send(fail_silently=False)
def send_mail(subject, message, from_email, recipient_list, priority="medium", fail_silently=False, auth_user=None, auth_password=None, attach_files=[]): from django.utils.encoding import force_unicode from mailer.models import make_message from django.core.mail.message import EmailMessage priority = PRIORITY_MAPPING[priority] # need to do this in case subject used lazy version of ugettext subject = force_unicode(subject) message = force_unicode(message) msg = make_message(subject=subject, body=message, from_email=from_email, to=recipient_list, priority=priority) email = msg.email email = EmailMessage(email.subject, email.body, email.from_email, email.to) for f in attach_files: if isinstance(f, str): email.attach_file(f) elif isinstance(f, (tuple, list)): n, fi, mime = f + (None,) * (3 - len(f)) email.attach(n, fi, mime) msg.email = email msg.save() return 1
def remind_account_about_events_with_email(account, single_events): featured_events = Event.featured_events_for_region(account.native_region) similar_events = find_similar_events( Event.future_events.filter(id__in=single_events.values_list("event_id", flat=True)) ) subject = "Upcoming events from cityfusion" message = render_to_string( "accounts/emails/reminder_email.html", { "featured_events": featured_events, "events": single_events, "similar_events": similar_events, "STATIC_URL": "/static/", "advertising_region": account.advertising_region, "site": "http://%s" % Site.objects.get_current().domain, }, ) msg = EmailMessage(subject, message, "*****@*****.**", [account.reminder_email]) msg.content_subtype = "html" msg.send() return message
def send_template_mail(template_name, to, from_email=None, extra_context=None, request=None, subject_template=None, html=False, **kwargs): default_context = { 'site': Site.objects.get_current(), } if request: context = RequestContext(request, default_context) else: context = Context(default_context) if extra_context: context.update(extra_context) if not subject_template: subject_template = '%s_subject%s' % os.path.splitext(template_name) subject = get_template(subject_template) body = get_template(template_name) subject = (''.join(subject.render(context).splitlines())).strip() body = body.render(context) from_email = from_email or settings.DEFAULT_FROM_EMAIL connection = get_connection() message = EmailMessage(subject, body, from_email, to, connection=connection) if html: message.content_subtype = 'html' return message.send()
def send(self, to_address, subject, body, route=None): connection = None if route: route_host = settings.SMTP_ROUTES[route]["HOST"] route_port = settings.SMTP_ROUTES[route]["PORT"] route_user = settings.SMTP_ROUTES[route].get("USERNAME", '') route_password = settings.SMTP_ROUTES[route].get("PASSWORD", '') route_use_tls = settings.SMTP_ROUTES[route].get("USE_TLS", True) connection = get_connection(host=route_host, port=route_port, username=route_user, password=route_password, use_tls=route_use_tls) self.attachment_content = render_to_string(self.attachment_template, self.attachment_data) if connection: self.email = EmailMessage(subject, body, self.from_address, to_address, connection=connection) else: self.email = EmailMessage(subject, body, self.from_address, to_address) self.email.attach(self.attachment_name, self.attachment_content, self.attachment_mime) self.email.send(fail_silently=False)
def send_confirmation(self): url = reverse("users:reset_password", kwargs=dict(key=self.key)) url = "http://%s%s" % (Site.objects.get_current().domain, url) body = render_to_string("users/emails/reset-password-confirmation.html", dict(url=url, user=self.user)) message = EmailMessage(u"Reset your OER Commons password", body, to=[self.user.email]) message.content_subtype = "html" message.send()
def send_mail(subject, template_name, to, **kwargs): kwargs['settings'] = settings body = render_to_string(template_name, kwargs) if to: msg = EmailMessage(subject, body, None, to=to) msg.content_subtype = "html" msg.send()
def send_single_email(subject, message,to_email, from_email=DEFAULT_FROM_EMAIL,info_dict={},token=None, job=None, resume_id=None): to=list() to.append(to_email) details = MarketEmailSendDetail() details.send_time = datetime.now() details.from_email = from_email details.subject = subject details.to_email = to_email details.status = True details.info_dict = info_dict details.save() token = str(details.id) try: if token: message = message.replace("pinbot_token",token) msg = EmailMessage(subject=subject, body=message, from_email=from_email, to=to) msg.content_subtype = "html" # Main content is now text/html ret = msg.send() # 添加C端企业感兴趣 brick_company_card = JobUtils.send_company_card(job.user, job, resume_id, token) if brick_company_card: details.info_dict['card_job_id'] = brick_company_card.id details.save() return True,str(details.id) except Exception , IntegrityError: details.status = False details.error_info = str(IntegrityError) details.save() return False, str(IntegrityError)
def send_simple_order_notification(sender, order, request, **kwargs): """ :param order: Order :type order: shuup.core.models.Order """ if order.log_entries.filter(identifier=NOTIFICATION_SUCCESS_LOG_IDENTIFIER).exists(): return try: engine = engines["jinja2"] except InvalidTemplateEngineError: return # Dont send notifications because we cannot parse files :( with translation.override(order.language): # Local import to make sure the environment is initialized env = {"order": order} subject = engine.from_string(MESSAGE_SUBJECT_TEMPLATE).render(env) body = engine.from_string(MESSAGE_BODY_TEMPLATE).render(env) message = EmailMessage(subject, body, to=[order.email]) try: message.send() except Exception as exc: LOG.exception("Failed to send order notification to %s" % message.to) order.add_log_entry( "Order Notification Email failed: %s" % exc, identifier=NOTIFICATION_ERROR_LOG_IDENTIFIER, kind=LogEntryKind.ERROR) else: LOG.info("Order notification sent to %s" % message.to) order.add_log_entry( "Order Notification Email sent", identifier=NOTIFICATION_SUCCESS_LOG_IDENTIFIER, kind=LogEntryKind.ERROR)
def send_email_feedback(self, feedback_pk, sender, recipents): try: feedback = Feedback.objects.get(pk=feedback_pk) except Feedback.DoesNotExist as exc: logger.error('Failed processing_crash_dump', exc_info=True, extra=dict(crash_pk=feedback_pk)) raise self.retry(exc=exc, countdown=2 ** send_email_feedback.request.retries) recipients = [x.strip() for x in recipents.split(',')] body = email_body_tmpl % ( feedback.description, feedback.page_url, feedback.email, feedback.ip, feedback.feedback_data, ) email = EmailMessage("Feedback # %s" % feedback_pk, body, sender, recipients) attachments = [ feedback.screenshot, feedback.blackbox, feedback.system_logs, feedback.attached_file ] for attach in attachments: if attach: email.attach(os.path.basename(attach.name), attach.read()) email.send()
def newsite(req): import base.models as M, random, string form = None auth_user = UR.getUserInfo(req) ensemble_form = None user_form = None if auth_user is not None: return HttpResponseRedirect("/admin") if req.method == 'POST': user = M.User(confkey="".join([choice(string.ascii_letters+string.digits) for i in xrange(0,32)])) ensemble = M.Ensemble() user_form = forms.UserForm(req.POST, instance=user) ensemble_form = forms.EnsembleForm(req.POST, instance=ensemble) if user_form.is_valid() and ensemble_form.is_valid(): user_form.save() ensemble.invitekey = "".join([ random.choice(string.ascii_letters+string.digits) for i in xrange(0,50)]) ensemble_form.save() m = M.Membership(user=user, ensemble=ensemble, admin=True) m.save() p = {"tutorial_url": settings.GUEST_TUTORIAL_URL, "conf_url": "http://%s?ckey=%s" %(settings.NB_SERVERNAME, user.confkey), "firstname": user.firstname, "email": user.email, "password": user.password } email = EmailMessage( "Welcome to NB, %s" % (user.firstname), render_to_string("email/confirm_newsite", p), settings.EMAIL_FROM, (user.email, ), (settings.EMAIL_BCC, )) email.send() return HttpResponseRedirect('/newsite_thanks') else: user_form = forms.UserForm() ensemble_form = forms.EnsembleForm() return render_to_response("web/newsite.html", {"user_form": user_form, "ensemble_form": ensemble_form})
def send_mail(self, request, newsletter_id): object = Newsletter.objects.get(id=newsletter_id) subscribers = Subscription.objects.filter(subscribed=True) site = Site.objects.get_current() template = render_to_string(object.template, locals(), RequestContext(request)) if request.method == 'POST': object.sent_date = datetime.now() object.save() email = EmailMessage(subject = '%s - %s' % (object.title, site), body = template, from_email = settings.NEWSLETTER_FROM_EMAIL, bcc = [e.email for e in subscribers], headers = {'Reply-To': settings.NEWSLETTER_REPLYTO_EMAIL} ) email.content_subtype = "html" # Main content is now text/html email.send() self.message_user(request, _(u"Newsletter sent successfully")) return HttpResponseRedirect(reverse('admin:newsletters_newsletter_changelist')) opts = Newsletter._meta app_label = opts.app_label return render_to_response('admin/newsletters/send_mail.html', locals(), RequestContext(request))
def send_html_message(subject, html_content, from_email, to_list): # with open( "output.html" , "w") as debug_file: # debug_file.write(html_content) msg = EmailMessage(string_to_email_subject(subject), html_content, from_email, to_list) msg.content_subtype = "html" # Main content is now text/html msg.send()
def send_email(self, email): """Send an email of this response""" metadata = self.crowdsource.get_metadata_keys() text = "\n".join( "{}: {}".format(k, v) for k, v in zip( self.crowdsource.get_header_values(metadata), self.get_values(metadata) ) ) text += "\n{}{}#assignment-responses".format( settings.MUCKROCK_URL, self.crowdsource.get_absolute_url() ) EmailMessage( subject="[Assignment Response] {} by {}".format( self.crowdsource.title, self.user.username if self.user else "Anonymous" ), body=text, from_email=settings.ASSIGNMENTS_EMAIL, to=[email], bcc=[settings.DIAGNOSTIC_EMAIL], ).send(fail_silently=False)
def mail_owners(subject, message, fail_silently=False, connection=None): ''' Sends a message to the owners, as defined by the OWNERS setting. Sends the email to the owners with the language in settings.LANGUAGE_CODE. Use ugettext_lazy if you want your message to be correctly translated. ''' if not settings.OWNERS: return from django.utils import translation cur_language = translation.get_language() try: translation.activate(settings.LANGUAGE_CODE) EmailMessage(settings.EMAIL_SUBJECT_PREFIX + unicode(subject), unicode(message), settings.SERVER_EMAIL, [a[1] for a in settings.OWNERS], connection=connection).send(fail_silently=fail_silently) finally: translation.activate(cur_language)
def test_send_messages_with_dashboardid(): with mock.patch('awx.main.notifications.grafana_backend.requests' ) as requests_mock: requests_mock.post.return_value.status_code = 200 m = {} m['started'] = dt.datetime.utcfromtimestamp(60).isoformat() m['finished'] = dt.datetime.utcfromtimestamp(120).isoformat() m['subject'] = "test subject" backend = grafana_backend.GrafanaBackend("testapikey", dashboardId=42) message = EmailMessage( m['subject'], { "started": m['started'], "finished": m['finished'] }, [], [ 'https://example.com', ], ) sent_messages = backend.send_messages([ message, ]) requests_mock.post.assert_called_once_with( 'https://example.com/api/annotations', headers={ 'Content-Type': 'application/json', 'Authorization': 'Bearer testapikey' }, json={ 'text': 'test subject', 'isRegion': True, 'timeEnd': 120000, 'panelId': None, 'time': 60000, 'dashboardId': 42 }, verify=True, ) assert sent_messages == 1
def test_send_messages_with_username_and_password(): with mock.patch( 'awx.main.notifications.webhook_backend.requests' ) as requests_mock, mock.patch( 'awx.main.notifications.webhook_backend.get_awx_http_client_headers' ) as version_mock: requests_mock.post.return_value.status_code = 200 version_mock.return_value = { 'Content-Type': 'application/json', 'User-Agent': 'AWX 0.0.1.dev (open)' } backend = webhook_backend.WebhookBackend('POST', None, username='******', password='******') message = EmailMessage( 'test subject', {'text': 'test body'}, [], [ 'http://example.com', ], ) sent_messages = backend.send_messages([ message, ]) requests_mock.post.assert_called_once_with( 'http://example.com', auth=('userstring', 'passwordstring'), data=json.dumps({ 'text': 'test body' }, ensure_ascii=False).encode('utf-8'), headers={ 'Content-Type': 'application/json', 'User-Agent': 'AWX 0.0.1.dev (open)' }, verify=True, ) assert sent_messages == 1
def notify_instance_owners(instances, subject, message): # the vms that are facing the problem users = [] # get only enabled clusters for c in Cluster.objects.filter(disabled=False): for i in c.get_all_instances(): if i.name in instances: for u in i.users: users.append(u.email) bcc_list = users subject = '%s %s' % (settings.EMAIL_SUBJECT_PREFIX, subject) recipient_list = [] from_email = settings.SERVER_EMAIL return EmailMessage(subject, message, from_email, recipient_list, bcc_list, headers={ 'Reply-To': '*****@*****.**' }).send()
def send_testmail(request): if request and not request.user.is_superuser: return HttpResponseForbidden('Not authenticated') mode = request.GET.get('mode', None) if mode not in [ 'or_fail', 'direct', 'direct_html', 'threaded', 'override' ]: mode = 'or_fail' subject = mode + ': Testmail from Housekeeping at %s' % str(now()) template = 'cosinnus/common/internet_explorer_not_supported.html' retmsg = '\n\n<br><br> Use ?mode=[or_fail, direct, direct_html, threaded, override]\n\nThe Answer was: ' if mode == 'or_fail': retmsg += force_text( send_mail_or_fail(request.user.email, subject, template, {})) return HttpResponse('Sent mail using or_fail mode. ' + retmsg) if mode == 'direct': retmsg += force_text( send_mail(request.user.email, subject, template, {})) return HttpResponse('Sent mail using direct mode. ' + retmsg) if mode == 'direct_html': template = 'cosinnus/housekeeping/test_html_mail.html' retmsg += force_text( send_mail(request.user.email, subject, template, {}, is_html=True)) return HttpResponse('Sent mail using direct HTML mode. ' + retmsg) if mode == 'threaded': retmsg += force_text( send_mail_or_fail_threaded(request.user.email, subject, template, {})) return HttpResponse('Sent mail using threaded mode. ' + retmsg) if mode == 'override': retmsg += force_text( EmailMessage(subject, 'No content', 'Testing <%s>' % settings.COSINNUS_DEFAULT_FROM_EMAIL, [request.user.email]).send()) return HttpResponse('Sent mail using override mode. ' + retmsg) return HttpResponse('Did not send any mail. ' + retmsg)
def test_send_messages_with_no_verify_ssl(): with mock.patch('awx.main.notifications.rocketchat_backend.requests' ) as requests_mock: requests_mock.post.return_value.status_code = 201 backend = rocketchat_backend.RocketChatBackend( rocketchat_no_verify_ssl=True) message = EmailMessage( 'test subject', 'test body', [], [ 'http://example.com', ], ) sent_messages = backend.send_messages([ message, ]) requests_mock.post.assert_called_once_with( 'http://example.com', data='{"text": "test subject"}', verify=False) assert sent_messages == 1
def send(self, subject, body): for field in filter( lambda x: self.notification_class.init_parameters[x]['type'] == "password", self.notification_class.init_parameters): self.notification_configuration[field] = decrypt_field( self, 'notification_configuration', subfield=field) recipients = self.notification_configuration.pop( self.notification_class.recipient_parameter) if not isinstance(recipients, list): recipients = [recipients] sender = self.notification_configuration.pop( self.notification_class.sender_parameter, None) notification_configuration = deepcopy(self.notification_configuration) for field, params in self.notification_class.init_parameters.items(): if field not in notification_configuration: if 'default' in params: notification_configuration[field] = params['default'] backend_obj = self.notification_class(**notification_configuration) notification_obj = EmailMessage(subject, backend_obj.format_body(body), sender, recipients) with set_environ(**settings.AWX_TASK_ENV): return backend_obj.send_messages([notification_obj])
def write_message(self, message): extra_content: List[str] = [] if isinstance(message, EmailMessage): log_extra_email_content(message, extra_content) if isinstance(message, EmailMultiAlternatives): log_extra_alternatives(message, extra_content) message = EmailMessage( subject=message.subject, body=message.body, from_email=message.from_email, to=message.to, bcc=message.bcc, connection=message.connection, attachments=None, headers=message.extra_headers, cc=message.cc, reply_to=message.reply_to, ) self.__log_extra_content(extra_content) super().write_message(message)
def process_location_reassignment(domain, transitions, new_location_details, user_transitions, site_codes, user_email): try: Processor(domain, transitions, new_location_details, user_transitions, site_codes).process() except Exception as e: email = EmailMessage( subject='[{}] - Location Reassignment Failed'.format( settings.SERVER_ENVIRONMENT), body="The request could not be completed. Something went wrong. " "Error raised : {}. " "Please report an issue if needed.".format(e), to=[user_email], from_email=settings.DEFAULT_FROM_EMAIL) email.send() raise e else: email = EmailMessage( subject='[{}] - Location Reassignment Completed'.format( settings.SERVER_ENVIRONMENT), body="The request has been successfully completed.", to=[user_email], from_email=settings.DEFAULT_FROM_EMAIL) email.send()
def email(request): # send_mail('subject','Hello world','*****@*****.**',['tomail'],fail_silently=False) if request.method=='POST': form = MailSendingForm(request.POST,request.FILES) if form.is_valid(): subject = form.cleaned_data['subject'] message = form.cleaned_data['message'] frommail = form.cleaned_data['frommail'] tomail = form.cleaned_data['tomail'] attachment = form.cleaned_data['attachment'] email = EmailMessage(subject,message,frommail,[tomail]) email.attach(attachment.name,attachment.read(),attachment.content_type) email.send() else: form = MailSendingForm() return render(request,'mailwithattachment.html',{'form':form})
def MailSending(request): if request.method == 'POST': form = MailSendingForm(request.POST, request.FILES) if form.is_valid(): subject = form.cleaned_data['subject'] message = form.cleaned_data['message'] from_mail = form.cleaned_data['from_mail'] to_mail = form.cleaned_data['to_mail'] attachment = form.cleaned_data['attachment'] email = EmailMessage(subject, message, from_mail, [to_mail]) email.attach(attachment.name, attachment.read(), attachment.content_type) email.send() return HttpResponse('Email send successfully :).....!!!!!!') else: form = MailSendingForm() return render(request, 'djangoapp/mailsend.html', {'form': form})
def __send_invitation_creation_notification_by_email(sender, instance): destination_email = instance.invitation_to.email if CustomUser.objects.is_unregistered( destination_email): # pragma: no cover -> no complexity send_email_to_register(destination_email) else: choices = dict(sender.type.field.choices) choice_label = choices.get(instance.type.upper()) email = EmailMessage() email.subject = f"You have a new {choice_label} Invitation" email.body = f""" Hi {instance.invitation_to.username}, {instance.invitation_from.username} sent an email to you. Hugs, """ email.to = [instance.invitation_to.email] email.send()
def test_send_messages(): with mock.patch('awx.main.notifications.slack_backend.WebClient' ) as slack_sdk_mock: WebClient_mock = slack_sdk_mock.return_value WebClient_mock.chat_postMessage.return_value = {'ok': True} backend = slack_backend.SlackBackend('slack_access_token') message = EmailMessage( 'test subject', 'test body', [], [ '#random', ], ) sent_messages = backend.send_messages([ message, ]) WebClient_mock.chat_postMessage.assert_called_once_with( channel='random', thread_ts=None, as_user=True, text='test subject') assert sent_messages == 1
def subscribe_to_newsletter(petition, email): if petition.newsletter_subscribe_method in ["POST", "GET"]: data = petition.newsletter_subscribe_http_data data[petition.newsletter_subscribe_http_mailfield] = email if petition.newsletter_subscribe_method == "POST": requests.post(petition.newsletter_subscribe_http_url, data) elif petition.newsletter_subscribe_method == "GET": requests.get(petition.newsletter_subscribe_http_url, data) elif petition.newsletter_subscribe_method == "MAIL": with get_connection( host=petition.newsletter_subscribe_mail_smtp_host, port=petition.newsletter_subscribe_mail_smtp_port, username=petition.newsletter_subscribe_mail_smtp_user, password=petition.newsletter_subscribe_mail_smtp_password, use_ssl=petition.newsletter_subscribe_mail_smtp_tls, use_tls=petition.newsletter_subscribe_mail_smtp_starttls ) as connection: EmailMessage( petition.newsletter_subscribe_mail_subject.format(email), "", petition.newsletter_subscribe_mail_from, [petition.newsletter_subscribe_mail_to], connection=connection).send(fail_silently=False)
def email(self): """ Send email to award recipient User email """ # Setup logger for debugging logger = logging.getLogger(__name__) # Create email fields this_subject = "You've received an award" email_body = 'Congratulations {0}! {1} has awarded you with {2}. ' +\ 'Your award certificate is attached.' email_body = email_body.format(self.to_name, self.from_name, self.award_type) # Generate PDF path = self.__generate_pdf() filename = os.path.split(path)[1] # Open file and read contents into variable try: pdf = open(path, mode='rb') pdf_content = pdf.read() pdf.close() except OSError as exception: logger.error('OS error: %s ', exception) # Create email with pdf attached email = EmailMessage(subject=this_subject, body=email_body, from_email='*****@*****.**', to=[self.to_email], headers={'Reply-To': '*****@*****.**'}) try: email.attach(filename, pdf_content, 'application/pdf') email.send() except: logger.error('Failed to send email') # Clean-up temp file try: os.remove(path) except OSError: pass
def send_mass_mail( datatuple, fail_silently=False, auth_user=None, auth_password=None, connection=None ): """ Given a datatuple of (subject, message, from_email, recipient_list), send each message to each recipient list. Return the number of emails sent. If from_email is None, use the DEFAULT_FROM_EMAIL setting. If auth_user and auth_password are set, use them to log in. If auth_user is None, use the EMAIL_HOST_USER setting. If auth_password is None, use the EMAIL_HOST_PASSWORD setting. Note: The API for this method is frozen. New code wanting to extend the functionality should use the EmailMessage class directly. """ connection = connection or get_connection( username=auth_user, password=auth_password, fail_silently=fail_silently, ) messages = [ EmailMessage(subject, message, sender, recipient, connection=connection) for subject, message, sender, recipient in datatuple ] return connection.send_messages(messages)
def send_email(self, email): """Send an email of this response""" metadata = self.crowdsource.get_metadata_keys() text = u'\n'.join( u'{}: {}'.format(k, v) for k, v in zip( self.crowdsource.get_header_values(metadata), self.get_values(metadata), ) ) text += u'\n{}{}#assignment-responses'.format( settings.MUCKROCK_URL, self.crowdsource.get_absolute_url(), ) EmailMessage( subject=u'[Assignment Response] {} by {}'.format( self.crowdsource.title, self.user.username if self.user else 'Anonymous', ), body=text, from_email='*****@*****.**', to=[email], bcc=['*****@*****.**'], ).send(fail_silently=False)
def email_signup_home(request): form = EmailListSubscriberForm(request.POST or None) if request.method == 'POST': try: attempted_email = request.POST.get('user_email', False).lower() this_person = EmailListSubscriber.objects.get(user_email=attempted_email) if this_person.is_confirmed: return render(request, 'email_signup_app/confirmation_check.html', {'already_confirmed': True}) elif (this_person.user_email == attempted_email) and (not this_person.is_confirmed): return render(request, 'email_signup_app/confirmation_check.html', {'remind_check_email': True}) except ObjectDoesNotExist: if form.is_valid(): unconf_user = form.save(commit=False) unconf_user.user_email = attempted_email unconf_user.name = request.POST.get('email_sub_name', False).title() unconf_user.save() request.session.setdefault('email_list_conf_sent', 'An email has already been sent') # can acces in template from request.session.email_signup, so it's visible on every page... Just put it in base.html, and # write the form raw so you don't need special form for every view # Send email when testing offline... # send_mail('Please confirm your email subscription to MyWebsite.com', # 'Just click the link below and follow the directions\n\nhttps://www.MyWebsite.com/email_signup_app/{}/{}/'.format(unconf_user.id, unconf_user.random_uuid), # '*****@*****.**', # [unconf_user.user_email], # fail_silently=False) # Send email when live with get_connection(host=EMAIL_HOST, port=EMAIL_PORT, username=EMAIL_HOST_USER, password=EMAIL_HOST_PASSWORD, use_ssl=EMAIL_USE_SSL) as connection: EmailMessage('Please confirm your email subscription to MyWebsite.com', 'Just click the link below and follow the directions\n\nhttps://www.MyWebsite.com/email_signup_app/{}/{}/'.format(unconf_user.id, unconf_user.random_uuid), '*****@*****.**', [unconf_user.user_email], headers={'List-Subscribe': '<{}>'.format(unconf_user.user_email)}, connection=connection).send() return render(request, 'email_signup_app/confirmation_check.html', {'email_sent': True}) return render(request, 'email_signup_app/confirmation_check.html', {'form': form})
def email_report(location_code, to): urlbase = Site.objects.get_current().domain full_url='%(base)s%(path)s?place=%(loc)s&magic_token=%(token)s' % \ {"base": urlbase, "path": reverse("tz_pdf_reports"), "loc": location_code, "token": settings.MAGIC_TOKEN} fd, tmpfilepath = tempfile.mkstemp(suffix=".pdf", prefix="report-%s" % location_code) os.close(fd) command = 'wkhtmltopdf "%(url)s" %(file)s' % { "url": full_url, "file": tmpfilepath } p = subprocess.Popen(command, stdout=PIPE, stderr=PIPE, shell=True) p.communicate() email = EmailMessage('%s Report' % location_code, 'See attachment', settings.EMAIL_LOGIN, to) email.attach_file(tmpfilepath) email.send(fail_silently=False)
def post(self, request, *args, **kwargs): form = self.get_form() if form.is_valid(): from django.core.mail.message import EmailMessage filepath = str(models.Photo.objects.get(id=self.kwargs.get("pk"))) email = EmailMessage(subject='Check out your photo:' + self.kwargs.get("pk"), body='Your photo ID:' + self.kwargs.get("pk") + ' is attached in this mail.', from_email='*****@*****.**',#settings.EMAIL_HOST_USER, to=[form.cleaned_data['to_email']] ) email.attach_file(settings.BASE_DIR + filepath) try: email.send(fail_silently=not(settings.DEBUG)) except BadHeaderError: return HttpResponse('Invalid header found.') return redirect('capture:home') else: return self.form_invalid(form)
def mail(self, request): message = self.render_message(request) headers = {} if self.cleaned_data.has_key('email'): headers = {'Reply-to': self.cleaned_data.get('email')} msg = EmailMessage(self.subject, message, self.sender, self.recipients, headers=headers) if request.FILES: uploaded_file = request.FILES['file'] msg.attach(uploaded_file.name, uploaded_file.read(), uploaded_file.content_type) msg.send() self.after_mail(message=message, headers=headers)
def render_mail(subject, template_prefix, to_emails, context, bcc=None, cc=None, **kwargs): from_email = DEFAULT_FROM_EMAIL bodies = {} for ext in ['html', 'txt']: try: template_name = '{0}.{1}'.format(template_prefix, ext) bodies[ext] = render_to_string(template_name, context).strip() except TemplateDoesNotExist: if ext == 'txt' and not bodies: # We need at least one body raise if 'txt' in bodies: msg = EmailMultiAlternatives(subject, bodies['txt'], from_email, to_emails, bcc=bcc, cc=cc) if 'html' in bodies: msg.attach_alternative(bodies['html'], 'text/html') else: msg = EmailMessage(subject, bodies['html'], from_email, to_emails, bcc=bcc, cc=cc) msg.content_subtype = 'html' # Main content is now text/html return msg
def test_send_messages_fail(): with mock.patch('awx.main.notifications.slack_backend.WebClient' ) as slack_sdk_mock, pytest.raises( RuntimeError, match=r'.*not_in_channel.*'): WebClient_mock = slack_sdk_mock.return_value WebClient_mock.chat_postMessage.return_value = { 'ok': False, 'error': 'not_in_channel' } backend = slack_backend.SlackBackend('slack_access_token') message = EmailMessage( 'test subject', 'test body', [], [ '#not_existing', ], ) sent_messages = backend.send_messages([ message, ]) WebClient_mock.chat_postMessage.assert_called_once_with( channel='not_existing', as_user=True, text='test subject') assert sent_messages == 0
def active(request): id = request.POST.get('id') user2 = User.objects.get(id=id) user2.is_active = 1 user2.save() print 'usuario activado' correo = EmailMessage() correo.subject = "Confirmación de acceso Portal Gastos" correo.body = """¡Bienvenido! Su solicitud fue confirmada. Ya puede ingresar al portal y registrar sus gastos, compras o consumos de tarjeta. Siempre a la orden. Equipo ACERH """ correo.to = [user2.email] correo.send() user = User.objects.filter(is_active=0) return render(request, 'activate.html', { 'user': user, 'users': user.all() })
def pull_translation_files_from_transifex(domain, data, user_email=None): def notify_error(error): email = EmailMessage( subject='[{}] - Transifex pulled translations'.format( settings.SERVER_ENVIRONMENT), body= "The request could not be completed. Something went wrong with the download. " "Error raised : {}. " "If you see this repeatedly and need support, please report an issue. " .format(error), to=[user_email], from_email=settings.DEFAULT_FROM_EMAIL) email.send() version = data.get('version') transifex = Transifex(domain, data.get('app_id'), data.get('target_lang') or data.get('source_lang'), data.get('transifex_project_slug'), version, lock_translations=data.get('lock_translations'), use_version_postfix='yes' in data['use_version_postfix']) translation_file = None try: translation_file, filename = transifex.generate_excel_file() with open(translation_file.name, 'rb') as file_obj: email = EmailMessage( subject='[{}] - Transifex pulled translations'.format( settings.SERVER_ENVIRONMENT), body="PFA Translations pulled from transifex.", to=[user_email], from_email=settings.DEFAULT_FROM_EMAIL) email.attach(filename=filename, content=file_obj.read()) email.send() except Exception as e: notify_error(e) six.reraise(*sys.exc_info()) finally: if translation_file and os.path.exists(translation_file.name): os.remove(translation_file.name)
def get(self, *args, **kwargs): from django.conf import settings user = User.objects.get(id=35) print user.qrcode.url subject = "Your sabha unique identity" message = "Keep attached QR code with you" sender = '*****@*****.**' recipients = ['*****@*****.**'] mail = EmailMessage(subject, message, sender, recipients) path = settings.BASE_DIR + user.qrcode.url print path fp = open(path, 'rb') msg_img = MIMEImage(fp.read()) msg_img.add_header('Content-ID', '<{}>'.format(user.qrcode.url)) fp.close() print msg_img mail.attach(msg_img) # send_mail(subject, message, sender, recipients) mail.send() return Response({'msg': 'success...'}, status=status.HTTP_200_OK)
def MailSending(request): form = MailSendingForm if request.method == 'POST': form = MailSendingForm(request.POST, request.FILES) if form.is_valid: subject = request.POST.get('subject') message = request.POST.get('message') from_mail = request.POST.get('from_mail') to_mail = request.POST.get('to_mail') attachment = request.POST.get('attachment') email = EmailMessage(subject, message, from_mail, [to_mail]) email.attach(attachment.name, attachment.read(), attachment.content_type) email.send() return HttpResponse('Mail Sent Successfully!') else: form = MailSendingForm() return render(request, 'newapp/mailsend.html', {'form': form})
def approve(request, report_id): """ approves the pending reports :param report_id: The id of pending report :return: redirect to list of pending reports """ report = get_report_by_id(report_id) report.confirm_status = 1 report.save() admin = Administrator.objects.get(user=request.user) volunteer_shift_list = report.volunteer_shifts.all() report_list = generate_report(volunteer_shift_list) volunteer = report.volunteer post_pdf = render_to_pdf( 'administrator/pdf.html', { 'report': report, 'admin': admin, 'report_list': report_list, }, ) message = render_to_string( 'administrator/confirm_report.html', { 'volunteer': volunteer, 'admin': admin, } ) msg = EmailMessage( "Report Approved", message, "*****@*****.**", [report.volunteer.email] ) msg.attach('file.pdf', post_pdf, 'application/pdf') msg.send() return HttpResponseRedirect('/administrator/report')
def send_email(self, request, fail_silently=False): self.request = request if EmailMessage(**self.get_message_dict()).send( fail_silently=fail_silently): messages.success(request, _('Message is sent successufully!'))