def save(self, validated_data): email = validated_data.get('email') new_user = User( username=email, email=email, is_active=False, ) new_user.save() # Create new salary instance new_salary = Salary(user=new_user) new_salary.save() # Create new adminprofile instance new_adminprofile = AdminProfile(user=new_user) new_adminprofile.save() # Create new company instance and assign admin_profile to new admin_profile, other fields have placeholder values new_company = Company(adminprofile=new_adminprofile) new_company.save() registration = Registration( user=new_user, code_type='RV', profile_type='AP', ) registration.save() email = Email( to=email, subject='Thank you for registering with RazzPay!', content=f'Here is your validation code: {registration.code}') email.save(request=self.context['request']) return new_user
def invite(request, id): event = get(Event, pk=id) email = Email(user = request.user, subject = "You're invited to %s" % (event.title), message = render_to_string("event_invite_email.txt", locals()), event = event ) email.save() return HttpResponseRedirect(reverse('emails-update', args=[email.id]))
def email(user, subj, template, context, check_pref=False, from_email=settings.DEFAULT_FROM_EMAIL): from emails.models import Email from subs.models import Subscription if user.bounce not in (None, 0, 1): # 1 bounce is ok, but not more return False if check_pref: c = MailoutCategory.objects.get(pk=check_pref) s = MailoutUser.objects.filter(user=user, category=c).first() if not s: return subject = 'Hi %s, %s' % (user.first_name, subj) from_email = "%s <%s>" % (settings.NAME, from_email) if 'Feedback' in subj: subject = subj # subject must not contain newlines subject = ''.join(subject.splitlines()) em = Email(to=user, subject=subject, body='') em.save() # add some generic_context context.update(settings.GENERIC_CONTEXT) context.update({ 'user': user, 'subject': subj, # use original short subject here 'template': template, # for tracking 'em': em, 'category': check_pref or '' }) body = render_to_string('emails/%s.html' % template, context) text = render_as_text(body) em.body = '%s<!--\n%s\n-->' % (body, text) em.save() headers = { 'List-Unsubscribe': '<mailto:%s>' % UNSUBSCRIBE_EMAIL, 'X-EMAIL-ID': str(em.pk), 'X-USER-ID': str(user.pk), } m = mail.EmailMultiAlternatives(subject, text, from_email, [user.email], headers=headers) m.attach_alternative(body, "text/html") # live or test, no sending in dev if not settings.DEBUG or hasattr(mail, 'outbox'): try: m.send() except Exception as e: logging.basicConfig(filename=settings.LOG) logging.warning(e) return False return True
def save(self, validated_data): # Obtain user info email = validated_data.get('email') first_name = validated_data.get('first_name') last_name = validated_data.get('last_name') company = self.context['request'].user.company # Obtain salary info gross_month = validated_data.get('gross_month') position = validated_data.get('position') new_user = User( username=email, email=email, first_name=first_name, last_name=last_name, company_id=company.id, # Mark as true so that employee user instance can be used immediately without waiting for employee to register via email code is_active=True, ) new_user.save() # Create new employeeprofile instance new_employeeprofile = EmployeeProfile(user=new_user) new_employeeprofile.save() # Create new salary instance new_salary = Salary(user=new_user, position=position, gross_month=round((gross_month), 2), ahv_amount=round((gross_month * 0.05125), 2), alv_amount=round((gross_month * 0.011), 2), pension=round((gross_month * 0.01), 2), net=round( (gross_month - (gross_month * 0.05125) - (gross_month * 0.011) - (gross_month * 0.01)), 2)) new_salary.save() registration = Registration( user=new_user, code_type='RV', profile_type='EP', ) registration.save() email = Email( to=email, subject='Welcome to RazzPay!', content=f'Here is your validation code: {registration.code}') email.save(request=self.context['request']) return new_user
def send_password_reset_email(self): email = self.validated_data.get('email') user = User.objects.get(email=email) user.registration.code = code_generator() user.registration.code_used = False user.registration.code_type = 'PR' user.registration.save() email = Email( to=email, subject='Reset your password for RazzPay', content= f'Here is your RazzPay password reset code: {user.registration.code}' ) email.save(request=self.context['request'])
def map_emails(g): unread_list = g.inbox().mail(unread=True) for email_object in unread_list: email_object.fetch() message_id = email_object.headers['Message-ID'].replace('<', '').replace('>', '') sender = email_object.headers['From'] body = strip_tags(email_object.body) body = '\n'.join(filter(None, body.replace('\t', '').replace('\r\n', '\n').split('\n'))) if body.strip(' \t\n\r') == '' or Email.objects.filter(message_id=message_id).count() > 0: email_object.add_label('discarded') continue subject = email_object.subject new = Email(message_id=message_id, subject=subject, body=body, sender=sender) new.save() email_object.read()
def send_message(message, to_user, email_type): # comment this out to test sending emails in other environments if settings.ENVIRONMENT != 'production': return email = Email(user=to_user, subject=message.subject, text_body=message.text, html_body=message.html, to_address=message.to[0], from_address=message.from_address, email_type=email_type) email.save() s = sendgrid.Sendgrid(settings.EMAIL_HOST_USER, settings.EMAIL_HOST_PASSWORD, secure=True) s.smtp.send(message)
def log_email(to, from_email, subject, message): email = Email( to=to, from_email=from_email, subject=subject, message=message ) email.save()
print i try: print "[" + mail["From"] + "] :" + mail["Subject"] except: try: print "[" + mail["From"] + "] :" except: pass content = unicode(mail.__str__(), errors="ignore") mailsave = Email() mailsave.Sender = mail["From"] mailsave.Content = content mailsave.Title = mail["Subject"] mailsave.save() if mail.get_content_maintype() != "multipart": continue # we use walk to creatone a generator so we can iterate on the parts and forget about the recursive headach j = 0 for part in mail.walk(): # multipart are just containers, so we skip them if part.get_content_maintype() == "multipart": continue # is this part an attachment ? if part.get("Content-Disposition") is None: continue filename = part.get_filename()
status = random.choice(["sent", "scheduled", "draft"]) email = Email( subject=fake.sentences(nb=1, ext_word_list=None)[0], body=fake.text(max_nb_chars=200, ext_word_list=None), status=status, created_by=random.choice(users), ) if status == "scheduled": email.time_scheduled = fake.date_time_this_month(before_now=False, after_now=True, tzinfo=pytz.UTC) elif status == "sent": email.time_sent = fake.date_time_this_month(before_now=True, after_now=False, tzinfo=pytz.UTC) email.save() emails.append(email) print("Generating hackathons...") hackathons = [] for i in range(3): hackathon = Hackathon( name="Hack " + fake.state(), date=fake.future_date(end_date="+30d", tzinfo=None), fundraising_goal=random.randint(1000, 10000), ) hackathon.save() hackathons.append(hackathon) print("Generating tiers...") tiers = []
def save(self, request): from django.template.loader import render_to_string from django.template import RequestContext from emails.models import Email from newsletters.utils import newsletter_articles_list, newsletter_news_list, \ newsletter_pages_list, newsletter_jobs_list from site_settings.utils import get_setting # converted from function newsletters_generate_processor opening_text = render_to_string('newsletters/opening_text.txt', context_instance=RequestContext(request)) simplified = self.cleaned_data['format'] try: simplified = int(simplified) except: simplified = 0 # articles art_content = "" if self.cleaned_data['articles']: articles_days = self.cleaned_data['articles_days'] art_content = newsletter_articles_list(request, articles_days, simplified) # calendar events event_content = "" if self.cleaned_data['events']: pass # news news_content = "" if self.cleaned_data['news']: news_days = self.cleaned_data['news_days'] news_content = newsletter_news_list(request, news_days, simplified) # jobs job_content = "" if self.cleaned_data['jobs']: jobs_days = self.cleaned_data['jobs_days'] job_content = newsletter_jobs_list(request, jobs_days, simplified) # pages page_content = "" if self.cleaned_data['pages']: pages_days = self.cleaned_data['pages_days'] page_content = newsletter_pages_list(request, pages_days, simplified) # jumplink jumplink_content = "" if self.cleaned_data['jump_links']: jumplink_content = render_to_string('newsletters/jumplinks.txt', locals(), context_instance=RequestContext(request)) # login block login_content = "" if self.cleaned_data['include_login']: login_content = render_to_string('newsletters/login.txt', context_instance=RequestContext(request)) # rss list email_d = {} # store all content in email_d["[content]"] # will be used to replace [content] in the template email_d["[content]"] = opening_text # get the newsletter template now template = 'newsletters/templates/%s' % (self.cleaned_data['template']) email_d['template_path_name'] = template #check if we have [jumplink] in the email template, if not, #include the jumplinks at the top of the newsletter template_content = render_to_string(template) if jumplink_content: if template_content.find("[jumplinks]") == -1: email_d["[content]"] += jumplink_content email_d["[content]"] += "%s%s%s%s%s%s" % (login_content, event_content, art_content, news_content, job_content, page_content) email_d["[jumplinks]"] = jumplink_content email_d["[articles]"] = art_content email_d["[calendarevents]"] = event_content email_d["[events]"] = event_content email_d["[jobs]"] = job_content email_d["[contentmanagers]"] = page_content email_d["[pages]"] = page_content email_d["[releases]"] = news_content email_d["[news]"] = news_content email_d["[sitewebmaster]"] = get_setting('site', "global", "sitewebmaster") email_d["[sitedisplayname]"] = get_setting('site', "global", "sitedisplayname") today = datetime.date.today() email_d["[monthsubmitted]"] = today.strftime("%B") # June email_d["[yearsubmitted]"] = today.strftime("%Y") # 2010 email_d["[unsubscribeurl]"] = "[unsubscribeurl]" email_d["[currentweekdayname]"] = today.strftime("%A") # Wednesday email_d["[currentday]"] = today.strftime("%d") email_d["[currentmonthname]"] = today.strftime("%B") email = Email() is_valid = email.template_body(email_d) email.sender_display = "%s %s" % (request.user.first_name, request.user.last_name) email.sender = request.user.email email.reply_to = request.user.email email.recipient = request.user.email #email.send_to_email2 email.content_type = 'text/html' personalize_subject_first_name = self.cleaned_data['personalize_subject_first_name'] personalize_subject_last_name = self.cleaned_data['personalize_subject_last_name'] email.subject = self.cleaned_data['subject'] if personalize_subject_first_name and personalize_subject_last_name: email.subject = "[firstname] [lastname], " + email.subject elif personalize_subject_first_name: email.subject = "[firstname], " + email.subject elif personalize_subject_last_name: email.subject = "[lastname], " + email.subject email.status = 1 email.status_detail = 'active' email.category = 'marketing' email.save(request.user) # action object - these 3 already included on the form: member_only, group and send_to_emails now = datetime.datetime.now() self.instance.email = email self.instance.name = email.subject self.instance.type = 'Distribution E-mail' self.instance.name = email.subject self.instance.description = '%s Electronic Newsletter: generated %s' % \ (get_setting('site', "global", "sitedisplayname"), now.strftime('%d-%b-%y %I:%M:%S %p')) self.instance.category = 'marketing' self.instance.due_dt = now try: entity = (request.user.get_profile()).entity except: entity = None if entity: self.instance.entity = entity self.instance.status = 1 self.instance.status_detail = 'open' self.instance.save(request.user) return self.instance
def hold(request): if request.method == "POST": # Grab all the data from POST requests subject = request.POST["email_subject"] unformatted_body = request.POST["email_body"] from_name = request.POST["email_from_name"] from_email = request.POST["email_from_email"].strip() # CSV IMPORTING to_name_list = [] to_email_list = [] if request.FILES != {}: csvfile = request.FILES['csv_file'] dialect = csv.Sniffer().sniff(codecs.EncodedFile(csvfile, "utf-8").read(1024)) csvfile.open() reader = csv.reader(codecs.EncodedFile(csvfile, "utf-8"), delimiter=',', dialect=dialect) for row in reader: to_name_list.append(row[0]) to_email_list.append(row[1].strip()) else: to_name_list = request.POST.getlist("email_recipients_name") to_email_list = request.POST.getlist("email_recipients_email") #TODO: QUICK HACKY FORM VALIDATION if subject == "" or unformatted_body == "" or from_name == "" or to_name_list[0] == "" or to_email_list[0] == "": return HttpResponseRedirect('/') # Format all the data and store into lists of correct emails formatted_to_email_list = [] holding_email_list = [] for i in range(len(to_name_list)): if to_name_list[i] == "" or to_email_list[i] == "": break body = unformatted_body.replace("[First]", getFirstName(to_name_list[i])) formatted_to_email_list.append(formatEmail(to_name_list[i], to_email_list[i].strip())); email = Email(from_name = from_name, from_email = from_email, to_name = to_name_list[i], to_email = to_email_list[i], subject = subject, body = body, uid = _createId(), sent = False) email.save() holding_email_list.append(email); #TODO: STOP Confirmation from happening if emails blank createConfirmationEmail(holding_email_list, from_name, from_email, formatted_to_email_list) return render_to_response('holding.html', {"count" : len(formatted_to_email_list), "to_emails" : formatted_to_email_list, "from" : getFirstName(from_name), "subject" : subject, "body" : unformatted_body}, context_instance=RequestContext(request)) return HttpResponseRedirect('/')