def sendemail(request): data = EmailSerializer(data=request.data) if data.is_valid(): username = data.validated_data['username'] email = data.validated_data['email'] verify_code = data.validated_data['verify_code'] content = data.validated_data['content'] else: return HttpResponse(data.error_messages, status=400) mail_title = "测试验证码" mail_content = content + verify_code try: # send_mail(receiver=email, mail_title=mail_title,\ # mail_content=mail_content ) send_email.delay(receiver=email, mail_title=mail_title,\ mail_content=mail_content ) status = 'succeed' except Exception as e: status = 'failure' logger.info(e) email_status = Email(email=email, username=username, verify_code=verify_code, status=status) email_status.save() return HttpResponse(json.dumps({"status": status}), content_type="application/json")
def post(self): params = register_parse.parse_args() email = params.get("email") pwd = params.get("pwd") confirm_pwd = params.get("confirm_pwd") User.query.paginate # 判断密码和确认密码是否一致 if pwd != confirm_pwd: return {"code": 2, "msg": "密码和确认密码不一致"} res = User.creat_user(email=email, pwd=pwd) # 给你发个邮件 让你激活 url = "http://" + request.host + "/active/" + create_unique_str() print(url) if res: send_email.delay(email, url, res.id, mail, cache) # msg = Message("欢迎注册爱鲜蜂后台管理", # [email], # sender="*****@*****.**" # ) # msg.html = render_template("active.html", url=url) # mail.send(msg) key = url.split("/")[-1] cache.set(key, res.id, timeout=60*60) return {"data": "/index"} else: return {"code": 3, "msg": "注册失败"}
def reset_password(): email = '*****@*****.**' toemail = '*****@*****.**' subject = 'test' content = 'test' send_email.delay(email, toemail, subject, content) return json.dumps({'code': 0})
def done(self, form_list, form_dict, **kwargs): with transaction.atomic(): user_data = form_dict['user'].cleaned_data phone_number = user_data['country_code'] + user_data['phone_number'] email = user_data['email'] username = user_data['username'] user = form_dict['user'].save() salt = hashlib.sha1(str(random.random())).hexdigest()[:5] activation_key = hashlib.sha1(salt + email).hexdigest() key_expires = timezone.now() + timedelta(days=30) user_profile = UserProfile(user=user, phone_number=phone_number, activation_key=activation_key, key_expires=key_expires) user_profile.save() email_subject = 'Account Confirmation' confirmation_url = self.request.build_absolute_uri( reverse('email_confirm', kwargs={'activation_key': activation_key})) email_body = "Hello %s, thanks for signing up. To activate your account,\ click this link %s" % (username, confirmation_url) send_email.delay(email_subject, email_body, [email]) messages.success( self.request, "You've successfully signed up. Please click the activation link sent to your email to activate your account" ) return HttpResponseRedirect('/')
def subscribe(course_id, user_id): logger.debug("Logger I'm in subscribe") try: course = Course.objects.get(id=course_id) user = User.objects.get(id=user_id) if not UserCourse.objects.filter(deleted=False).filter(course=course).filter(user=user).exclude(status='ended').exists(): if course.price == 0: usercourse_new = UserCourse(course=course, user=user, status='active') context = {"course": course} email_message = render_to_string('email/email_subscribe_course_free.html', context) # email_message = Engine().from_string('email/email_subscribe_course_free.html').render(context) else: usercourse_new = UserCourse(course=course, user=user, status='begin') context = {"course": course, "user": user} email_message = render_to_string('email/email_subscribe_course_paid.html', context) # email_message = Engine().from_string('email/email_subscribe_course_paid.html').render(context) from tasks import send_email send_email.delay( EMAIL_SUBJECT=u"Поздравляем с подпиской на курс: '%s'." % course.name, EMAIL_EMAIL_FROM=u'Карманный Психолог <*****@*****.**>', EMAIL_EMAIL_TO=user.email, HTML_EMAIL_MESSAGE=email_message ) usercourse_new.save() return True except Exception, e: print e
def done(self, form_list, form_dict, **kwargs): with transaction.atomic(): user_data = form_dict["user"].cleaned_data phone_number = user_data["country_code"] + user_data["phone_number"] email = user_data["email"] username = user_data["username"] user = form_dict["user"].save() salt = hashlib.sha1(str(random.random())).hexdigest()[:5] activation_key = hashlib.sha1(salt + email).hexdigest() key_expires = timezone.now() + timedelta(days=30) user_profile = UserProfile( user=user, phone_number=phone_number, activation_key=activation_key, key_expires=key_expires ) user_profile.save() email_subject = "Account Confirmation" confirmation_url = self.request.build_absolute_uri( reverse("email_confirm", kwargs={"activation_key": activation_key}) ) email_body = ( "Hello %s, thanks for signing up. To activate your account,\ click this link %s" % (username, confirmation_url) ) send_email.delay(email_subject, email_body, [email]) messages.success( self.request, "You've successfully signed up. Please click the activation link sent to your email to activate your account", ) return HttpResponseRedirect("/")
def mail(): # app=current_app._get_current_object() # mail = current_app.extensions['mail'] # msg = Message(subject='Email test by flask-email', sender="*****@*****.**", # recipients=['*****@*****.**']) # msg.body = 'hello test' # msg.html = '<b>测试Flask发送邮件<b>' # mail.send(msg) send_email.delay('*****@*****.**', "新的标题2", "新的信息2") return 'ok'
def send_messages(self, email_message): from_email = sanitize_address(email_message.from_email, email_message.encoding) recipients = [sanitize_address(addr, email_message.encoding) for addr in email_message.recipients()] try: send_email.delay(email_message.subject, email_message.message, from_email, recipients) except: if not self.fail_silently: raise
def post(self): forms = Email(request.form) username = g.user.username if forms.validate(): code = self.get_random_str() send_email.delay(e=forms.data['mail'], code=code) client.set(username, code, time=360) return jsonify({'error': True, 'message': '邮件发送成功'}) else: message = email.errors return jsonify({'error': False, 'message': message})
def post_report_save(sender, raw, **kwargs): created = kwargs.get("created", False) raw = kwargs.get("raw", False) if created and not raw: inst = kwargs["instance"] email_to = inst.template.email_to.exists() if email_to: inst_id = inst.id # This is until we get the pdf generation fixed. # from tasks import generate_pdf, send_email # res = (generate_pdf.si(inst_id) | send_email.si(inst_id))() from tasks import send_email send_email.delay(inst_id)
def send_messages(self, email_message): from_email = sanitize_address(email_message.from_email, email_message.encoding) recipients = [ sanitize_address(addr, email_message.encoding) for addr in email_message.recipients() ] try: send_email.delay(email_message.subject, email_message.message, from_email, recipients) except: if not self.fail_silently: raise
def send_message(sender, recipients, subject, body_text, body_html, attachments=None, ccs=None, bccs=None, categories=None, send=True): mail = sgh.Mail() mail.from_email = sgh.Email(sender.email, sender.name) mail.subject = subject for recipient in recipients: personalization = sgh.Personalization() personalization.add_to(sgh.Email(recipient.email, recipient.name)) if ccs: for cc in ccs: personalization.add_cc(sgh.Email(cc.email)) if bccs: for bcc in bccs: personalization.add_bcc(sgh.Email(bcc.email)) mail.add_personalization(personalization) mail.add_content(sgh.Content("text/plain", body_text)) mail.add_content(sgh.Content("text/html", body_html)) if attachments: for attach in attachments: attachment = sgh.Attachment() attachment.set_content(attach.content) attachment.set_type(attach.type) attachment.set_filename(attach.filename) attachment.set_disposition(attach.disposition) attachment.set_content_id(attach.content_id) mail.add_attachment(attachment) if categories: for category in categories: mail.add_category(sgh.Category(category)) if send: if os.environ.get('REDIS_URL') is not None: send_email.delay(body=mail.get()) else: import sendgrid sg_api = sendgrid.SendGridAPIClient( apikey=constants.SENDGRID_API_KEY) return sg_api.client.mail.send.post(request_body=mail.get())
def done(self, form_list, form_dict, **kwargs): with transaction.atomic(): user_data = form_dict['user'].cleaned_data phone_number = user_data['country_code'] + user_data['phone_number'] email = user_data['email'] username = user_data['username'] user = form_dict['user'].save() salt = hashlib.sha1(str(random.random())).hexdigest()[:5] activation_key = hashlib.sha1(salt+email).hexdigest() key_expires = timezone.now() + timedelta(days=30) user_profile = UserProfile(user=user, phone=phone_number, role='job_seeker', activation_key=activation_key, key_expires=key_expires) user_profile.save() email_subject = 'Account Confirmation' confirmation_url = self.request.build_absolute_uri(reverse('email_confirm', kwargs={'activation_key': activation_key})) email_body = "Hello %s, thanks for signing up. To activate your account,\ click this link %s" % (username, confirmation_url) send_email.delay(email_subject, email_body, [email]) seeker_data = form_dict['job_seeker_profile'].cleaned_data jobseekerprofile = JobSeeker(user=user, category=seeker_data['category'], summary=seeker_data['summary'], years_of_experience=seeker_data['years_of_experience']) jobseekerprofile.save() for skill in seeker_data['skills']: jobskill = JobSeekerSkill(seeker=jobseekerprofile, skill=skill) jobskill.save() match_candidate.delay(jobseekerprofile.id) messages.success(self.request, "You've successfully signed up. Please click the activation link sent to your email to activate your account") return HttpResponseRedirect('/')
def post(self, request, *args, **kwargs): """ A normal post request which takes input from field "email_or_username" (in ResetPasswordRequestForm). """ context = {'error': 'None'} form = self.form_class(request.POST) if form.is_valid(): data = form.cleaned_data["email_or_username"] if self.validate_email_address(data) is True: #uses the method written above ''' If the input is an valid email address, then the following code will lookup for users associated with that email address. If found then an email will be sent to the address, else an error message will be printed on the screen. ''' associated_users = User.objects.filter(Q(email=data) | Q(username=data)) if associated_users.exists(): for user in associated_users: c = { 'email': user.email, 'domain': request.META['HTTP_HOST'], 'site_name': 'EQ', 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'user': user, 'token': default_token_generator.make_token(user), 'protocol': 'http', } email_template_name ='account/password_reset_email.html' email = loader.render_to_string(email_template_name, c) send_email.delay( EMAIL_SUBJECT=u'EQ: восстановление пароля', EMAIL_EMAIL_FROM=u'Карманный Психолог <*****@*****.**>', EMAIL_EMAIL_TO=user.email, EMAIL_MESSAGE=email ) context['success'] = u'E-mail был отправлен ' + data + u". Пожалуйста, проверьте его почтовый ящик для продолжения сброса пароля." return JsonResponse(context) context['error'] = u'Ни один пользователь не связан с этим адресом электронной почты' return JsonResponse(context) context['error'] = 'Invalid Input' return JsonResponse(context)
def dashboard(request): user = request.user if request.method == 'GET': my_user = MyUser.objects.get(user=user) context = { 'username' : user.username, 'email' : user.email, 'sections' : my_user.sections.all() } return render(request, 'dashboard.html', context) elif request.method == 'POST': my_user = MyUser.objects.get(user=user) param = request.POST crn = param.get('crn') term = param.get('term') restrict = param.get('send_restrict') if not term: term = settings.CURRENT_TERM else: term = convert_term_to_code(term) context = { 'email' : user.email, 'sections' : my_user.sections.all(), 'error' : '', } try: sec = my_user.add_section(crn, term, restrict) if sec: msg = "You successfully subscribe section:%s \n" % sec try: send_email.delay([my_user.user.email,], msg) except ImportError as e: pass #send_email([my_user.user.email,], msg) except ParserException as e: context['error'] = e.message return render(request, 'dashboard.html', context) return render(request, 'dashboard.html', context)
def post(self, request, uidb64=None, token=None, *arg, **kwargs): """ View that checks the hash in a password reset link and presents a form for entering a new password. """ form = self.form_class(request.POST) assert uidb64 is not None and token is not None # checked by URLconf try: uid = urlsafe_base64_decode(uidb64) user = User.objects.get(pk=uid) except (TypeError, ValueError, OverflowError, User.DoesNotExist): user = None if user is not None and default_token_generator.check_token(user, token): if form.is_valid(): new_password = form.cleaned_data['new_password2'] user.set_password(new_password) user.save() messages.success(request, u'Пароль был сброшен.') email_template_name = 'email/password_changed.html' c = { 'user': user } email = loader.render_to_string(email_template_name, c) send_email.delay( EMAIL_SUBJECT=u'EQ: изменение пароля', EMAIL_EMAIL_FROM=u'Карманный Психолог <*****@*****.**>', EMAIL_EMAIL_TO=user.email, HTML_EMAIL_MESSAGE=email ) return self.form_valid(form) else: messages.error(request, u'Восстановление пароля не увенчались успехом.') return self.form_invalid(form) else: messages.error(request, u'Ссылка для изменения пароля больше не действительна.') return self.form_invalid(form)
def done(self, form_list, form_dict, **kwargs): with transaction.atomic(): user_data = form_dict['user'].cleaned_data phone_number = user_data['country_code'] + user_data['phone_number'] email = user_data['email'] username = user_data['username'] user = form_dict['user'].save() salt = hashlib.sha1(str(random.random())).hexdigest()[:5] activation_key = hashlib.sha1(salt+email).hexdigest() key_expires = timezone.now() + timedelta(days=30) user_profile = UserProfile(user=user, phone=phone_number, role='employer', activation_key=activation_key, key_expires=key_expires) user_profile.save() email_subject = 'Account Confirmation' confirmation_url = self.request.build_absolute_uri(reverse('email_confirm', kwargs={'activation_key': activation_key})) email_body = "Hello %s, thanks for signing up. To activate your account,\ click this link %s" % (username, confirmation_url) send_email.delay(email_subject, email_body, [email]) profile_data = form_dict['company_profile'].cleaned_data employer = Employer(user=user, company=profile_data['company_name'], description=profile_data['description'], location=profile_data['location'], address=profile_data['address']) employer.save() messages.success(self.request, "You've successfully signed up. Please click the activation link sent to your email to activate your account") return HttpResponseRedirect('/')
def email_captcha(): form = EmailCaptchaForm(request.form) if form.validate(): email = form.email.data # 产生随机验证码 # string.ascii_letters -- > 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' # source 是26个大小写英文字母加上10个数字,验证码随机从这中间取得6位 source = list(string.ascii_letters) source.extend(['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']) # random.sample(source, 6) --> [x,x,x,x,x,x] 需要用''.join转化成字符串 captcha = ''.join(random.sample(source, 6)) # message = Message(subject='Blog password email captcha', recipients=[email], # body='[My Blog] Your captcha is %s' % captcha) # try: # mail.send(message) # except: # return restful.server_error() send_email.delay(subject='Blog password email captcha', recipients=email, body='[My Blog] Your captcha is %s' % captcha) blogcache.set(email, captcha) return restful.success() else: return restful.params_error(message='Params error!')
def send_messages(self, email_messages, **kwargs): ''' Django Email Backend API - send_messages :param email_messages: list of django.core.mail.messages.EmailMessage instance - This implementation delegates STMP task to Celery worker. ''' logger.debug(_('PalomaEmailBackend is used to send a message.')) from tasks import send_email results = [] for msg in email_messages: results.append(send_email.delay(msg, **kwargs)) # asynchronous send_email return results
from tasks import send_email if __name__ == '__main__': send_email.delay()
# coding=utf-8 from tasks import send_email, add print("my other codes are here.") send_email.delay(dict(to='*****@*****.**')) result = add.delay(10, 25) print(result.status) # he ready() method returns whether the task has finished processing or not: print(result.ready()) result.get() print(result.ready()) # You can wait for the result to complete, # but this is rarely used since it turns the asynchronous call into a synchronous one: # result.get(timeout=3) # import time # from tasks import send_email, add # print(send_email.delay(dict(to='*****@*****.**'))) # answer = send_email.delay(dict(to='*****@*****.**')) # while 1: # print('wait for ready') # if answer.ready(): # break
def hello_world(): send_email.delay("*****@*****.**", 'hello world') return 'Hello World!%s' % (app.config['MAIL_USERNAME'])