def abandonJob(jobID): job = Job.query.filter_by(jobID=jobID).first() if job is None or job.jobReceiver != current_user.username: return redirect(url_for("index", _scheme="https", _external=True)) job.jobReceiver = None db.session.commit() session["abandonedJob"] = True jobSender = User.query.filter_by(username=job.jobSender).one() try: msgReceiver = flask_mail.Message("Gigomy: You have abandoned a job", sender="*****@*****.**", recipients=[current_user.email]) msgReceiver.body = ( "Greetings from Gigomy!\nThis email confirms that you have abandoned the job '{}' by {}." .format(job.jobTitle.rstrip(), job.jobSender.rstrip())) mail.send(msgReceiver) msgSender = flask_mail.Message("Gigomy: Your job has been abandoned!", sender="*****@*****.**", recipients=[jobSender.email]) msgSender.body = ( "Greetings from Gigomy!\nThis email informs you that your job '{}' has been abandoned by {}." .format(job.jobTitle.rstrip(), current_user.username.rstrip())) mail.send(msgSender) except: return redirect( url_for("see", id=jobID, _scheme="https", _external=True)) return redirect(url_for("see", id=jobID, _scheme="https", _external=True))
def deleteJob(jobID): job = Job.query.filter_by(jobID=jobID).first() if job is None: return redirect(url_for("index", _scheme="https", _external=True)) jobReceiver_ = job.jobReceiver db.session.delete(job) db.session.commit() session["deletedJob"] = True try: msgSender = flask_mail.Message("Gigomy: Your job has been deleted!", sender="*****@*****.**", recipients=[current_user.email]) msgSender.body = ( "Greetings from Gigomy!\nThis email confirms that your job '{}' has been deleted." .format(job.jobTitle.rstrip())) mail.send(msgSender) jobReceiver = User.query.filter_by(username=jobReceiver_).one() if jobReceiver: msgReceiver = flask_mail.Message( "Gigomy: Your job has been deleted!", sender="*****@*****.**", recipients=[jobReceiver.email]) msgReceiver.body = ( "Greetings from Gigomy!\nThis email informs you that your job '{}' has been deleted." .format(job.jobTitle.rstrip())) mail.send(msgReceiver) except: return redirect(url_for("index", _scheme="https", _external=True)) return redirect(url_for("index", _scheme="https", _external=True))
def send_mail(to, mailcode): app = current_app._get_current_object() msg = flaskmail.Message(app.config['FLASK_MAIL_SUBJECT_PREFIX'] + "您的账号注册验证码", sender=app.config['FLASK_MAIL_SENDER'], recipients=[to]) # 邮件内容会以文本和html两种格式呈现,而你能看到哪种格式取决于你的邮件客户端。 msg.body = 'sended by flask-email' msg.html = ''' <h1> 亲爱的, </h1> <h3> 欢迎来到 <b>球鞋资讯平台</b>! </h3> <p> 您的验证码为 <b>{mailcode}</b> 赶快去完善注册信息吧!!! </p> <p>感谢您的支持和理解</p> <p>来自:Flask-Test-Project</p> <p><small>{time}</small></p> '''.format(mailcode=mailcode, time=datetime.utcnow) thread = Thread(target=send_async_email, args=[app, msg]) thread.start() return thread
def index(): if flask.request.method == "POST": firstname = flask.request.form.get('firstname') lastname = flask.request.form.get('lastname') email = flask.request.form.get('email') countryCode = flask.request.form.get('countryCode') phone = flask.request.form.get('phone') job = flask.request.form.get('job') company = flask.request.form.get('company') message = flask.request.form.get('message') msg = flask_mail.Message( subject="Hit for Steinherz Media", body= "{} {}, {}, from {} company sent you a message.\nThe message is: {}.\nThe return e-mail address is: {}\nThe phone number is: country code ({}) {}" .format(firstname, lastname, job, company, message, email, countryCode, phone), sender=('*****@*****.**'), recipients=['*****@*****.**']) mail.send(msg) flask.flash( "Your message has been sent successfully. Steinherz Media will contact you shortly." ) return flask.redirect(flask.url_for('index')) return flask.render_template("index.html")
def send_upload_cv_confirmation(app, mail, person_id, to_email, to_name): to_email = map_to_email(app, to_email) link = generate_upload_url(app.secret_key, person_id) print("confirm candidate email: ", person_id, " ", to_email, "\n", link, sep='') f = open("last_confirm_url.txt", 'w') try: f.write(link) # for use in selenium_tests.js finally: f.close() body = UPLOAD_CV_MESSAGE.format(name=to_name, link=link) msg = flask_mail.Message( body=body, subject="Share your CV with voters using this link", sender=("Democracy Club CV", "*****@*****.**"), recipients=[(to_name, to_email)]) mail.send(msg)
def send_email_candidates(app, mail, candidates, from_email, subject, message): for candidate in candidates: person_id = candidate['id'] to_email = candidate['email'] to_name = candidate['name'] to_email = map_to_email(app, to_email) link = generate_upload_url(app.secret_key, person_id) print("email candidate asking: ", person_id, " ", to_email, "\n", link, sep='') full_message = "Dear " + to_name + ", \n\n" + message.strip() body = CONSTITUENT_MAIL_MESSAGE.format(name=to_name, link=link, from_email=from_email, message=full_message) msg = flask_mail.Message(body=body, subject=subject.strip(), sender=("Democracy Club CV", "*****@*****.**"), recipients=[(to_name, to_email)]) mail.send(msg)
def share_p(): ''' generates a token that can be used to grant access to a project ''' if not authenticator.is_auth(flask.session): return flask.jsonify(status="auth", message="User is not authenticated") # request fields: target, access, project_id, document_id req = json.loads(flask.request.form['request']) try: # create a token for the given document and email the recipient if req['record']['project_id'] is None: raise query.QueryException("Required parameter project_id not provided") result = query.add_token(db(), authenticator.user_id(flask.session), req['record']['project_id'], req['record']['access'], document_id=None) # send email if config.EMAIL: # not yet implemented msg = flask_mail.Message("Hello", sender="*****@*****.**", recipients=[req['record']['target']]) mail.send(msg) return flask.jsonify(status="success", token=result) except query.QueryException as ex: return flask.jsonify(status="error", message=ex.message)
def api_comsolRegister(): import flask import flask_mail import sirepo.util global _mail if not _mail: a = sirepo.util.flask_app() a.config.update( MAIL_USE_TLS=True, MAIL_PORT=587, MAIL_SERVER=cfg.mail_server, MAIL_USERNAME=cfg.mail_username, MAIL_PASSWORD=cfg.mail_password, ) _mail = flask_mail.Mail(a) req = http_request.parse_json() msg = flask_mail.Message( subject='Sirepo / COMSOL Registration', sender=cfg.mail_support_email, recipients=[cfg.mail_recipient_email], body=u''' Request for access to Sirepo / COMSOL. Name: {} Email: {} '''.format(req.name, req.email), ) _mail.send(msg) return http_reply.gen_json_ok()
def send_recovery_email(email): users = User.query.filter_by(email=email).all() email_authentication = Authentication.query.filter(db.and_(Authentication.login['login'].astext == email, Authentication.type == AuthenticationType.EMAIL)).first() if email_authentication is not None and email_authentication.user not in users: users.append(email_authentication.user) if not users: return password_reset_urls = {} for user in users: for authentication_method in user.authentication_methods: if authentication_method.type != AuthenticationType.LDAP: password_reset_urls[authentication_method] = build_confirm_url(authentication_method) service_name = flask.current_app.config['SERVICE_NAME'] subject = service_name + " Account Recovery" html = flask.render_template('mails/account_recovery.html', email=email, users=users, password_reset_urls=password_reset_urls) text = flask.render_template('mails/account_recovery.txt', email=email, users=users, password_reset_urls=password_reset_urls) while '\n\n\n' in text: text = text.replace('\n\n\n', '\n\n') try: mail.send(flask_mail.Message( subject, sender=flask.current_app.config['MAIL_SENDER'], recipients=[email], body=text, html=html )) except smtplib.SMTPRecipientsRefused: pass
def gen_thumbs(): # find all the CVs with out of date thumbnail cvs_bad_thumbs = lookups.all_cvs_bad_thumbnails(main.app.config) for x in cvs_bad_thumbs: print("cron missing thumb:", x) filename = "tmp/{0}.png".format(x["person_id"]) # generate thumbnail with phantom try: subprocess.check_call(["phantomjs", "screenshot.js", x["url"], filename]) # make a JPEG, they're smaller img = PIL.Image.open(filename) img.save(filename + ".jpg", option='optimize') # add the thumbnail to S3 lookups.add_thumb(main.app.config, filename + ".jpg", x['name'].replace("cvs/", "thumbs/") + ".jpg", extension="jpg") os.remove(filename) os.remove(filename + ".jpg") except subprocess.CalledProcessError: print("Failed to make thumb for person ", str(x["person_id"])) print(traceback.format_exc()) msg = flask_mail.Message(body=traceback.format_exc(), subject="Failed to make thumb for person " + str(x["person_id"]), sender=("Democracy Club CV", "*****@*****.**"), recipients=[("Democracy Club CV", "*****@*****.**")] ) with main.app.app_context(): main.mail.send(msg)
def test_send(self, requests_mock): requests_mock.post('https://api.mailgun.net/v3/example.com/messages', json={'response': 'ok'}) client = MailgunClient(domain='example.com', api_key='foo', testing=False) message = flask_mail.Message( subject='RE: xyz', recipients=['*****@*****.**', '*****@*****.**'], body='very important message', html='<blink>very important message</blink>', sender='*****@*****.**', cc=['*****@*****.**'], bcc=['*****@*****.**'], ) resp = client.send(message) assert resp == {'response': 'ok'} assert requests_mock.call_count == 1 req = requests_mock.request_history[0] body = urllib.parse.parse_qs(req.text) assert body['from'] == ['*****@*****.**'] assert body['to'] == ['*****@*****.**', '*****@*****.**'] assert body['cc'] == ['*****@*****.**'] assert body['bcc'] == ['*****@*****.**'] assert body['subject'] == ['RE: xyz'] assert body['text'] == ['very important message'] assert body['html'] == ['<blink>very important message</blink>'] assert 'attachment' not in body
def send_email(body): msg = flask_mail.Message( sender='*****@*****.**', recipients=current_user.email, body=body ) mail_mgr.send(msg)
def send_email_confirmation_email(email, user_id, salt): token_data = {'email': email, 'user_id': user_id} token = generate_token(token_data, salt=salt, secret_key=flask.current_app.config['SECRET_KEY']) confirm_url = flask.url_for("frontend.user_preferences", user_id=user_id, token=token, _external=True) service_name = flask.current_app.config['SERVICE_NAME'] subject = service_name + " Email Confirmation" html = flask.render_template('mails/email_confirmation.html', confirm_url=confirm_url) text = flask.render_template('mails/email_confirmation.txt', confirm_url=confirm_url) while '\n\n\n' in text: text = text.replace('\n\n\n', '\n\n') try: mail.send( flask_mail.Message(subject, sender=flask.current_app.config['MAIL_SENDER'], recipients=[email], body=text, html=html)) except smtplib.SMTPRecipientsRefused: pass
def _send_notification(type: NotificationType, user_id: int, data: typing.Dict[str, typing.Any]) -> None: """ Send a new notification by email. :param type: the type of the new notification :param user_id: the ID of an existing user :param data: the data for the new notification :raise errors.UserDoesNotExistError: when no user with the given user ID exists """ user = users.get_user(user_id) service_name = flask.current_app.config['SERVICE_NAME'] subject = service_name + " Notification" template_path = 'mails/notifications/' + type.name.lower() html = flask.render_template(template_path + '.html', user=user, type=type, data=data, get_user=users.get_user, get_group=groups.get_group, get_project=projects.get_project) text = flask.render_template(template_path + '.txt', user=user, type=type, data=data, get_user=users.get_user, get_group=groups.get_group, get_project=projects.get_project) while '\n\n\n' in text: text = text.replace('\n\n\n', '\n\n') try: mail.send(flask_mail.Message( subject, sender=flask.current_app.config['MAIL_SENDER'], recipients=[user.email], body=text, html=html )) except smtplib.SMTPRecipientsRefused: pass
def events(): service = auth.get_calendar_service() now = (datetime.datetime.utcnow()).isoformat() + \ 'Z' # 'Z' indicates UTC time print('Getting the upcoming 100 events') events, time_zone = calendar_api.get_events(service, end_cap=now, max_results=100) json_dict = { 'timeZone': time_zone, 'events': sorted([calendar_api.parse_event_info(e) for e in events], key=lambda e: e['start']) } for e in json_dict.get('events'): if e.get('zoom') == "": # No zoom link found, send email message = flask_mail.Message( subject='No Link included in your ZoomTV Event', body= "Your zoomTV event titled {} doesn't seem to have a Zoom link in the location or description. \ Please add one so people can find your event!".format( e.get('summary')), recipients=[str(e['creator'])]) mail.send(message) return json.dumps(json_dict)
def reset_password(): # If the user is already logged in, just display the index if already_logged_in(request): flash('Already logged in.') return redirect(url_for('index')) if request.method == 'GET': return TemplateManager.get_reset_password_template() elif request.method == 'POST': email = request.form['email'].strip() errors = User.validate_email(email) if len(errors): return TemplateManager.get_reset_password_template(errors) user = User.get_user_by_email(email) if user: token = PasswordRecoveryTokens.create(user) if not token: return TemplateManager.get_reset_password_template(['Could not reset password. Please try again.']) # Send a password recovery token via email msg = flask_mail.Message("Tweeter - Password Recovery", sender="*****@*****.**", recipients=[user.email]) msg.html = 'To reset your password click <a href="https://{:s}/update_password/{:s}">here</a>'.format(request.host, token) mail.send(msg) flash('If your email address exists in our database, you will receive a password recovery link at your email address in a few minutes.') return redirect(url_for('login'))
def reset_password(school): request = flask.request.json school = app.mongo.db.schools.find_one_or_404({'fragment': school}, {'_id': False}) c = mongo.SchoolCollections(school['fragment']) user = c.user.find_one_or_404({ 'email': request['email'], }, { '_id': True, 'email': True, 'first': True, 'middle': True, 'last': True, }) user = util.User(user, school) user['name'] = user.name() secret = util.create_verification(c, 'reset_password', user=user['_id']) msg = flask_mail.Message( "Password Reset", recipients=user['email'][0:1], ) msg.html = flask.render_template( 'email/reset_password.html', school=school, user=user.user, secret=secret, ) msg.body = flask.render_template( 'email/reset_password.txt', school=school, user=user.user, secret=secret, ) app.mail.send(msg) return flask.jsonify()
def mail_message(subject, template, to, **kwargs): sender_email = '*****@*****.**' email = flask_mail.Message(subject, sender=sender_email, recipients=[to]) email.body = render_template(template + ".txt", **kwargs) email.html = render_template(template + ".html", **kwargs) mail.send(email)
def _send_login_email(user, uri): global _smtp if not _smtp: if not (pkconfig.channel_in('dev') and cfg.smtp_server == _DEV_SMTP_SERVER): a = sirepo.util.flask_app() a.config.update( MAIL_USE_TLS=True, MAIL_PORT=587, MAIL_SERVER=cfg.smtp_server, MAIL_USERNAME=cfg.smtp_user, MAIL_PASSWORD=cfg.smtp_password, ) _smtp = flask_mail.Mail(a) else: pkdlog('{}', uri) return http_reply.gen_json_ok({'uri': uri}) login_text = u'sign in to' if user.user_name else \ u'confirm your email and finish creating' msg = flask_mail.Message(subject='Sign in to Sirepo', sender=(cfg.from_name, cfg.from_email), recipients=[user.unverified_email], body=u''' Click the link below to {} your Sirepo account. This link will expire in {} hours and can only be used once. {} '''.format(login_text, _EXPIRES_MINUTES / 60, uri)) _smtp.send(msg) return http_reply.gen_json_ok()
def send_email(subject, sender, recipients, text_body, html_body, attachments=None): msg = flask_mail.Message(subject, sender=sender, recipients=recipients) msg.body = text_body msg.html = html_body if attachments: for attachment in attachments: msg.attach(*attachment) mail.send(msg)
def send_mail(subject, recipients, text, html): msg = flask_mail.Message(subject=subject, sender=app.config['MAIL_USERNAME'], recipients=recipients, text=text, html=html) mail_mgr.send(msg)
def SendEmail(emailSubject: str, emailTo: str, emailBody: str): with app.app_context(): msg = eMail.Message(sender=app.config.get("MAIL_USERNAME"), subject=emailSubject, recipients=[emailTo], body=emailBody) mail.send(msg)
def send_mail(sender, receivers, subject, txt_content=None, html_content=None): msg = flask_mail.Message(sender=sender, recipients=receivers, subject=subject, body=txt_content, html=html_content) mail.send(msg)
def post(self, link_id): if not link_id: l = Link() l.uuid = uuid.uuid4().hex l.receiver_id = flask_auth.current_user.id # TODO: by default, no expiry and unlimited uploads # in the future, allow users to configure this # l.expiry_date = datetime.datetime.today() + \ # datetime.timedelta(days=7) # l.uploads_allowed = 1 db.session.add(l) db.session.commit() return flask.Response(json.dumps(l.to_dict()), status=201, mimetype='application/json') link = Link.query.filter_by(receiver_id=flask_auth.current_user.id, uuid=link_id).first_or_404() if not flask.request.json: flask.abort(400) email = flask.request.json.get('mail') if email: link.giver_email = email['giver'] link.message = email.get('message', '') msg = flask_mail.Message('Send me a file via AeroUP', body='{}\n\n{}'.format( link.message, flask.url_for('.upload', link_id=link.uuid, _external=True)), sender=(link.receiver.full_name(), link.receiver.email), recipients=[link.giver_email]) mail.send(msg) valid_for = flask.request.json.get('valid_for') if valid_for: link.expiry_date = datetime.datetime.today() + \ datetime.timedelta(days=valid_for) max_uploads = flask.request.json.get('max_uploads') if max_uploads: link.uploads_allowed = max_uploads db.session.add(link) db.session.commit() return flask.Response(json.dumps(link.to_dict()), status=200, mimetype='application/json')
def send_email(subject, text_body, sender, receivers, html_body=None): # Create a message msg = flask_mail.Message(subject=subject, sender=sender, recipients=receivers) msg.body = text_body if html_body: msg.html = html_body mail_mngr.send(msg)
def send_password_code(user, action): "Send an email with the one-time code to the user's email address." message = flask_mail.Message("DataGraphics user account {action}", recipients=[user["email"]]) url = flask.url_for(".password", username=user["username"], code=user["password"][len("code:"):], _external=True) message.body = f"To set your password, go to {url}" utils.mail.send(message)
def emit(self, record): msg = self.format(record) subj = self.getSubject(record, msg) email = flask_mail.Message( subj, recipients=self.recipients, ) email.body = 'User-agent: %s\n\n%s' % ( flask.request.headers.get('User-agent'), msg) self.mailer.send(email)
def send_password_code(user, action): "Send an email with the one-time code to the user's email address." site = flask.current_app.config["SITE_NAME"] message = flask_mail.Message(f"{site} user account {action}", recipients=[user["email"]]) url = utils.url_for(".password", username=user["username"], code=user["password"][len("code:"):]) message.body = f"To set your password, go to {url}" utils.mail.send(message)
def send_mail(to, subject, template_file, **kwargs): msg = flask_mail.Message(subject=\ flask.current_app.config['FLASKY_MAIL_SUBJECT_PREFIX'] + subject, sender=flask.current_app.config['FLASKY_MAIL_SENDER'], recipients=[to]) msg.body = flask.render_template(template_file+'.txt', **kwargs) msg.html = flask.render_template(template_file+'.html', **kwargs) app = flask.current_app._get_current_object() # get the real object thread = threading.Thread(target=async_send, args=(app, msg)) thread.daemon = True thread.start()
def send(self, to, subject=None, body=None, reply_to=None, template=None, **kwargs): """ To send email :param to: the recipients, list or string :param subject: the subject :param body: the body :param reply_to: reply_to :param template: template, will use the templates instead :param kwargs: context args :return: bool - True if everything is ok """ sender = self.config.get("MAIL_SENDER") recipients = [to] if not isinstance(to, list) else to kwargs.update({"subject": subject, "body": body, "reply_to": reply_to}) if not self.validated: raise exceptions.MochaError("Mail configuration error") if self.provider == "SES": kwargs["to"] = recipients if template: self.mail.send_template(template=template, **kwargs) else: self.mail.send(**kwargs) elif self.provider == "SMTP": if template: data = self._template(template=template, **kwargs) kwargs["subject"] = data["subject"] kwargs["body"] = data["body"] kwargs["recipients"] = recipients kwargs["sender"] = sender # Remove invalid Messages keys _safe_keys = [ "recipients", "subject", "body", "html", "alts", "cc", "bcc", "attachments", "reply_to", "sender", "date", "charset", "extra_headers", "mail_options", "rcpt_options" ] for k in kwargs.copy(): if k not in _safe_keys: del kwargs[k] message = flask_mail.Message(**kwargs) self.mail.send(message) else: raise exceptions.MochaError( "Invalid mail provider. Must be 'SES' or 'SMTP'")