def contact(): if request.method == 'POST': if request.form['url1'] != "": return render_template('contact.html') #it's a bot! data_surname = request.form['surname'] data_lastname = request.form['lastname'] data_email = request.form['email'] data_querytype = request.form['querytype'] data_querytype = category[data_querytype] data_details = request.form['details'] new_dataset = Dataset(surname=data_surname, lastname=data_lastname, email=data_email, querytype=data_querytype, details=data_details) msg = Message(subject=data_surname + ": " + data_querytype + " - carmenphotography.ch", sender=app.config.get("MAIL_USERNAME"), recipients=[mail_recipients[0]], # replace with your email for testing html="\ <h3>Anfrage: "+ data_querytype +"</h3>\ <p>von: "+ data_surname + " " + data_lastname + "</p>\ <p>"+ data_details +"</p>\ <p>"+ data_email +"</p>\ ") msg.add_recipient(mail_recipients[1]) try: db.session.add(new_dataset) db.session.commit() mail.send(msg) return redirect('/thanks/') except: app.logger.warning(traceback.format_exc()) return 'There was an issue to add your request. Please try again.' else: return render_template('contact.html')
def ForgotPassword(): try: if request.method == 'POST': form = request.form if not form['email']: flash("You must enter email","error") return render_template("ForgotPassword.html") usuario = USUARIOS.find_by_email(form['email']) token = PASSWORD_RESET_TOKENS(usuario.id_usuario) if token.Add(): try: msg = Message("Reset password", sender=("Noreply", "*****@*****.**")) msg.add_recipient(usuario.email) msg.html = render_template('Email/ResetPassword.html', \ nombre = usuario.nombre, \ app_name = app.config['APP_NAME'], \ host = app.config['HOSTNAME_NAME'], \ token = token.Token) mail.send(msg) flash("Email successfully sent, check your mailbox.","success") except: flash("Error sending email, please wait and try again.","error") else: flash("Error sending email, please wait and try again.","error") return render_template("ForgotPassword.html") except: e = sys.exc_info() Log("An error {} has occurred in ForgotPassword".format(e)) flash("Error sending email to reset username and password.","error") return render_template("ForgotPassword.html") return render_template("ForgotPassword.html")
def index(): msg = Message('Peace be upon you,', recipients=['*****@*****.**']) msg.add_recipient('*****@*****.**') # msg.body='This one is just example mail to remind you about upcoming session. If you know just ignore' msg.html = '<b>SOme more blah blah text that is supposedly formated to be bold</b>' with app.open_resource('cat.jpg') as cat: msg.attach('cat.jpg', 'image/jpeg', cat.read()) mail.send(msg) msg = Message(subject='', recipients=[], body='', html='', sender='', cc=[], bcc=[], attachments=[], reply_to=[], date='date', charset='', extra_headers={'': ''}, mail_options=[], rcpt_options=[]) return 'Message has been sent!'
def send_update_email(university=None, body="", subject="Confirm update to University API"): msg = Message(subject) msg.add_recipient( os.getenv("MAIL_DEFAULT_RECEIVER", "*****@*****.**")) if body: msg.body = body else: msg.body = """The following information has been provided to be updated in the university database: University Name: university-name Country: university-country Website: university-webpage Domain: university-domain Please verify the information provided above. To confirm update, click: {url_for('university_api.confirm_update', university=university, _external=True)} """ try: mail.send(msg) except Exception as e: current_app.logger.error(print(e))
def post(self): """ Method to ask for a Password recovery :return: """ # Entries try: email = api.payload['email'] except: raise ParameterException('email') # if the user is not existing, we return a standard error if User.get_by_email(email) is None: return { "message": 'request for recovery successful' } # mail creation user = User.query.filter_by(email=email).first() link = constants.CLIENT_URL + "/recover;token_recover=" + generate_confirmation_token(email) msg = Message() msg.add_recipient(email) msg.subject = 'Password recovery for the HotMaps toolbox' msg.body = 'Hello ' + user.first_name + ' ' + user.last_name + ' you asked for a password recovery ' \ 'on your HotMaps account,\n to reset your password, please click on the following link: ' \ '\n' + link + '\n if you haven\'t ask for this modification, please delete this email.' try: mail.send(msg) except Exception as e: raise RequestException(str(e)) output = 'request for recovery successful' # output return { "message": output }
def send_user_resetlink(user_id, email=None, expiry=86400): if email is None: db = get_db() rc = db.execute( 'SELECT * FROM user WHERE id=? AND email IS NOT NULL AND disabled=0', (user_id, )).fetchone() if rc is not None: email = rc['email'] else: return None # Create a password reset link url = create_password_reset_link(user_id) # Create an email mail = get_mail() server_name = current_app.config['HISTOANNOT_PUBLIC_NAME'] msg = Message("Password Reset Link for %s" % (server_name, )) msg.add_recipient(email) msg.html = """ <p>You have requested a link to reset your password on %s.</p> <p>Please follow this link to reset the password for user <b>%s</b>:</p> <a href="%s">%s</a> """ % (server_name, rc['username'], url, url) mail.send(msg)
def test_sendto_properly_set(self): msg = Message( subject="subject", recipients=["*****@*****.**"], cc=["*****@*****.**"], bcc=["*****@*****.**"] ) self.assertEqual(len(msg.send_to), 3) msg.add_recipient("*****@*****.**") self.assertEqual(len(msg.send_to), 3)
def index(): theEmailForm = emailForm(request.form) if (request.method == 'POST'): if (request.form['type'] == "img"): files = request.files['file'] filename = secure_filename(files.filename) files.save( os.path.join( os.path.join(os.path.dirname(os.path.abspath(__file__)), 'static/img'), 'GT_logo.png')) src = os.path.join( os.path.join(os.path.dirname(os.path.abspath(__file__)), 'static/img'), 'GT_logo.png') dst = os.path.join( os.path.join( os.path.dirname(os.path.dirname( os.path.abspath(__file__))), 'website/static/img'), 'GT_logo.png') shutil.copyfile(src, dst) #the previous line will need to be calibrated on deploy else: msg = Message('expo.gatech.edu Contact Form', recipients=['*****@*****.**']) msg.add_recipient("*****@*****.**") msg.body = "Name: " + theEmailForm.name.data + "\n Email:" + \ theEmailForm.email.data + "\n\n" + theEmailForm.message.data mail.send(msg) return render_template('index.html', pageName="Index", emailForm=emailForm())
class EmailService(): def __init__(self): self.message = Message() def set_subject(self, subject): self.message.subject = subject return self def set_body(self, body): self.message.body = body return self def set_html(self, body): self.message.html = body return self def set_sender(self, sender): self.message.sender = sender return self def set_recipient(self, recipient): self.message.add_recipient(recipient) return self def set_recipients(self, recipients): self.message = recipients return self def build(self): return self.message
def send_mail(event_id, recipients): """ Sends an send_email asynchronously using flask rq-scheduler Args: event_id (Event.id) : Event ID Returns: None Todo: still manually passing recipients value to function, cause can't load from db yet. This function should be just passing event ID. """ event = Event.query.get(event_id) msg = Message(subject=event.email_subject) for addr_ in recipients: msg.add_recipient(addr_) with mail.connect() as conn: """If email content has HTML code, it will send as HTML. If it just text, it will be send as email body. """ if (BeautifulSoup(event.email_content, 'html.parser').find()): msg.html = event.email_content else: msg.body = event.email_content conn.send(msg) event.is_done = True event.done_at = datetime.utcnow() done_at = event.done_at db.session.add(event) db.session.commit() return "Success. Done at {}".format(done_at)
def send_naggy_email(mail, email_address, github_username): print("Processing @%s" % github_username) to_review = [] for pull_request in PullRequest.by_requested_reviewer(github_username): my_state = pull_request.state_for_user(github_username) if my_state.state not in ("haircut", "unreviewed"): continue to_review.append(my_state) my_pulls = [] for pull_request in PullRequest.by_author(github_username): review_stage = pull_request.review_stage() if review_stage not in ("fish", "eyeglasses", "nail_care"): continue my_pulls.append(pull_request) if not to_review and not my_pulls: return print("- Sending nag to %r" % email_address) date = datetime.date.today().strftime("%b %d") message = Message() message.sender = u"Harold \U0001F487 <*****@*****.**>" message.subject = u"Outstanding pull requests for %s" % (date, ) message.html = render_template( "email.html", username=github_username, to_review=to_review, my_pulls=my_pulls, ) message.add_recipient(email_address) mail.send(message)
def ignoreReported(sid): post = Reported.query.filter_by(id=sid).first() if post is None: flash('This post has already been handled.', 'info') return redirect(url_for('adminReported')) email = post.email print(email) # parse the email by spliting the email with the colon separator emailList = email.split("::") db.session.delete(post) db.session.flush() db.session.commit() message = 'Report of #' + str(sid) + ' has been ignored.' flash(message) if email is not None: msg = Message('Hello from Purdue Secrets!', sender='*****@*****.**') for i in emailList: msg.add_recipient(i) msg.body = """We are sending this email to inform that your post has been reported by other users and after the examinations from the admins, we decided to keep your post on the wall""" mail.send(msg) return redirect(url_for('adminReported'))
def signup(): if request.method == 'POST': try: #add the user to database newUser = User( request.form['inputEmail'], generate_password_hash(request.form['inputPassword']), request.form['inputName'], datetime(2001, 01, 01), "") db.session.add(newUser) db.session.commit() #generate confirmation link, code:email+hash of email+name confirmation_link = app.config[ 'DOMAIN'] + 'confirmemail?email=' + request.form[ 'inputEmail'] + '&code=' + hashlib.md5( request.form['inputEmail'] + request.form['inputName']).hexdigest() #send email msg = Message("Welcome to better app", sender=app.config['DEFAULT_MAIL_SENDER']) msg.add_recipient(request.form['inputEmail']) msg.body = 'Welcome to the app! Please go to this address to confirm your email: {0}'.format( confirmation_link) mail.send(msg) return render_template( 'signup.html', message=gettext( 'Signed up, please check email for confirmation link!')) except Exception, e: print str(e) return render_template('signup.html', message=gettext('Error, please try again!'))
def send_email(): captcha = FlaskSessionCaptcha(app) cform = ContactForm(request.values) tmpl = tmpl_picker('contact') reply = tmpl_picker('autoreply') if request.method == 'POST': if cform.validate_on_submit(): if captcha.validate(): try: mail = Mail(app) msg = Message(">>> message from SciBook: " + cform.data["subject"], sender=cform.data["email"], recipients=[app.config["EMAIL_1"]]) msg.add_recipient(app.config["EMAIL_2"]) msg.body = cform.data["msg"] + "\n\n" + "signed as from:\n" + cform.data["email"] mail.send(msg) flash("Your message is sent!", category='info') return render_template(reply, form=g.form, cform=cform) except: flash("Your message is not sent fast way... Something went wrong, we are soory, but we look at your message a bit later", category='error') return render_template(reply, form=g.form, cform=cform) else: flash("Captcha is wrong!", category='error') return render_template(tmpl, form=g.form, cform=cform, email=cform.data["email"], subject=cform.data["subject"], msg=cform.data["msg"], topics=g.topics) else: flash("All fields are necessary to fill in!", category='error') return render_template(tmpl, form=g.form, cform=cform, email=cform.data["email"], subject=cform.data["subject"], msg=cform.data["msg"], topics=g.topics) else: return render_template(tmpl, form=g.form, cform=cform, topics=g.topics)
def send_mail(): try: msg = Message( 'Invoice form 2J-ART Ltd.', sender='*****@*****.**', recipients=[ User.query.filter_by(id=int(session['userId'])).first().email ]) msg.add_recipient("*****@*****.**") msg.body = "If you can't read this email please contact us." msg.html = render_template( 'example1.html', invoiceData=session['invoiceData'], user=User.query.filter_by(id=int(session['userId'])).first(), salon=Salon.query.filter_by(id=int(session['salonId'])).first(), invoiceId=session['invoiceId'], date=session['date'], serviceList=session['serviceList'], total=session['total']) mail.send(msg) msg.subject = 'COPY of Invoice form 2J-ART Ltd.' msg.recipients = ['*****@*****.**'] mail.send(msg) except Exception as e: return str(e) new_invoice = Invoices() db.session.add(new_invoice) db.session.commit() return redirect(url_for('index'))
def index(): if request.method == 'GET': return render_template('index.html', form={}, errors={}, mixpanel_token=mixpanel_token()) form = request.form errors = {} if not form['email']: errors['email'] = strings.ERROR_NO_EMAIL_TO_GET_AHOLD if not form['report']: errors['report'] = strings.ERROR_NO_REPORT if not errors: subject = strings.SUBJ_REPORT msg = Message(subject) msg.add_recipient(email_address(config.CONTACT_EMAIL)) msg.html = render_template('mail/report.html', form=form) msg.body = render_template('mail/report.txt', form=form) mail.send(msg) flash(strings.SUCCESS_REPORT_SUBMITTED, 'success') return redirect(url_for('index')) flash(strings.ERROR_NOT_SUBMITTED, 'danger') return render_template('index.html', form=form, errors=errors, mixpanel_token=mixpanel_token())
def submit(): if (request.method == 'POST'): about = request.form.get("about") recipient = '*****@*****.**' enquiry = { 1: "General Enquiry", 2: "Come & Try", 3: "Beginner's course" } body = [] first = request.form.get("form-first-name") last = request.form.get("form-last-name") email = request.form.get("form-email") size = request.form.get("size") #age check for beginner's course info = request.form.get("info") body.append("Contact Name: %s %s" % (first, last)) body.append("Email: %s" % (email)) if (int(about) > 1): body.append("Group Size: %s" % (size)) body.append("Enquiry Details:") body.append(info) msg = Message(enquiry.get(int(about))) msg.add_recipient(recipient) msg.body = "\r\n".join(body) mail.send(msg) return render_template('contact.html')
def send_reset_password_mail(user_email, request): user = User().load({'email': user_email}) if user.id: msg = Message() msg.add_recipient(user_email) minutes = 30 token = User.encode_auth_token(user.id, days=0, seconds=0, minutes=minutes).decode() link = f'http://{request.host}/reset/{token}' msg.html = get_reset_password_html( username=f"{user.first_name} {user.last_name}", link=link, minutes=minutes, token=token) msg.subject = 'Reset Password Request' msg.sender = '*****@*****.**' mail.send(msg) response_object = { 'status': 'success', 'message': 'An email with a reset was sent link.', } return response_object, 200 else: response_object = { 'status': 'fail', 'message': 'User provided email does not exist.', } return response_object, 409
def RdRequirement(): creater = session.get('username') """多个项目会分割会在数据库中分割成多条记录,通过时间戳来判断是同一个工单""" RdProject = request.form['rdproject'] RdErrlogPath = request.form['rderrlogpath'] RdLogPath = request.form['rdlogpath'] RdHostIp = request.form['rdhostip'] RdNotify = request.form['rdnotify'] """下面会得到一个十三位的时间戳,会根据这个时间戳到时候计算是否是属于同一个工单""" """RdTime = int(round(time.time() * 1000))""" rdmysql.rd_mysql.InserInto(creater=creater, project=RdProject, errlogpath=RdErrlogPath, logpath=RdLogPath, hostip=RdHostIp, notify=RdNotify) """记录日志""" loginfo.logger.info("rd需求单记录" + " " + "项目名:" + RdProject + "/ " + "错误日志路径:" + RdErrlogPath + "/ " + "api日志路径:" + RdLogPath + "/ " + "在哪些主机上:" + RdHostIp + "/ " + "需要通知的人:" + RdNotify) """邮件服务""" msg = Message("Bdg_agent_Rd新需求单", recipients=["*****@*****.**"]) msg.add_recipient("bdg-agent.baijiahulian.com") msg.body = "rd需求单记录" + " " + "项目名:" + RdProject + "/ " + "错误日志路径:" + RdErrlogPath + "/ " + "api日志路径:" + RdLogPath + "/ " + "在哪些主机上:" + RdHostIp + "/ " + "需要通知的人:" + RdNotify + " " + "详情请到工单系统中查询" """异步发邮件""" thr = threading.Thread(target=send_async_email, args=[app, msg]) thr.start() return jsonify({"code": 200, "message": "已经邮件通知业务方"})
def post(self): """ Method to ask for a Password recovery :return: """ # Entries try: email = api.payload['email'] except: raise ParameterException('email') # if the user is not existing, we return a standard error if User.get_by_email(email) is None: return {"message": 'request for recovery successful'} # mail creation user = User.query.filter_by(email=email).first() link = constants.CLIENT_URL + "/recover;token_recover=" + generate_confirmation_token( email) msg = Message() msg.add_recipient(email) msg.subject = 'Password recovery for the HotMaps toolbox' msg.body = 'Hello ' + user.first_name + ' ' + user.last_name + ' you asked for a password recovery ' \ 'on your HotMaps account,\n to reset your password, please click on the following link: ' \ '\n' + link + '\n if you haven\'t ask for this modification, please delete this email.' try: mail.send(msg) except Exception as e: raise RequestException(str(e)) output = 'request for recovery successful' # output return {"message": output}
def store(): try: name = request.json['name'] email = request.json['email'] password = request.json['password'] users = Users(name=name, email=email) users.setPassword(password) db.session.add(users) db.session.commit() msg = Message("Hello, {} welcome to Belajar Flask Python".format(name), sender="*****@*****.**") msg.add_recipient(email) # msg.body = "testing" msg.html = render_template('mail.html', app_name="Learn Flask with Kiddy", app_contact="*****@*****.**", name=name, email=email) mail.send(msg) return response.ok('', 'Successfully create data!') except Exception as e: print(e)
def readCsv(): if request.method == 'POST': # Get uploaded file f = request.files['myFile'] # Convert the uploaded file into Stream stream = io.StringIO(f.stream.read().decode("UTF8"), newline=None) # csv_rows = list(csv.reader(stream, delimiter=",")) csvlist = [] csvreader = csv.reader(stream) for row in csvreader: csvlist.append(row) csvlist = csvlist[1:] emails = [] names = [] # Split emails and names from CSV file for i in range(len(csvlist)): emails.append(csvlist[i][0]) names.append(csvlist[i][1]) # Only this part is remaining for i in range(len(names)): msg = Message('Test Emails From Flask', sender='*****@*****.**') msg.body = generateMessage(names[i]) msg.add_recipient(emails[i]) mail.send(msg) # print(msg.recipients) return ''
def submit_payment(): pform = PaymentForm() pform.uid.choices = User.get_uids() if not pform.validate_on_submit(): flash('Payment invalid.') return redirect(url_for('coffee.admin')) uid = pform.uid.data amount = float(pform.amount.data) * 100 user = User.objects.get(id=uid) transaction = Transaction(user=user, diff=amount, description='{} payment from {}'.format( euros(amount), user.name)) transaction.save() if user.email: msg = Message('[Kaffeeministerium] Einzahlung von {}'.format( euros(amount))) msg.charset = 'utf-8' msg.add_recipient(user.email) msg.body = render_template('mail/payment', amount=amount, balance=user.balance) flash('Mail sent to user {}'.format(user.name)) if not app.config['DEBUG']: mail.send(msg) else: print(u'Sending mail \n{}'.format(msg.as_string())) return redirect(url_for('coffee.admin'))
def send_action(cipher_iv, ciphertext, hmac): fields = app.config.get_namespace('HERMOD_FIELDS_') form = request.form.copy() address = crypto.decrypt(cipher_iv, ciphertext) redirect_to = form.pop(fields.get('redirect'), default=request.referrer) honeypot = form.pop(fields.get('honeypot'), default=None) if honeypot != '': return render_template('response.html', error='Content tampered'), 403 domain = urlparse(redirect_to).netloc if domain is None: domain = urlparse(request.referrer).netloc digest = signature(address, domain) if not crypto.verify(digest, hmac): return render_template('response.html', error='Content tampered'), 403 message = { 'origin': request.referrer, 'sender': form.pop(fields.get('name'), default=None), 'address': form.pop(fields.get('from'), default=None), 'administrator': app.config.get('HERMOD_ADMIN_EMAIL'), 'fields': form } if message['address'] is None: return render_template( 'response.html', error='A required field is missing: your email address'), 400 if '@' not in message['address']: return render_template( 'response.html', error='A required field is invalid: your email address'), 400 msg = Message('New message via Hermód') msg.add_recipient(address) if message['sender'] is not None: msg.reply_to = (message['sender'], message['address']) else: msg.reply_to = message['address'] msg.html = render_template('mail.html', message=message) text = 'Received message from {sender} <{address}> via {origin}'.format_map( message) text += ' to {0}'.format(address) app.logger.info(text) try: mail.send(msg) except ConnectionError as e: app.logger.error( "Connection error: {e.errno} {e.strerror}".format(e=e)) except SMTPResponseException as e: app.logger.error( "SMTP error: {e.smtp_code} {e.smtp_error}".format(e=e)) return redirect(redirect_to)
def index(): print("Add user") global move_id move_id += 1 global ttt_props print("Finding request method") if request.method == 'POST': print("POST request") # Gather the details and add to users DB form = request.json print(request.json) if not 'username' in form: print("Bad form formatting") return jsonify({"status": "OK"}) name = form['username'] print("Obtained name") ttt_props['name'] = name print("Now let's get the email") mail_addr = form['email'] print(name + " " + mail_addr) userinfo = { 'username': name, 'password': form['password'], 'email': mail_addr } print(userinfo) users.insert_one(userinfo) print("Inserted user into users collection") # Send the message msg = Message("Tic-Tac-Toe Registration", sender="*****@*****.**") key = "abracadabra" # temporary string until we can generate something random msg.body = "The key is: " + key msg.add_recipient(mail_addr) mail.send(msg) # Get the email-key pair and add it to the keys DB keypair = {'email': mail_addr, 'key': key} keys.insert_one(keypair) print("Inserted key into keys collection") # return redirect print("Redirecting to verify page") redirect('/verify', code=200) return jsonify({"status": "OK"}) #return redirect("/verify", code=302) else: print("Add user GET request") props_clear() ttt_grid = json.dumps(ttt_props) return render_template('hw1.html', name=None, winner=None, email=None, board=ttt_grid, getupdate=False, id=move_id)
def test_sendto_properly_set(self): msg = Message(subject="subject", recipients=["*****@*****.**"], cc=["*****@*****.**"], bcc=["*****@*****.**"]) self.assertEqual(len(msg.send_to), 3) msg.add_recipient("*****@*****.**") self.assertEqual(len(msg.send_to), 3)
def send_mail(): app.logger.warning('sample message') msg = Message("halloo", sender="*****@*****.**") msg.add_recipient("*****@*****.**") msg.body = "testing" msg.html = "<b>testing</b>" mail.send(msg) return render_template('index.html')
def test_recipients_properly_initialized(self): msg = Message(subject="subject") self.assertEqual(msg.recipients, []) msg2 = Message(subject="subject") msg2.add_recipient("*****@*****.**") self.assertEqual(len(msg2.recipients), 1)
def send_mail_with_token(email, token): '''Send email with the confirmation token''' msg = Message() msg.add_recipient( email ) msg.subject = 'Account Verification' msg.sender = "Pig Latin <*****@*****.**>" msg.body = 'Token Verification: ' + token mail.send( msg )
def send_email(username, email, message, subject): """Metodo para la generacion y envio de emails""" msg = Message(subject, sender=app.config['MAIL_USERNAME'], recipients=[email, ]) msg.add_recipient('*****@*****.**') msg.html = render_template('mail.html', user=username, message=message) mail.send(msg)
def warning_mail(user): msg = Message(u"[Kaffeeministerium] Geringes Guthaben!") msg.charset = 'utf-8' msg.add_recipient(user.email) msg.body = render_template('mail/lowbudget', balance=euros(user.balance)) if not app.config['DEBUG']: mail.send(msg) else: print(u'Sending mail \n{}'.format(unicode(msg.as_string(), 'utf-8')))
def send_reset_email(user): token = user.get_reset_token() msg = Message('Password Reset Request') msg.add_recipient(user.email) msg.body = ' To reset your password, visit the following link: ' + url_for( 'users.reset_token', token=token, _external=True ) + ' if you did not make this request then simply ignore this email and no change ' mail.send(msg)
def send_email(conn, rec): msg = Message(rec.job.subject, sender=app.config["CONTACT_EMAIL"]) msg.add_recipient(rec.user.email) msg.body = rec.job.text_body msg.html = rec.job.html_body conn.send(msg) rec.sent = True db.session.add(rec) db.session.commit()
def send_email(self, conn, rec): msg = Message(rec.job.subject, sender=app.config['CONTACT_EMAIL']) msg.add_recipient(rec.user.email) msg.body = rec.job.text_body msg.html = rec.job.html_body conn.send(msg) rec.sent = True db.session.add(rec) db.session.commit()
def index(): theEmailForm = emailForm(request.form) if(request.method == 'POST'): msg = Message( 'expo.gatech.edu Contact Form', recipients=['*****@*****.**']) msg.add_recipient("*****@*****.**") msg.body = "Name: " + theEmailForm.name.data + "\n Email:" + \ theEmailForm.email.data + "\n\n" + theEmailForm.message.data mail.send(msg) return render_template('index.html', pageName="Index", emailForm=emailForm())
def download(token): form = TrackedDownloadForm(request.form) context = {'form': form} if app.config['DELIVERY_CONTROL_FILE']: path = app.config['DELIVERY_CONTROL_FILE'] try: t = os.path.getmtime(path) except FileNotFoundError: pass else: context['delivery_date'] = datetime.datetime.fromtimestamp(t) if token: dl = TrackedDownload.from_token(token) if not dl: flash('Clé invalide.', 'error') return render_template('download.html', **context), 403 else: dl.use() flash("Merci d'avoir téléchargé la base adresse nationale !", "success") if app.config['BAN_FILE_PATH']: suffix = "_%s" % dl.area if dl.area else '' path = app.config['BAN_FILE_PATH'].format(area=suffix) name = Path(path).name headers = { 'X-Accel-Redirect': path, 'Content-Disposition': 'attachment; filename="{}"'.format(name), # noqa } return '', 200, headers if request.method == 'POST' and form.validate(): dl = TrackedDownload.from_email(form.email.data, form.area.data) if not dl: dl = TrackedDownload(**form.data) dl.save() msg = Message() msg.add_recipient(dl.email) email_context = dict(dl.__dict__) download_link = "https:{domain}{path}".format( domain=app.config['SITE_URL'], path=url_for('download', token=dl.token)) email_context['download_link'] = download_link msg.body = render_template('tracked_download_email.txt', **email_context) msg.html = render_template('tracked_download_email.html', **email_context) msg.subject = "Votre téléchargement de la base adresse nationale" area = DEPARTEMENTS.get(dl.area) if area: msg.subject = "{} [{}]".format(msg.subject, area) mail.send(msg) flash('Un courriel vous a été envoyé à l\'adresse {email}'.format( email=dl.email), 'success') return redirect(url_for('download')) return render_template('download.html', **context)
def checkitup(): # we collect all invoices which are not paid sql_query = Payd.query.filter_by( time_payment=datetime.fromtimestamp(0)).all() for invoice in sql_query: print(invoice) howold = current_app.config['WARRANTY_TIME'] # ignore all invoices which are older than WARRANTY_TIME days if invoice.time_creation + timedelta(days=howold) > datetime.now(): print(invoice.order_id) # initiate conversation with pypayd pypayd_headers = {'content-type': 'application/json'} pypayd_payload = { "method": "check_order_status", "params": {"order_id": invoice.order_id}, "jsonrpc": "2.0", "id": 0, } #pypayd_response = requests.post( # current_app.config['PYPAYD_URI'], # data=json.dumps(pypayd_payload), # headers=pypayd_headers).json() #print(pypayd_response) #invoice.txn = 0 howmanyconfirmations = current_app.config['CONFIRMATIONS'] confirmations = pypayd_response['result']['amount'] # Huhu! We have a new payment! if invoice.txn == 0 and confirmations > howmanyconfirmations: # Send an email message if payment was registered # From: DEFAULT_MAIL_SENDER msg = Message() msg.add_recipient(current_user.email) msg.subject = "Payment confirmation" msg.body = "" # Register payment invoice.time_payment = datetime.now() # Register paid amount in the main database balance = current_user.credits current_user.credits = balance + pypayd_response['result']['amount'] # Housekeeping invoice.txn = confirmations # register all transactions in databases db.session.commit() flash('Thank you.', 'info') return redirect(url_for('frontend.index'))
def _game_started(recipient, screenname, identity, is_starter, is_acting): """ Lets recipient know their game has started. """ msg = Message("A game has started on Range vs. Range") msg.add_recipient(recipient) msg.html = render_template('game_started.html', recipient=recipient, screenname=screenname, is_starter=is_starter, is_acting=is_acting, unsubscribe=make_unsubscribe_url(identity)) send_email_async(msg)
def rsvp(): form = RsvpForm() if 'guestid' not in session: return redirect(url_for('login')) guests = Guest.query.filter_by(group=session['group']).all() if request.method == 'POST' and form.validate(): #if form.validate_on_submit(): #testg = Rsvp(2, 1, 'friday','afternoon',0) #return testg #db.session.add(testg) msg = Message("Thank you for your RSVP", sender=("Name", "*****@*****.**")) msg.bcc = ("*****@*****.**","*****@*****.**") for i in guests: msg.add_recipient(i.email_address) #return i.id #gid = i.id #logging.debug("this is i.id: ", i.id) #rsvpi = Rsvp(gid, form.i['id'].data, form.arrival_date.data, form.arrival_time.data, form.child_care.data, 1) radioname = "guest" + str(i.id) radval = form[radioname].data radval = str(radval) if radval not in ('0','1'): radval = -1 #if i.id == session['guestid']: session['response'] = radval ccval = form.child_care.data if ccval not in ('0','1'): ccval = -1 rsvpi = Rsvp(i.id, radval, form.notebox.data, form.arrival_date.data, form.arrival_time.data, ccval, 1 ) db.session.add(rsvpi) db.session.commit() rsvp_response0 = GuestRsvp.query.filter_by(id=session['guestid']).first() rsvp_response1 = GuestRsvp.query.filter_by(group=session['group']).all() #msg.body = "Insert receipt email here" # text body msg.body = render_template('rsvp-thank-you-email.txt', rsvp0=rsvp_response0, rsvpr=rsvp_response1) msg.html = render_template('rsvp-thank-you-email.html', rsvp0=rsvp_response0, rsvpr=rsvp_response1) mail.send(msg) return redirect(url_for('rsvp')) #else: #return "Didn't work" glist = [] for j in guests: glist.append(j.id) rsvp_response0 = GuestRsvp.query.filter_by(id=session['guestid']).first() rsvp_response = GuestRsvp.query.filter_by(group=session['group']).all() for r in rsvp_response: if r.id == session['guestid']: session['response'] = r.response if rsvp_response: return render_template('rsvp-thank-you.html', rsvpr=rsvp_response, guests=guests, glist=glist, rsvp0=rsvp_response0) return render_template('rsvp.html', form=form, guests=guests)
def _game_started(recipient, screenname, identity, is_starter, is_acting, game): """ Lets recipient know their game has started. """ msg = Message("Game %d has started on Range vs. Range" % (game.gameid,)) msg.add_recipient(recipient) msg.html = render_template('email/game_started.html', recipient=recipient, screenname=screenname, is_starter=is_starter, is_acting=is_acting, unsubscribe=make_unsubscribe_url(identity), game_url=make_game_url(str(game.gameid), login=True), gameid=game.gameid) send_email(msg)
def _your_turn(recipient, screenname, identity): """ Lets recipient know it's their turn in a game. The identity is used to create the unsubscribe link. We can safely use that to identify the user in plain text, because they get to see it anyway during authentication. Uses Flask-Mail; sends asynchronously. """ msg = Message("It's your turn on Range vs. Range") msg.add_recipient(recipient) msg.html = render_template('your_turn.html', recipient=recipient, screenname=screenname, unsubscribe=make_unsubscribe_url(identity)) send_email_async(msg)
def send_message(recipient, message, identity): """ Send message to userid. The identity is used to create the unsubscribe link. We can safely use that to identify the user in plain text, because they get to see it anyway during authentication. Uses Flask-Mail; sends asynchronously. """ msg = Message("A message for you!") msg.add_recipient(recipient) msg.html = render_template('email.html', message=message, unsubscribe=make_unsubscribe_url(identity)) send_email_async(msg)
def assignresource(x): org_id = request.form['employee'] row_data = Issue.query.filter_by(id=x).first() row_data.assigned_to = org_id row_data.status = "Open" db.session.commit() raised_by = Account.query.filter_by(org_id=row_data.raised_by).first() resource = Account.query.filter_by(org_id=org_id).first() body = "Dear " + resource.f_name + " " + resource.l_name + ",<br /><br />Thanks for using Issue Tracker.<br />Please note that you have been assigned an issue to resolve. Please find the details on the portal. <br /><br /> \ Thanks and Kind Regards,<br /> Admin. " msg = Message("Issue Tracker Notification", sender="*****@*****.**", recipients=[str(resource.email)]) msg.add_recipient(str(raised_by.email)) msg.html = body mail.send(msg) flash("Assignment successful.") return render_template('/reports/open_issues_rpt.html')
def email(): form = EmailComposeForm() if form.validate_on_submit(): users = get_query(form.destination.data) if form.preview.data is True: return render_template( "admin/email.html", html=format_html_email(form.text.data, form.subject.data), form=form, count=users.count(), ) if form.send_preview.data is True: subject = "[PREVIEW] " + form.subject.data formatted_html = format_html_email(form.text.data, subject) preview_email = form.send_preview_address.data with mail.connect() as conn: msg = Message(subject, sender=app.config["CONTACT_EMAIL"]) msg.add_recipient(preview_email) msg.body = format_plaintext_email(form.text.data) msg.html = formatted_html conn.send(msg) flash("Email preview sent to %s" % preview_email) return render_template( "admin/email.html", html=formatted_html, form=form, count=users.count() ) if form.send.data is True: job = EmailJob( form.subject.data, format_plaintext_email(form.text.data), format_html_email(form.text.data, form.subject.data), ) db.session.add(job) for user in users: db.session.add(EmailJobRecipient(job, user)) db.session.commit() flash("Email queued for sending to %s users" % len(users.count())) return redirect(url_for(".email")) return render_template("admin/email.html", form=form)
def markissueclosed(x): now = datetime.datetime.now() comment = request.form['comment'] row_data = Issue.query.filter_by(id=x).first() row_data.solution = comment row_data.status = "Closed" row_data.date_resolved = now db.session.commit() raised_by = Account.query.filter_by(org_id=row_data.raised_by).first() resource = Account.query.filter_by(org_id=row_data.assigned_to).first() body = "Dear " + raised_by.f_name + " " + raised_by.l_name + ",<br /><br />Thanks for using Issue Tracker.<br />An issue you raised has been closed. Please find the details on the portal. <br /><br /> \ Thanks and Kind Regards,<br /> Admin. " msg = Message("Issue Tracker Notification", sender="*****@*****.**", recipients=[str(resource.email)]) msg.add_recipient(str(raised_by.email)) msg.html = body mail.send(msg) flash("Issue successful closed.") return render_template('/reports/closed_issues_rpt.html')
def index(): theEmailForm = emailForm(request.form) if(request.method == 'POST'): if(request.form['type']=="img"): files=request.files['file'] filename = secure_filename(files.filename) files.save(os.path.join(os.path.join(os.path.dirname(os.path.abspath(__file__)),'static/img'),'GT_logo.png')) src = os.path.join(os.path.join(os.path.dirname(os.path.abspath(__file__)),'static/img'),'GT_logo.png') dst = os.path.join(os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))),'website/static/img'),'GT_logo.png') shutil.copyfile(src,dst) #the previous line will need to be calibrated on deploy else: msg = Message( 'expo.gatech.edu Contact Form', recipients=['*****@*****.**']) msg.add_recipient("*****@*****.**") msg.body = "Name: " + theEmailForm.name.data + "\n Email:" + \ theEmailForm.email.data + "\n\n" + theEmailForm.message.data mail.send(msg) return render_template('index.html', pageName="Index", emailForm=emailForm())
def send(o_id): # oh shit oh shit OH SHIT OH SHIT!!!! group = group_col.Group.find_one({'_id': ObjectId(o_id)}) if group.owner != session.get('username'): return render_template('basic.html', text='That is NOT your group. PLEASE.', redirect="/") users = group.users if len(users) <= 1: return render_template('basic.html', text="There aren't enough people!", redirect="/get/%s" % o_id) results = ss(users) with mail.connect() as conn: for user in results: email = user_col.User.find_one({'username': user}).email msg = Message(body='Hello %s,\n\nYour secret santa is %s! Have fun!' % (user, results[user]), subject="Your Secret Santa", sender=("Secret Santa", "*****@*****.**")) msg.add_recipient(email) conn.send(msg) return render_template('basic.html', text='Emails were sent!', redirect='/get/%s' % o_id)
def _game_finished(recipient, screenname, identity, game): """ Lets recipient know their game has finished and analysis is ready. This email gets sent even if the user is unsubscribed, because it just sucks so much when you miss one. """ msg = Message("Analysis for Game %d on Range vs. Range" % (game.gameid,)) msg.add_recipient(recipient) results = [] for rgp in game.rgps: items = {rgpr.scheme: rgpr.result for rgpr in rgp.results} results.append((rgp.user.screenname, items[RunningGameParticipantResult.SCHEME_EV])) msg.html = render_template('email/game_complete.html', recipient=recipient, screenname=screenname, unsubscribe=make_unsubscribe_url(identity), game_url=make_game_url(str(game.gameid)), gameid=game.gameid, results=results) send_email(msg)
def signup(): if request.method == 'POST': try: #add the user to database newUser = User(request.form['inputEmail'], generate_password_hash(request.form['inputPassword']), request.form['inputName'], datetime(2001,01,01), "") db.session.add(newUser) db.session.commit() #generate confirmation link, code:email+hash of email+name confirmation_link = app.config['DOMAIN'] + 'confirmemail?email='+request.form['inputEmail']+'&code='+hashlib.md5(request.form['inputEmail']+request.form['inputName']).hexdigest() #send email msg = Message("Welcome to better app", sender=app.config['DEFAULT_MAIL_SENDER']) msg.add_recipient(request.form['inputEmail']) msg.body = 'Welcome to the app! Please go to this address to confirm your email: {0}'.format(confirmation_link) mail.send(msg) return render_template('signup.html', message=gettext('Signed up, please check email for confirmation link!')) except Exception, e: print str(e) return render_template('signup.html', message=gettext('Error, please try again!'))
def send_confirm_email(to, code, url): with celery.app.test_request_context('/version'): message = Message("It'se you? Then type {}".format(code)) message.add_recipient(to) message.body = """Hello We've just received note, that this email wants to be registered with it-se.me . Please open this URL to confirm this has been sent by you {0} Or type the following code into your app: {1} If that wasn't triggered by you, feel free to delete this message and accept our apology for the bother. Thanks Mario """.format(url, code) message.html = """<p>Hello</p> <p>We've just received note, that this email wants to be registered with it-se.me . Please open this URL to confirm this has been sent by you</p> <p><a href="{0}">{0}</a><p> <p>Or type the following code into your app: <br><strong>{1}</strong> </p> <p>If that wasn't triggered by you, feel free to delete this message and accept our apology for the bother.</p> <p>Thanks<br>Mario</p> """.format(url, code) mail.send(message)
def contact_exchange(event): if request.method=='GET': return render_template('contact_exchange.html.jinja2', event=event, debug=str(app.config['DEBUG']).lower(), ui_test=str(request.args.get('ui_test', False)).lower()) if request.method == 'POST': ids = tuple(request.form.getlist('ids[]')) if len(ids) < 2: return jsonify(status=False, error=u'Insufficient users to connect') users = Participant.query.filter(Participant.event_id == event.id, Participant.nfc_id.in_(ids)).all() mail = Mail(app) message = Message("You connected with " + str(len(users) - 1) + " people using ContactExchange") message.cc = list() for user in users: email = '"' + user.name + '"<' + user.email + '>' if message.reply_to is None: message.reply_to = email message.add_recipient(email) else: message.cc.append(email) message.attach(make_name(user.name) + '.vcf', 'text/vcard', render_template('user_card.vcf', user=user, event=event)) message.sender = '"HasGeek"<*****@*****.**>' message.body = render_template('connectemail.md', users=users, event=event) message.html = markdown(message.body) log = CXLog() try: mail.send(message) log.sent = True log.log_message = u"Mail delivered to postfix server" except Exception as error: log.sent = True log.log_message = unicode(error) log.users = u','.join(ids) db.session.add(log) db.session.commit() return jsonify(success=True)
def sendMail(who, text): msg = Message('SurvivalCraft',sender='*****@*****.**') msg.add_recipient(who) msg.body = text with app.app_context(): mail.send(msg)
def test_add_recipient(self): msg = Message("testing") msg.add_recipient("*****@*****.**") self.assertEqual(msg.recipients, ["*****@*****.**"])
def send_contact_email(user_email, subject, body): msg = Message(subject, reply_to=user_email) msg.add_recipient('*****@*****.**') msg.body = body services.mail.send(msg)
def post(self): """ Returns the statistics for specific layers, area and year :return: """ # Entries wrong_parameter = [] try: first_name = api.payload['first_name'] except: wrong_parameter.append('first_name') try: last_name = api.payload['last_name'] except: wrong_parameter.append('last_name') try: email = api.payload['email'] except: wrong_parameter.append('email') try: unencrypted_password = api.payload['password'] except: wrong_parameter.append('password') # raise exception if parameters are false if len(wrong_parameter) > 0: exception_message = '' for i in range(len(wrong_parameter)): exception_message += wrong_parameter[i] if i != len(wrong_parameter) - 1: exception_message += ', ' raise ParameterException(exception_message + '') # password_encryption try: password = bcrypt.using(salt=FLASK_SALT).hash(str(unencrypted_password)) except Exception as e: raise RequestException(str(e)) # we check if the email has already been used if User.get_by_email(email) is not None: raise UserExistingException(email) # user creation in the DB user_datastore.create_user(email=email, password=password, active=False, first_name=first_name, last_name=last_name) db.session.commit() # mail creation try: link = constants.CLIENT_URL + "/register;token_activation=" + generate_confirmation_token(email) msg = Message() msg.add_recipient(email) msg.subject = 'Your registration on the HotMaps toolbox' msg.body = 'Welcome ' + first_name + ' ' + last_name + ' on the HotMaps toolbox,\n' \ 'To finalize your registration on the toolbox, please click on the following link: \n' \ + link mail.send(msg) except Exception as e: raise RequestException("Problem with the mail sending.") output = 'user registered' # output return { "message": output }
if details and len(details.groups()) == 10: subber = details.group(1) title = details.group(2) episode = str(int(details.group(3))) quality = details.group(7) format = details.group(10).upper() match = Anime.getAllMatches(subber, title, episode, quality, format) for watch in match: message = Message( 'New Episode of {0} Available'.format(watch.anime), sender = 'A Letter Bee <*****@*****.**>', ) message.add_recipient(watch.email) message.html = ''' Episode {0} of {1} is now available. Click <a href="{2}">here</a> to download it now. <br /> <br /> <small>To stop receiving notifications click <a href="http://watchmyani.me/unsubscribe/{3}">here</a>.</small> '''.format(episode, title, anime['links'][0]['href'], watch.h) with app.app_context(): mailman.send(message) watch.watched = episode watch.save() except (KeyboardInterrupt, SystemExit):
def send(self, body=None, recipient=None, subject=None): if self.mail: msg = Message(subject=subject, body=body) msg.add_recipient(recipient) return self.mail.send(msg)
def send_contact_email(user_email, subject, body, send_func=PyPICalc.mail.send): msg = Message(subject, reply_to=user_email) msg.add_recipient('*****@*****.**') msg.body = body send_func(msg)