def import_email(): click.echo("Importing Email...", nl=False) with open("./data/emails.json") as data_file: emails = json.load(data_file) for e in emails: satoshi_id = None if "satoshi_id" in e.keys(): satoshi_id = e["satoshi_id"] parent = None if "parent" in e.keys(): parent = Email.query.get(e["parent"]) new_email = Email( id=e["id"], satoshi_id=satoshi_id, url=e["url"], subject=e["subject"], sent_from=e["sender"], date=parser.parse(e["date"]), text=e["text"], source=e["source"], source_id=e["source_id"], thread_id=e["thread_id"], ) if parent: new_email.parent = parent db.session.add(new_email) db.session.commit() click.echo(DONE)
class EmailTest(unittest.TestCase): ''' Test class to test the behavior of the Email class ''' def setUp(self): ''' Set up method that will run before every test ''' self.new_email = Email(name='John', email_data='*****@*****.**') def tearDown(self): ''' Method that will clear up after test has run ''' db.session.delete(self.new_email) db.session.commit() def test_instance(self): self.assertTrue(isinstance(self.new_email,Email)) def test_check_instance_variables(self): self.assertEquals(self.new_email.name,'John') self.assertEquals(self.new_email.email_data,'*****@*****.**') def test_save_review(self): self.new_email.save_email() self.assertTrue(len(Email.query.all())>0)
def post(self): parser = reqparse.RequestParser() parser.add_argument('email', location='json', required=True) data = parser.parse_args() email = Email(data['email']) email.create() return Response(email, 201).to_dict()
def create_email(): data = request.get_json(force=True) validate(data, post_create_email_schema) email = Email(**data) dao_create_email(email) return jsonify(email.serialize()), 201
def generic_test_setup(test_case): app.config['TESTING'] = True app.config['WTF_CSRF_ENABLED'] = False app.config['DEBUG'] = False app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + \ os.path.join(app.config['BASE_DIR'], TEST_DB) test_case.app = app.test_client() db.drop_all() db.create_all() # Insert test contact with email new_contact = ContactStore(username=TEST_CONTACT_01.get('username'), first_name=TEST_CONTACT_01.get('first_name'), last_name=TEST_CONTACT_01.get('last_name') ) email_model_list = [] for email in TEST_CONTACT_01.get('emails'): email_model_list.append( Email(username=TEST_CONTACT_01.get('username'), email_address=email) ) new_contact.emails = email_model_list db.session.add(new_contact) db.session.commit()
def create_email(old_id=1, old_event_id=2, event_id=None, details='test event details', extra_txt='test extra text', replace_all=False, email_type=EVENT, created_at=None, send_starts_at=None, expires=None): if old_event_id: event = dao_get_event_by_old_id(old_event_id) if not event: event = create_event(old_id=old_event_id) create_event_date(event_id=str(event.id), event_datetime='2019-06-21 19:00') event_id = str(event.id) data = { 'event_id': event_id, 'old_id': old_id, 'old_event_id': old_event_id, 'details': details, 'extra_txt': extra_txt, 'replace_all': replace_all, 'email_type': email_type, 'created_at': created_at, 'send_starts_at': send_starts_at, 'expires': expires } email = Email(**data) dao_create_email(email) return email
def SendMail(request): log = 0 if request.method == 'POST': SendEmailform = SendEmailForm(request.POST) if SendEmailform.is_valid(): subject = SendEmailform.cleaned_data['subject'] body = SendEmailform.cleaned_data['body'] value1 = SendEmailform.cleaned_data['Select_Event'] event = Event.objects.get(id=value1) registraions = Registration.objects.filter(event=event) Email(registraions, subject, body) messages = "Email send succesfully" return render(request, 'form.html', { 'SendEmailform': SendEmailform, "messages": messages }) message = "Error during validation of form, please fill correct email data" return render(request, 'form.html', { 'SendEmailform': SendEmailform, "message": message }) else: SendEmailform = SendEmailForm() return render(request, 'form.html', {'SendEmailform': SendEmailform})
def test_an_email_models_string_is_the_email(session): """An email model's string is the email itself.""" # Given an email email = Email(email='*****@*****.**') # Then it's email is its string representation assert str(email) == '*****@*****.**'
def test_user_can_add_emails(session): """A user can add emails to their existing account.""" # Given a user user = create_user(session, email='*****@*****.**') # When an email is added using `add_email` method user.add_email('*****@*****.**') # Then that email should be accessible assert user.emails[1].email == '*****@*****.**' # When an email is added using `add_email` method using keyword user.add_email(email='*****@*****.**') # Then that email should be accessible assert user.emails[2].email == '*****@*****.**' # When a list of emails is added using `add_email` method user.add_email(emails=['*****@*****.**', '*****@*****.**']) # Then that email should be accessible assert user.emails[3].email == '*****@*****.**' assert user.emails[4].email == '*****@*****.**' # When an email is added using SQLAlchemy's `append` method user.emails.append(Email(email='*****@*****.**')) # Then that email should be accessible assert user.emails[5].email == '*****@*****.**'
def import_emails(): data = request.get_json(force=True) validate(data, post_import_emails_schema) errors = [] emails = [] for item in data: err = '' email = Email.query.filter(Email.old_id == item['id']).first() if not email: event_id = None email_type = EVENT if int(item['eventid']) < 0: if item['eventdetails'].startswith('New Acropolis'): email_type = MAGAZINE else: email_type = ANNOUNCEMENT expires = None if email_type == EVENT: event = dao_get_event_by_old_id(item['eventid']) if not event: err = u'event not found: {}'.format(item) current_app.logger.info(err) errors.append(err) continue event_id = str(event.id) expires = event.get_last_event_date() else: # default to 2 weeks expiry after email was created expires = datetime.strptime( item['timestamp'], "%Y-%m-%d %H:%M") + timedelta(weeks=2) email = Email( event_id=event_id, old_id=item['id'], old_event_id=item['eventid'], details=item['eventdetails'], extra_txt=item['extratxt'], replace_all=True if item['replaceAll'] == 'y' else False, email_type=email_type, created_at=item['timestamp'], send_starts_at=item['timestamp'], expires=expires) dao_create_email(email) emails.append(email) else: err = u'email already exists: {}'.format(email.old_id) current_app.logger.info(err) errors.append(err) res = {"emails": [e.serialize() for e in emails]} if errors: res['errors'] = errors return jsonify(res), 201 if emails else 400 if errors else 200
def build_email(subject, recipients, cc, body): sender = settings.EMAIL_SENDER return Email(subject=subject, from_email=sender, to=recipients, cc=cc, body=body)
def verify_email(token): email = Email.get_email_by_token(token) if email: email.verify() flash('Your email is now verified!') else: flash('Something went wrong. Please try again.') return redirect(url_for('auth.login'))
def build_email(subject, recipients, cc, body): sender = 'Eau de Web <Tenders Bot>' return Email(subject=subject, from_email=sender, to=recipients, cc=cc, body=body)
def forgot_password(): if request.method == 'POST': form = PasswordResetForm() #if form.validate_on_submit(): if True: if form.email.data != "": user = User.query.filter_by(email=form.email.data).first() else: return render_template( 'forgot_password.html', form=form, message="Please enter a valid user name or email address", passed="no") if user: new_mail = Email(user_id=user.id, recipient=user.email, message_type='Password reset', link_followed=0, created=db.func.now()) link_hash = new_mail.set_unique_hash() #db.session.add(new_mail) #db.session.commit() send_password_reset_email(user.email, link_hash) return render_template( 'forgot_password.html', form=form, message= 'We have sent your password reset email, from [email protected]. Please follow it\'s instructions to reset your password.', passed="yes") else: return render_template( 'forgot_password.html', form=form, message= "We cannot find a user matching either that user name or email address. Please check your spelling and try again." ) if not current_user.is_authenticated: form = PasswordResetForm() return render_template('forgot_password.html', form=form, message="", passed='no') else: return redirect('/userdata')
def email(self): # custom view to set SMTP settings form = EmailSetupForm() email = Email.query.first() if form.validate_on_submit(): if email is None: email = Email( server=form.server.data, port=form.port.data, username=form.username.data, password=form.password.data, default_sender=form.default_sender.data, use_tls=True, ) db.session.add(email) else: email.server = form.server.data email.port = form.port.data email.username = form.username.data email.default_sender = form.default_sender.data email.use_tls = True db.session.commit() flash('Email server info saved.') return redirect(url_for('email.email')) return self.render('admin/email.html', form=form, email=email)
def get_list_mails(item, dict_li): for n_email in item['email']: if Email.query.filter_by(email=n_email).count() != 0: email = Email.query.filter_by(email=n_email).first() else: email = Email(email=n_email, label='pro') dict_li['emails'].append(email) return dict_li
def email(): email_form = EmailForm() if email_form.validate_on_submit(): msg = Email(title=email_form.title.data, content=email_form.content.data) # 邮件内容会以文本和html两种格式呈现,而你能看到哪种格式取决于你的邮件客户端。 db.session.add(msg) db.session.commit() return '<h1>邮件发送成功</h1><a href="http://127.0.0.1:5000/dashboard">点此回主页</a>' return render_template('email.html', form=email_form)
def handle(self, *args, **options): with open('./ids.json') as ids_json: ids = json.load(ids_json) ids_json.close() with open('./emails.json') as emails_json: emails = json.load(emails_json) emails_json.close() usersList = [] usersMap = {} for user in ids: usersMap = { "user_id": user, "name": ids[user] } usersList.append(usersMap) for user in usersList: try: u = User(**user) u.save() self.stdout.write(u.user_id + ' created') except IntegrityError: self.stdout.write(u.user_id + ' SKIPPED') for email in emails: try: jsts = email["timeSent"] try: email["timeSent"] = datetime.datetime.fromtimestamp(jsts/1000.0) except ValueError: self.stdout.write(e.subject + ' SKIPPED') continue e = Email(**email) e.save() except IntegrityError: self.stdout.write(e.subject + ' SKIPPED')
def test_duplicate_emails(self): # Ensure emails are unique. email = Email('*****@*****.**') db.session.add(email) db.session.commit() with self.client: response = self.client.post('/', data=dict(email="*****@*****.**"), follow_redirects=True) self.assertIn(b'Sorry that email aleady exists!', response.data) self.assertTrue(response.status_code == 200)
def add_contact_to_db(username, first_name, last_name, emails): new_contact = ContactStore(username=username, first_name=first_name, last_name=last_name) email_model_list = [] for email in emails: email_model_list.append(Email(username=username, email_address=email)) new_contact.emails = email_model_list db.session.add(new_contact) db.session.commit() return new_contact
def index(): """Landing page for users to enter emails.""" form = SignUpForm(request.form) if form.validate_on_submit(): test = Email.query.filter_by(email=form.email.data, source=None).first() if test: flash('Sorry that email aleady exists!', 'danger') else: email = Email(email=form.email.data) db.session.add(email) db.session.commit() flash('Thank you for your interest!', 'success') return redirect(url_for('main.index')) return render_template('main/index.html', form=form)
def post(self): args = parser.parse_args() if Email.query.filter(Email.email == args.get('email'), Email.source == args.get('source')).first(): return {'message': "Thanks for signing up"} else: email = Email(email=args.get('email'), source=args.get('source'), form_data_as_json=args.get('form_data_as_json')) try: db.session.add(email) db.session.commit() except IntegrityError: return {'message': "Error signing up"}, 500 return {'message': "Thanks for signing up"}
def upload_magazine(magazine_id, pdf_data): current_app.logger.info('Upload magazine pdf: {}'.format(magazine_id)) try: magazine = dao_get_magazine_by_id(magazine_id) storage = Storage(current_app.config['STORAGE']) decoded_data = base64.b64decode(pdf_data) storage.upload_blob_from_base64string(magazine.filename, magazine.filename, decoded_data, content_type='application/pdf') try: topics = extract_topics(base64.b64decode(decoded_data)) except Exception as e: topics = [] current_app.logger.error("Error extracting topics: %r", e) dao_update_record(Magazine, magazine_id, topics=topics) email = dao_get_email_by_magazine_id(magazine_id) if not email: email = Email(magazine_id=magazine.id, email_state=READY, email_type=MAGAZINE) dao_create_email(email) emails_to = [user.email for user in dao_get_users()] subject = 'Please review {}'.format(magazine.title) # send email to admin users and ask them to log in in order to approve the email review_part = '<div>Please review this email: {}/emails/{}</div>'.format( current_app.config['FRONTEND_ADMIN_URL'], str(email.id)) magazine_html = get_email_html(MAGAZINE, magazine_id=magazine.id) response = send_smtp_email(emails_to, subject, review_part + magazine_html) if response != 200: current_app.logger.error( 'Error sending review email {}, for {}'.format( email.id, magazine.id)) except Exception as e: current_app.logger.error('Task error uploading magazine: {}'.format( str(e)))
def getEmails(gte, lte): store = file.Storage('token.json') creds = store.get() if not creds or creds.invalid: flow = client.flow_from_clientsecrets( '/Users/b0206610/Desktop/Gmail-Alexa/app/credentials.json', SCOPES) creds = tools.run_flow(flow, store) service = build('gmail', 'v1', http=creds.authorize(Http())) query = "before: {0} after: {1}".format(lte.strftime('%Y/%m/%d'), gte.strftime('%Y/%m/%d')) batch = service.users().messages().list(userId='me', q=query, labelIds=['INBOX', 'UNREAD']).execute() emails = [] for message in batch['messages']: msg = service.users().messages().get(userId='me', id=message['id']).execute() date = datetime.datetime.fromtimestamp(int(msg['internalDate']) / 1000) if date >= gte and date <= lte: sender = list( filter(lambda x: x['name'] == 'From', msg['payload']['headers']))[0]['value'] receiver = list( filter(lambda x: x['name'] == 'To', msg['payload']['headers']))[0]['value'] try: timestamp = getDateObjFromDate( list( filter(lambda x: x['name'] == 'Date', msg['payload']['headers']))[0]['value']) except Exception as e: timestamp = None subject = list( filter(lambda x: x['name'] == 'Subject', msg['payload']['headers']))[0]['value'] snippet = msg['snippet'] emails.append(Email(sender, receiver, timestamp, subject, snippet)) else: break return emails
def getMessage(record_idP, client_tokenP, message_typeP): """this will return sent message :param record_idP: this is the record id of sms or email :param client_tokenP: this is the user token :param message_typeP: this is the message type :return: will return result """ client_record = RemoteClient.getRemoteClientRecord(client_tokenP) record = None result_dict = {} #check if we have nothing if client_record is None: return json.dumps({"error": "user not found"}) #check if sms is being requested if message_typeP == "sms": record = SMS.getRecentlySentSMS(record_idP, client_record.id) #check if we have nothing if record is None: return json.dumps({"error": "no match found"}) result_dict["contact_number"] = record.contact_number #check if email is being requested elif message_typeP == "email": record = Email.getRecentlySentEmail(record_idP, client_record.id) # check if we have nothing if record is None: return json.dumps({"error": "no match found"}) result_dict["contact_email"] = record.contact_email_address else: return json.dumps({"error": "unknown message type"}) result_dict["message_content"] = record.message_content return json.dumps(result_dict) #===========================================end of class definition
def register(): if current_user.is_authenticated: return redirect(url_for('index')) form = RegistrationForm() if form.validate_on_submit(): user = User(name=re.sub(r'\s', '', form.name.data), surname=re.sub(r'\s', '', form.surname.data), patronymic=re.sub(r'\s', '', form.patronymic.data), email=re.sub(r'\s', '', form.email.data), position=form.position.data, organization=form.organization.data, materials='') user.set_password(form.password.data) email = Email(value=form.email.data) db.session.add(user) db.session.add(email) db.session.commit() flash('Вы зарегистрированы') return redirect(url_for('login')) return render_template('register.html', title='Register', form=form)
def test_an_email_can_generate_verification_token(app, session): """An email can generate a verification token.""" # Given an email (on a user) and that email's verification token user = create_user(session, email='*****@*****.**') email_verification_token = user.email.verification_token # When the token is used to retrieve the email email_to_verify = Email.get_email_by_token(email_verification_token) # Then it returns the email to verify assert email_to_verify == '*****@*****.**' # When the token is decoded from jwt import decode as jwt_decode decoded_token = jwt_decode(email_verification_token, app.config['SECRET_KEY'], algorithms=['HS256']) # Then the email and user id should be accessible. assert decoded_token['email'] == '*****@*****.**' assert decoded_token['user_id'] == user.id
def emails(workspace_id): ''' For GET requests, return all emails for the given workspace. For POST requests, add a new email to the given workspace. ''' if not validate_workspace(workspace_id): return 'workspace does not exist', 404 # request is a GET if request.method == 'GET': all_emails = Email.query.filter_by(workspace_id=workspace_id).order_by( Email.updated_at.desc()).all() schema = EmailSchema(many=True, strict=True) email_data = schema.dump(all_emails) return jsonify(email_data[0]) # request is a POST elif request.method == 'POST': name = request.form.get('Name') html = request.form.get('HTML').encode() subject = request.form.get('Subject') track = request.form.get('Track') track_bool = convert_to_bool(track) if type(track_bool) != bool: return 'Track must be either true or false', 400 email = Email(name=name, html=html, subject=subject, workspace_id=workspace_id, track=track_bool) db.session.add(email) update_workspace_ts(Workspace.query.filter_by(id=workspace_id).first()) db.session.commit() schema = EmailSchema(strict=True) email_data = schema.dump(email) return jsonify(email_data[0]), 200
def createEmail(contact_email_addressP, message_contentP, client_tokenP): """this will create a new email :param contact_email_addressP: this is the email address of the contact :param message_contentP: this is the message content :param client_tokenP: this is the user token :return: will return details of the email record """ client_record = RemoteClient.getRemoteClientRecord(client_tokenP) # check if we dont have client record if client_record is None: return json.dumps({"error": "user not found"}) email = Email(contact_email_addressP, client_record.id, message_contentP) commitToDatabase() return json.dumps({ "id": email.id, "remote_client_id": email.remote_client_id, "contact_email_address": email.contact_email_address })
def _send( self, message, subject, type_, user=None, recipient=None, add_sender=True, _disable_commit=False, **kwargs, ): from app.models import Email from app import db actual_recipient = user.email if user else recipient message = {**message, "To": [{"Email": actual_recipient}]} if add_sender: message["From"] = {"Email": SENDER_ADDRESS, "Name": SENDER_NAME} if subject: message["Subject"] = subject response = self.mailjet.send.create(data={"Messages": [message]}) mailjet_id = self._retrieve_mailjet_id_or_handle_error( response, actual_recipient ) db.session.add( Email( mailjet_id=mailjet_id, address=actual_recipient, user=user, type=type_, employment=kwargs.get("employment"), ) ) db.session.commit() if not _disable_commit else db.session.flush()
def create_data(): """Adds data to the email model.""" db.session.add(Email(email="*****@*****.**")) db.session.add(Email(email="*****@*****.**")) db.session.add(Email(email="*****@*****.**")) db.session.commit()
def _extract_email_info(self, message): """Copy email contents into Email object for database storage""" log.debug("Extracting email contents for database") email = Email() email.read_receipt_requested = message.json['IsReadReceiptRequested'] email.from_emailaddress = EmailAddress( address=message.json['From']['EmailAddress']['Address'], name=message.json['From']['EmailAddress']['Name']) email.sender = EmailAddress( address=message.json['Sender']['EmailAddress']['Address'], name=message.json['Sender']['EmailAddress']['Name']) to_recipients = [EmailAddress( address=recipient['EmailAddress']['Address'], name=recipient['EmailAddress']['Name']) for recipient in message.json['ToRecipients']] for recipient in to_recipients: email.to_recipients.append(recipient) cc_recipients = [EmailAddress( address=recipient['EmailAddress']['Address'], name=recipient['EmailAddress']['Name']) for recipient in message.json['CcRecipients']] for recipient in cc_recipients: email.cc_recipients.append(recipient) bcc_recipients = [EmailAddress( address=recipient['EmailAddress']['Address'], name=recipient['EmailAddress']['Name']) for recipient in message.json['BccRecipients']] for recipient in bcc_recipients: email.bcc_recipients.append(recipient) reply_to_recipients = [EmailAddress( address=recipient['EmailAddress']['Address'], name=recipient['EmailAddress']['Name']) for recipient in message.json['ReplyTo']] for recipient in reply_to_recipients: email.reply_to_recipients.append(recipient) email.importance = message.json['Importance'] email.subject = message.json['Subject'].encode('ascii', 'ignore') email.body_content_type = message.json['Body']['ContentType'] email.body = message.json['Body']['Content'].encode('ascii', 'ignore') email.body_preview = message.json['BodyPreview'].encode( 'ascii', 'ignore') email.created = datetime.strptime( message.json['DateTimeCreated'], '%Y-%m-%dT%H:%M:%SZ') # 2016-02-11T14:37:27Z email.sent = datetime.strptime( message.json['DateTimeSent'], '%Y-%m-%dT%H:%M:%SZ') email.received = datetime.strptime( message.json['DateTimeReceived'], '%Y-%m-%dT%H:%M:%SZ') email.last_modified = datetime.strptime( message.json['DateTimeLastModified'], '%Y-%m-%dT%H:%M:%SZ') email.has_attachments = message.hasAttachments if message.hasAttachments: for attachment in message.attachments: attachment_obj = Attachment( filename=attachment.json['Name'], file=attachment.json['ContentBytes']) email.attachments.append(attachment_obj) db.session.add(email) db.session.commit()