def save_model(self, request, obj, form, change): obj.save() #Send email for newly assigned incidents if ('assignee' in form.changed_data or change == False) and obj.assignee != None: email_body_tpl = """Hi %(first_name)s, You have been assigned a new incident. To follow up, click this link: https://vincent.berniesanders.com/incidents/%(incident_id)s Reported by: %(reporter_name)s %(reporter_phone)s Type: %(type)s Description: %(description)s""" plain_text_body = email_body_tpl % {'first_name': obj.assignee.first_name, 'description': obj.description, 'type': obj.nature, 'reporter_name': obj.reporter_name, 'reporter_phone': obj.reporter_phone, 'incident_id': obj.id} html_body = linebreaks(urlize(plain_text_body)) email_message = EmailMultiAlternatives(subject='New Vincent Assignment', body=plain_text_body, from_email='Voter Incident Reporting System <*****@*****.**>', to=[obj.assignee.email], reply_to=[obj.creator_email, '*****@*****.**'], headers={'X-Mailgun-Track': False}) email_message.attach_alternative(html_body, "text/html") email_message.send(fail_silently=False)
def mail_managers(subject, message, fail_silently=False, connection=None, html_message=None): """Send a message to the managers, as defined by the MANAGERS setting.""" if not settings.MANAGERS: return if not all( isinstance(a, (list, tuple)) and len(a) == 2 for a in settings.MANAGERS): raise ValueError('The MANAGERS setting must be a list of 2-tuples.') mail = EmailMultiAlternatives( '%s%s' % (settings.EMAIL_SUBJECT_PREFIX, subject), message, settings.SERVER_EMAIL, [a[1] for a in settings.MANAGERS], connection=connection, ) if html_message: mail.attach_alternative(html_message, 'text/html') mail.send(fail_silently=fail_silently)
def send_email(self, context): """ Sends an email to admin containing a csv of all users who have logged in within the given days and have staff access role in active courses (Courses with end date in the future). Arguments: context: context for the email template """ plain_content = self.render_template(self.txt_template_path, context) html_content = self.render_template(self.html_template_path, context) with open(self.csv_filename, 'r') as csv_file: email_message = EmailMultiAlternatives(self.subject, plain_content, self.from_address, to=self.to_addresses) email_message.attach_alternative(html_content, 'text/html') email_message.attach(self.csv_filename, csv_file.read(), 'text/csv') email_message.send() remove(self.csv_filename)
def handle(self, *args, **options): talks = TalkExtraProperties.objects.exclude(ticket_voucher="").exclude(published=False) if not options['reinvite']: talks = talks.exclude(voucher_sent=True) invited = 0 for talk in talks: for user in talk.submission.speakers.all(): context = { 'name': user.name, 'voucher': talk.ticket_voucher, 'email': user.email, } body = loader.render_to_string("ticketholders/invite_speaker.txt", context) subject = "Ticket voucher for DjangoCon" subject = ''.join(subject.splitlines()) email_message = EmailMultiAlternatives(subject, body, "*****@*****.**", [user.email]) email_message.send(fail_silently=False) if not talk.voucher_sent: self.stdout.write(self.style.SUCCESS("Invited {}".format(user.email))) else: self.stdout.write(self.style.SUCCESS("Re-invited {}".format(user.email))) talk.voucher_sent = True talk.save() invited += 1 self.stdout.write(self.style.SUCCESS("Sent {} vouchers".format(invited)))
def task_send_invoice(invoice, old_status=None): urlsafe_token = invoice.generate_token() subject = "Presupuesto" from_email = settings.ADMIN_EMAIL to = invoice.proposal.event.customer.email template = loader.get_template("base/email/invoice.html") domain = settings.CATERFULL_BASE_URL context = Context({ 'token': urlsafe_token, 'domain': domain, 'invoice': invoice, 'iidb64': urlsafe_base64_encode(force_bytes(invoice.id)) }) text_content = template.render(context) msg = EmailMultiAlternatives(subject, text_content, from_email, [to]) invoice_pdf = generate_invoice_pdf(invoice=invoice) msg.content_subtype = "html" msg.attach_file(invoice_pdf.name, 'application/pdf') response = OK try: with transaction.atomic(): if not invoice.has_payment_order(): payment = create_payment(invoice.proposal.get_total()) invoice.set_payment(payment=payment) msg.send(fail_silently=False) # invoice.has_been_sent() except SMTPException as e: print(e) invoice.reset_token(restart_status=True, old_status=old_status) response = ERROR except Exception as e: invoice.reset_token(restart_status=True, old_status=old_status) response = ERROR print(e) return response
class PasswordResetForm(authforms.PasswordResetForm, BootstrapForm): def save(self, from_email, domain_override=None, email_template_name='registration/password_reset_email.html', use_https=False, token_generator=default_token_generator, request=None): try: user = User.objects.get(email=self.cleaned_data['email']) site = Site.objects.get(name='TicketTracker') except Exception, e: raise ValidationError(e) ctx = Context({ 'email': user.email, 'domain': site.domain, 'site_name': site.name, 'uid': int_to_base36(user.id), 'user': user, 'token': token_generator.make_token(user), 'protocol': use_https and 'https' or 'http', }) text_body = loader.get_template( 'email/email_password_reset.txt').render(ctx) html_body = loader.get_template( 'email/email_password_reset.html').render(ctx) try: bcc = [] if hasattr(settings, 'EMAIL_LOG'): bcc.append(settings.EMAIL_LOG) email = EmailMultiAlternatives('Password reset for TicketTracker', text_body, settings.SERVER_EMAIL, [user.email], bcc) email.attach_alternative(html_body, 'text/html') email.send() except Exception, ex: pass # TODO: do something when SMTP fails, but do not draw an error page
def send_mail(template_name, subject, to_addresses, cc=None, bcc=None, from_email=None, **context): """ Helper for sending templated email :param str template_name: Name of the template to send. There should exist a txt and html version :param str subject: Subject line of the email :param str from_email: From address for email :param list to_addresses: List of addresses to email. If str is provided, wrapped in list :param list cc: List of addresses to carbon copy :param list bcc: List of addresses to blind carbon copy :param str custom_message Custom email message - for use instead of a template :kwargs: Context vars for the email template """ context["base_url"] = BASE_URL text_content = get_template( "emails/{}.txt".format(template_name)).render(context) html_content = get_template( "emails/{}.html".format(template_name)).render(context) if not isinstance(to_addresses, list): to_addresses = [to_addresses] from_address = from_email or EMAIL_FROM_ADDRESS email = EmailMultiAlternatives(subject, text_content, from_address, to_addresses, cc=cc, bcc=bcc) email.attach_alternative(html_content, "text/html") email.send()
def sendMassiveHtmlEmails(datatuple, fail_silently=False, auth_user=None, auth_password=None, connection=None): """ Given a datatuple of (subject, message, html_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. """ connection = connection or get_connection( username=auth_user, password=auth_password, fail_silently=fail_silently, ) plain_text_message = '' messages = [] step = 100 email_list_length = len(datatuple[3]) for j in range(0, email_list_length, step): if j + step > email_list_length: bcc_recipents = datatuple[3][j:] else: bcc_recipents = datatuple[3][j:j + step] message = EmailMultiAlternatives(datatuple[0], plain_text_message, datatuple[2], alternatives=[(datatuple[1], 'text/html')], connection=connection, bcc=bcc_recipents) messages.append(message) connection.send_messages(messages) return
def send_contact_message(communication_type, course, sender_username, sender_email, message, fail_silently=False, connection=None): # Add course name to the message body message = "%s: %s\n\n%s" % (_("Course"), course, message) subject = "%s | %s <%s>" % (communication_type.title, sender_username, sender_email) headers = {'Reply-To': sender_email} destination = communication_type.destination if not destination: if not settings.MANAGERS: logger.error('Could not send a contact message because there is no destination email configured neither in the communication type or the MANAGERS setting.') return else: to = [m[1] for m in settings.MANAGERS] else: to = [destination] try: if settings.SEND_CONTACT_EMAIL_FROM_SENDER: from_ = sender_email else: from_ = settings.DEFAULT_FROM_EMAIL except AttributeError: from_ = settings.DEFAULT_FROM_EMAIL mail = EmailMultiAlternatives( u'%s%s' % (settings.EMAIL_SUBJECT_PREFIX, subject), message, from_, to, connection=connection, headers=headers, ) mail.send(fail_silently=fail_silently)
def send_mail(subject, message, from_email, recipient_list, fail_silently=False, auth_user=None, auth_password=None, connection=None, html_message=None, timeout=None, max_retries=3, retry_wait=1): """ Easy wrapper for sending a single message to a recipient list. All members of the recipient list will see the other recipients in the 'To' field. """ for i in range(max_retries): try: connection = connection or get_connection( username=auth_user, password=auth_password, fail_silently=fail_silently, timeout=timeout) mail = EmailMultiAlternatives(subject, message, from_email, recipient_list, connection=connection) if html_message: mail.attach_alternative(html_message, 'text/html') return mail.send() except Exception: if i >= max_retries - 1: raise if retry_wait: sleep(retry_wait)
def send_mass_html_mail(datatuple, fail_silently=False, auth_user=None, auth_password=None, connection=None): """ Given a datatuple of (subject, message, html_message, from_email, recipient_list), sends each message to each recipient list. Returns the number of emails sent. If from_email is None, the DEFAULT_FROM_EMAIL setting is used. If auth_user and auth_password are set, they're used to log in. If auth_user is None, the EMAIL_HOST_USER setting is used. If auth_password is None, the EMAIL_HOST_PASSWORD setting is used. NOTE: This is a variant of send_mass_mail that allows including an html template. https://docs.djangoproject.com/en/1.8/_modules/django/core/mail/#send_mass_mail """ connection = connection or get_connection(username=auth_user, password=auth_password, fail_silently=fail_silently) messages = [] for subject, message, html_message, sender, recipient in datatuple: message = EmailMultiAlternatives(subject, message, sender, recipient, connection=connection) if html_message: message.attach_alternative(html_message, "text/html") messages.append(message) return connection.send_messages(messages)
def payment_notification(user, card, plan, number_payment): try: to = user.email data = {'domain_fron': 'app.ezonseller.com', 'url': settings.URL, 'username': user.username, 'msg': 'Payment Confirmation', 'card': card, 'creditCard': card.number_card[-4:], 'plan': plan, 'numberPayment': number_payment } subject, from_email = data['msg'], EMAIL_HOST_USER text_content = render_to_string("email/payment_notification.html", data) html_content = render_to_string("email/payment_notification.html", data) send = EmailMultiAlternatives(subject, text_content, from_email, [to], headers={'From': 'Ezonseller <'+from_email+'>', 'Reply-to': 'Ezonseller <'+from_email+'>'}) send.attach_alternative(html_content, "text/html") send.send() return True except: return False
def enviar_correo(request): correo=request.POST.get("email",None) Usuario=MyUser.objects.get(username=correo) print "correo:"+ correo if Usuario is not None: email_context={ 'Recuperar Contrasena', Usuario.get_full_name(), Usuario.username, Usuario.password } subject='Recuperar contrasena' text_content = Usuario.password from_email= settings.EMAIL_HOST_USER to='*****@*****.**' msg=EmailMultiAlternatives(subject,text_content,from_email,[to]) #se envia el correo msg.send() return HttpResponseRedirect('/')
def check_daily_submissions(): """Check the action submission queue and send out notifications to admin when there are still submission in the queue. algorithm for queue processing: 2. every 24 hours: send email with queue size unless queue size is zero. """ submission_count = ActionMember.objects.filter( action__type="activity", approval_status="pending").count() if submission_count: challenge = challenge_mgr.get_challenge() subject = "[%s] %d Remaining Pending Action Submissions" % ( challenge.name, submission_count) message = "There are %d remaining pending action submissions as of %s." % ( submission_count, datetime.datetime.today()) if challenge.email_enabled and challenge.contact_email: print "Sending new submission notification to %s" % challenge.contact_email mail = EmailMultiAlternatives(subject, message, challenge.contact_email, [ challenge.contact_email, ]) mail.send()
def send_mail(self, subject_template_name, email_template_name, context, from_email, to_email, html_email_template_name=None): """ Sends a django.core.mail.EmailMultiAlternatives to `to_email`. """ subject = loader.render_to_string(subject_template_name, context) # Email subject *must not* contain newlines subject = ''.join(subject.splitlines()) body = loader.render_to_string(email_template_name, context) email_message = EmailMultiAlternatives(subject, body, from_email, [to_email]) if html_email_template_name is not None: html_email = loader.render_to_string(html_email_template_name, context) email_message.attach_alternative(html_email, 'text/html') return email_message.send()
def send_mail_wrapper(subject, template, context, recipients): if not recipients: return subject = settings.EMAIL_SUBJECT_PREFIX + subject body = render_to_string(template + '.txt', context) if settings.IS_TEST: logger.info('Sending mail <{}> to <{}>:\n{}'.format( subject, ', '.join(recipients), body)) return mail = EmailMultiAlternatives(subject=subject, body=body, from_email="*****@*****.**", to=recipients, alternatives=[(render_to_string( template + '.html', context), 'text/html')], reply_to=['*****@*****.**']) try: if mail.send() != 1: raise RuntimeError('Unknown failure???') except Exception: dispatch_general_alert('Could not send mail <{}> to <{}>:\n{}'.format( subject, ', '.join(recipients), traceback.format_exc()))
def task_sendmail_confirm_registration(order): subject = "Confirmacion de correo" from_email = settings.ADMIN_EMAIL to = order.user.email template = loader.get_template("base/email/registration_confirm.html") domain = settings.CATERFULL_BASE_URL token = default_token_generator.make_token(order.user) context = Context({ 'user': order.user, 'domain': domain, 'key': order.key, 'token': token }) text_content = template.render(context) msg = EmailMultiAlternatives(subject, text_content, from_email, [to]) try: msg.send(fail_silently=False) order.pending = False order.save() except SMTPException as e: print(e)
def send_activation_email(request, user_profile): ctx_dict = { 'host_name': settings.EXTERNAL_HOST_NAME, 'use_https': settings.USE_HTTPS, 'user_name': user_profile.user.username, 'activation_key': user_profile.activation_key, 'expiration_days': settings.ACCOUNT_ACTIVATION_DAYS } subject = render_to_string('ecm/auth/activation_email_subject.txt', ctx_dict, context_instance=Ctx(request)) # Email subject *must not* contain newlines subject = ''.join(subject.splitlines()) txt_content = render_to_string('ecm/auth/activation_email.txt', ctx_dict, Ctx(request)) html_content = render_to_string('ecm/auth/activation_email.html', ctx_dict, Ctx(request)) msg = EmailMultiAlternatives(subject, body=txt_content, to=[user_profile.user.email]) msg.attach_alternative(html_content, "text/html") msg.send()
def send_mail(subject, message, from_email, recipient_list, fail_silently=False, auth_user=None, auth_password=None, connection=None, html_message=None): """ Easy wrapper for sending a single message to a recipient list. All members of the recipient list will see the other recipients in the 'To' field. If auth_user is None, use the EMAIL_HOST_USER settings. If auth_password is None, use the EMAIL_HOST_PASSWORD settings. 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, ) mail = EmailMultiAlternatives(subject, message, from_email, recipient_list, connection=connection) if html_message: mail.attach_alternative(html_message, 'text/html') return mail.send()
def SendEmail(request): subject, from_email = 'Violation Message', '*****@*****.**' to = ['*****@*****.**'] address = '' if 'reqAddress' in request.POST: address = request.POST['reqAddress'] if 'emailText' in request.POST: userEmail = request.POST['emailText'] to.append(userEmail) county_code = datamodel.get_county_code_by_address(address) pws_info = datamodel.get_pws_details_by_county(county_code) #Get Template emailTemplate = get_template('email.html') data = Context({ 'pws_info': pws_info }) emailContent = emailTemplate.render(data) msg = EmailMultiAlternatives(subject, 'Sample', from_email, to) msg.attach_alternative(emailContent, "text/html") msg.send() return HttpResponse(str(0), content_type="text/plain")
def send_player_invite(name, email, uid, trip_name, trip_template, attachments): subject = "You have been selected for {}!".format(trip_name) message = "" from_email = settings.EMAIL_HOST_USER recipient_list = [email] html_message = trip_template html_message = html_message.replace("{{player_name}}", name) html_message = html_message.replace( "{{invitation_link}}", "{}?uid={}".format(settings.APP_URL, uid), ) invitation_email = EmailMultiAlternatives( subject=subject, body="", from_email=from_email, to=recipient_list, reply_to=[from_email], ) invitation_email.attach_alternative(html_message, "text/html") for attachment in attachments: invitation_email.attach_file(attachment.document.path) return invitation_email.send(fail_silently=True) return send_mail( subject=subject, message=message, from_email=from_email, recipient_list=recipient_list, html_message=html_message, fail_silently=True, )
def sender(template_name, to=None, cc=None, bcc=None, attach_files=[], **kvp): try: tmpl = Mail.objects.get(template_name=template_name) except Mail.DoesNotExist: return if to and cc: for v in to: try: cc.remove(v) except ValueError: continue if to and bcc: for v in to: try: bcc.remove(v) except ValueError: continue subject = tmpl.subject.format(**kvp) body = PartialFormatter().format(tmpl.message, **kvp) from_email = DEFAULT_FROM_EMAIL connection = get_connection(fail_silently=False) mail = EmailMultiAlternatives( subject=subject, body=body, from_email=from_email, to=to, cc=cc, bcc=bcc, connection=connection) for attach_file in attach_files: mail.attach_file(attach_file) try: mail.send() except SMTPDataError as e: logger.error(e)
def send_mail( context, template_name, to_email_list, from_email=settings.DEFAULT_FROM_EMAIL, bcc=None, cc=None, file_path=None, ): """ A static method that takes inputs and sends mail & sms """ if bcc is None: bcc = [] subject = render_to_string("{}{}.txt".format(template_name, "sub"), context) message = EmailMultiAlternatives( subject=subject, body=render_to_string("{}{}.txt".format(template_name, "msg"), context), from_email=from_email, to=to_email_list, bcc=bcc, cc=cc, alternatives=[ ( render_to_string("{}{}.html".format(template_name, "msg"), context), "text/html", ), ], ) # attach file if file_path: message.attach_file(file_path) message.send()
def send_email(self, context, node=None): if not node: recipients = Group.objects.get( name=settings.READ_DATAJSON_RECIPIENT_GROUP).user_set.all() else: recipients = node.admins.all() emails = [user.email for user in recipients] if not emails: # Nothing to do here return start_time = self._format_date(self.task.created) subject = u'[{}] API Series de Tiempo: {}'.format( settings.ENV_TYPE, start_time) msg = render_to_string('indexing/report.txt', context=context) mail = EmailMultiAlternatives(subject, msg, settings.EMAIL_HOST_USER, emails) html_msg = render_to_string('indexing/report.html', context=context) mail.attach_alternative(html_msg, 'text/html') mail.attach('errors.log', self.task.logs, 'text/plain') mail.attach('catalogs.csv', attachments.generate_catalog_attachment(node=node), 'text/csv') mail.attach('datasets.csv', attachments.generate_dataset_attachment(node=node), 'text/csv') mail.attach('distributions.csv', attachments.generate_distribution_attachment(node=node), 'text/csv') mail.attach('series.csv', attachments.generate_field_attachment(node=node), 'text/csv') sent = mail.send() if emails and not sent: raise ValueError
def send_mail_with_reply_to_field(subject, message, from_email, recipient_list, fail_silently=False, reply_to=None, auth_user=None, auth_password=None, connection=None, html_message=None): """ This function replaces send_mail in django.core.mail in order to have reply_to functionality. Easy wrapper for sending a single message to a recipient list. All members of the recipient list will see the other recipients in the 'To' field. If auth_user is None, the EMAIL_HOST_USER setting is used. If auth_password is None, the EMAIL_HOST_PASSWORD setting is used. 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, ) # get_connection imported from django.core.mail mail = EmailMultiAlternatives(subject, message, from_email, recipient_list, reply_to=reply_to, connection=connection) if html_message: mail.attach_alternative(html_message, 'text/html') return mail.send()
def mail_username_retrieve(email, secret): """ Sends an email to the specified email address containing the url for username retrieval. Arguments: - email <str> - secret <str>: username retrieval secret in the user's session """ msg = loader.get_template("email/username-retrieve.txt").render( { "email": email, "secret": secret, "username_retrieve_url": "{}/username-retrieve/complete?secret={}".format( settings.BASE_URL, secret ), } ) subject = "PeeringDB username retrieval" mail = EmailMultiAlternatives(subject, msg, settings.DEFAULT_FROM_EMAIL, [email]) mail.send(fail_silently=False)
def mail_admins_with_from( subj, msg, from_addr, fail_silently=False, connection=None, html_message=None ): """ mail admins but allow specifying of from address """ if not settings.ADMINS: return # set plain text message msg_raw = strip_tags(msg) mail = EmailMultiAlternatives( f"{settings.EMAIL_SUBJECT_PREFIX}{subj}", msg, from_addr, [a[1] for a in settings.ADMINS], connection=connection, ) # attach html message mail.attach_alternative(msg.replace("\n", "<br />\n"), "text/html") mail.send(fail_silently=fail_silently)
def get(self, request, *args, **kwargs): username = kwargs.get('username') if not username: return Response({ 'status': 'error', 'msg': 'Username is required' }, status=status.HTTP_400_BAD_REQUEST) user = User.objects.filter(username=username).first() if not user: return Response({ 'status': 'error', 'msg': 'User not found' }, status=status.HTTP_400_BAD_REQUEST) code = ''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(15)) user_code = UserCode(user=user, code=code) user_code.save() d = { 'url': request.build_absolute_uri( reverse('api:reset-password', kwargs={'token': code})) } plaintext = get_template('pw_reset.txt') htmly = get_template('pw_reset.html') subject, from_email, to = '[EmoTalk] Password Reset', '*****@*****.**', user.email text_content = plaintext.render(d) html_content = htmly.render(d) msg = EmailMultiAlternatives(subject, text_content, from_email, [to]) msg.attach_alternative(html_content, "text/html") msg.send() return Response({'status': 'ok'})
def mail_admins_contact(request, subject, message, context, sender, to): """Send a message to the admins, as defined by the ADMINS setting.""" LOGGER.info( 'contact form from %s', sender, ) if not to and settings.ADMINS: to = [a[1] for a in settings.ADMINS] elif not settings.ADMINS: messages.error(request, _('Message could not be sent to administrator!')) LOGGER.error('ADMINS not configured, can not send message!') return mail = EmailMultiAlternatives( '{0}{1}'.format(settings.EMAIL_SUBJECT_PREFIX, subject % context), message % context, to=to, headers={'Reply-To': sender}, ) mail.send(fail_silently=False) messages.success(request, _('Message has been sent to administrator.'))
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