Esempio n. 1
0
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})
Esempio n. 2
0
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)
Esempio n. 3
0
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()
Esempio n. 4
0
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) == '*****@*****.**'
Esempio n. 5
0
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
Esempio n. 6
0
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 == '*****@*****.**'
Esempio n. 7
0
 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)
Esempio n. 8
0
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
Esempio n. 9
0
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)
Esempio n. 10
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()
Esempio n. 11
0
def build_email(subject, recipients, cc, body):
    sender = settings.EMAIL_SENDER

    return Email(subject=subject,
                 from_email=sender,
                 to=recipients,
                 cc=cc,
                 body=body)
Esempio n. 12
0
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
Esempio n. 13
0
 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)
Esempio n. 14
0
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
Esempio n. 15
0
 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)
Esempio n. 16
0
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
Esempio n. 17
0
 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"}
Esempio n. 18
0
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)
Esempio n. 19
0
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)))
Esempio n. 20
0
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
Esempio n. 21
0
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')
Esempio n. 22
0
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)
Esempio n. 23
0
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
Esempio n. 24
0
    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
        })
Esempio n. 25
0
    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()
Esempio n. 26
0
 def setUp(self):
     '''
     Set up method that will run before every test
     '''
     self.new_email = Email(name='John', email_data='*****@*****.**')
Esempio n. 27
0
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()
Esempio n. 28
0
def add_cp_organization():
    """Add new organization
    When adding a new organization only the full name and abbreviation are
    required.

    **Example request**:

    .. sourcecode:: http

        POST /api/1.0/organizations HTTP/1.1
        Host: do.cert.europa.eu
        Accept: application/json
        Content-Type: application/json

        {
          "abbreviation": "BEREC1",
          "abuse_emails": [
            "*****@*****.**"
          ],
          "asns": [
            8194
          ],
          "contact_emails": [
            {
              "email": "*****@*****.**",
              "cp": true
            }
          ],
          "fqdns": [
            "berec.europa.eu"
          ],
          "full_name": "New Body of European Regulators for Electronic...",

          "group_id": 1,
          "ip_ranges": [
            "212.70.173.66/32",
            "212.70.173.67/32",
            "212.70.173.68/32"
          ],
          "mail_template": "EnglishReport",
          "mail_times": 3600,
          "old_ID": "64"
          "parent_org_id": 95
        }

    **Example response**:

    .. sourcecode:: http

        HTTP/1.0 201 CREATED
        Content-Type: application/json

        {
          "message": "Organization saved"
        }

    **Example validation error**:

    .. sourcecode:: http

        HTTP/1.0 400 BAD REQUEST
        Content-Type: application/json

        {
          "message": "'abbreviation' is a required property",
          "validator": "required"
        }

    :reqheader Accept: Content type(s) accepted by the client
    :reqheader API-Authorization: API key. If present authentication and
            authorization will be attempted.
    :resheader Content-Type: this depends on `Accept` header or request

    :<json string abbreviation: Abbreviation of organization
    :<json string full_name: Full official name of organization
    :<json string mail_template: Template used by AbuseHelper.
      Default is EnglishReport
    :<json integer mail_times: E-mailing time interval, in seconds.
       Default is 3600
    :<json string old_ID: ID used in the legacu excel sheet
    :<json integer group_id: Unique ID of the belonging group
    :<json object group: Group information
    :<json array abuse_emails: E-mail addresses
    :<json array contact_emails: Contact e-mail addresses
    :<jsonarr string email: E-mail address
    :<jsonarr boolean cp: CP access flag
    :<jsonarr boolean fmb: Functional mailbox marker
    :<json array asns: AS numbers
    :<json array fqdns: List of FQDNs
    :<json array ip_ranges: List of IP ranges used by this organization
    :<json integer parent_org_id: Parent organization ID
    :>json string message: Status message
    :>json integer id: organization ID

    :status 200: Organization details were successfully updated
    :status 400: Bad request
    :status 401: Authorization failure. The client MAY repeat the request with
        a suitable API-Authorization header field. If the request already
        included Authorization credentials, then the 401 response indicates
        that authorization has been refused for those credentials.
    :status 403: Access denied. Authorization will not help and the request
        SHOULD NOT be repeated.
    """
    o = Organization.fromdict(request.json)

    parent_org = Organization.query.get(o.parent_org_id)
    if not parent_org or not g.user.may_handle_organization(parent_org):
        abort(403)

    try:
        contact_emails = request.json.pop('contact_emails')
        for e in contact_emails:
            cp = e.get('cp', False)
            o.contact_emails.append(
                ContactEmail(
                    email_=Email(email=e['email']),
                    cp=cp))
    except KeyError as ke:
        print('No contact emails provided: {}'.format(ke))

    db.session.add(o)
    db.session.commit()
    return ApiResponse({'organization': o.serialize(),
            'message': 'Organization added'}, 201, \
           {'Location': url_for('cp.get_cp_organization', org_id=o.id)})
Esempio n. 29
0
def update_cp_organization(org_id):
    """Update organization details

    **Example request**:

    .. sourcecode:: http

        PUT /api/1.0/organizations HTTP/1.1
        Host: cp.cert.europa.eu
        Accept: application/json
        Content-Type: application/json

        {
          "abbreviation": "CERT-EU",
          "abuse_emails": ["*****@*****.**"],
          "asns": [5400],
          "contact_emails": [
            {
              "email": "*****@*****.**",
              "cp": true
            }
          ],
          "fqdns": ["cert.europa.eu"],
          "full_name": "Computer Emergency Response Team for EU...",
          "group": {
            "color": "#0033cc",
            "id": 1,
            "name": "Constituents"
          },
          "group_id": 1,
          "id": 185,
          "ip_ranges": [
            "212.8.189.16/28"
          ],
          "mail_template": "EnglishReport",
          "mail_times": 3600,
          "old_ID": "00",
        }

    **Example response**:

    .. sourcecode:: http

        HTTP/1.1 200 OK
        Content-Type: application/json

        {
          "message": "Organization saved"
        }

    **Example validation error**:

    .. sourcecode:: http

        HTTP/1.0 400 BAD REQUEST
        Content-Type: application/json

        {
          "message": "'abbreviation' is a required property",
          "validator": "required"
        }

    :reqheader Accept: Content type(s) accepted by the client
    :resheader Content-Type: this depends on `Accept` header or request

    :<json integer id: Unique ID of organization
    :<json string abbreviation: Abbreviation of organization
    :<json string full_name: Full official name of organization
    :<json string mail_template: Template used by AbuseHelper
    :<json integer mail_times: E-mailing time interval, in seconds
    :<json string old_ID: ID used in the legacu excel sheet
    :<json integer group_id: Unique ID of the belonging group
    :<json object group: Group information
    :<json array abuse_emails: E-mail addresses used to send abuse information
    :<json array contact_emails: Contact e-mail addresses
    :<jsonarr string email: E-mail address
    :<jsonarr boolean cp: CP access flag
    :<jsonarr boolean fmb: Functional mailbox marker
    :<json array asns: AS numbers
    :<json array fqdns: List of FQDNs
    :<json array ip_ranges: List of IP ranges used by this organization
    :>json string message: Status message

    :status 200: Organization details were successfully updated
    :status 400: Bad request
    :status 422: Validation error
    """
    o = Organization.query.filter(
        Organization.id == org_id
    ).first()
    if not o:
        return redirect(url_for('cp.add_cp_organization'))

    if not g.user.may_handle_organization(o):
        abort(403)

    untouchables_ = ['is_sla', 'mail_template', 'group_id', 'old_ID', 'group',
                     'group_id', 'parent_org_abbreviation']
    for k in untouchables_:
        request.json.pop(k, None)

    contact_emails = request.json.pop('contact_emails', [])
    abuse_emails = request.json.pop('abuse_emails', [])
    o.from_json(request.json)
    o.contact_emails = []
    o.abuse_emails = []

    for ac in abuse_emails:
        o.abuse_emails.append(ac)

    for e in contact_emails:
        cp = e.get('cp', False)
        fmb = e.get('fmb', False)
        o.contact_emails.append(
            ContactEmail(
                email_=Email(email=e['email']),
                fmb=fmb,
                cp=cp))

    db.session.add(o)
    db.session.commit()
    return ApiResponse({'message': 'Organization saved'})