новый e-mail аккаунт в сPanel

 
 
 
Сообщения:3874
Народ, кто-нибудь знает как создать новый e-mail аккаунт в сPanel программно?

Существуют ли какие-то программные интерфейсы к этой панеле?
 
 
Сообщения:3874
Мда ... я всетаки сделал ... но получилось только через http запрос

    
       
       /**
     * The full URL to the host where cpanel is installed (with scheme and
     * port).<br />
     * (e.g http://domain:2082)
     */
    public static final String CPANEL_URL = "mail.system.cpanel_account_manager.cpanel_url";
    /**
     * The full URI to the doaddpop.html file (including context).<br />
     * (e.g /frontend/&lt;theme&gt;/mail/doaddpop.html)
     */
    public static final String DOADDPOP_URI = "mail.system.cpanel_account_manager.doaddpop.url";
    /**
     * User name for the connection authentication
     */
    public static final String AUTH_ACCOUNT = "mail.system.cpanel_account_manager.auth.account";
    /**
     * User password for the connection authentication
     */
    public static final String AUTH_PASSWORD = "mail.system.cpanel_account_manager.auth.password";


    ....


    public void createMailAccount(String userName, String userPassword, long quota) throws AccountAlreadyExistsException,
            TooBigQuotaException, InvalidDomainException, InvalidPasswordException, InvalidQuotaException,
            MailAccountManagerSystemException {
        PostMethod authPost = null;
        try {
            // Check quota size
            long maxQuotaSize = this.settings.getMaximumQuotaSize();
            if (maxQuotaSize > 0) if (quota > maxQuotaSize) throw new TooBigQuotaException("The supplied quota size [" + quota
                    + "] is greater then maximum permited quota size [" + maxQuotaSize + "]");
            if (quota < 0) throw new InvalidQuotaException("Invalid quota [" + quota + "]");
            // Getting required properties from global settings
            String domain = this.settings.getPrimaryEmailDomain();

            System.out.println("Setup URL: " + this.settings.getProperty(CPANEL_URL));
            // Getting service specific properties
            URI cpanelURL = new URI(this.settings.getProperty(CPANEL_URL), false);
            HttpClient client = new HttpClient();
            HostConfiguration hostConfiguration = client.getHostConfiguration();
            client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
            hostConfiguration.setHost(cpanelURL);

            // Set preemptive authorization to reducing the overhead of making
            // the connection
            client.getParams().setAuthenticationPreemptive(true);

            System.out.println("Setup auhtentication credentials: " + this.settings.getProperty(AUTH_ACCOUNT) + ", "
                    + this.settings.getProperty(AUTH_PASSWORD));

            Credentials defaultCreds = new UsernamePasswordCredentials(this.settings.getProperty(AUTH_ACCOUNT), this.settings
                    .getProperty(AUTH_PASSWORD));
            client.getState().setCredentials(
                    new AuthScope(cpanelURL.getHost(), AuthScope.ANY_PORT, AuthScope.ANY_REALM, AuthScope.ANY_SCHEME),
                    defaultCreds);

            // Creating data, to be submited via POST method
            System.out.println("Preparing service URI: " + this.settings.getProperty(DOADDPOP_URI));
            authPost = new PostMethod(this.settings.getProperty(DOADDPOP_URI));
            // Prepare login parameters
            NameValuePair emailParameter = new NameValuePair("email", constructUserEmail(userName));
            NameValuePair domainParameter = new NameValuePair("domain", domain);
            NameValuePair passwordParameter = new NameValuePair("password", userPassword);

            // Converting Quota to MegaBytes
            Size quotaMB = new Size(quota, SizeUnit.BYTES);
            quotaMB = quotaMB.convertTo(SizeUnit.MEGABYTES);

            if ( quotaMB.round() < 1 ) throw new InvalidQuotaException("Invalid quota [" + quota + "] MB. Quota must be at least 1 MB");
            
            System.out.println("Quota is: " + quotaMB.round() + " MB");

            NameValuePair quotaParameter = new NameValuePair("quota", new Long(quotaMB.round()).toString());
            authPost.setRequestBody(new NameValuePair[] { emailParameter, domainParameter, passwordParameter, quotaParameter });

            int statusCode = client.executeMethod(authPost);

            Header[] headers = authPost.getResponseHeaders();

            System.out.println("HEADERS ------------------------------- ");
            if (headers != null) for (int i = 0; i < headers.length; i++) {
                System.out.println(headers[i].toExternalForm());
            }

            if (statusCode == HttpStatus.SC_OK) {
                // We have valid response, try to parse response
                System.out.println("We have VALID response!");
                String response = MailUtils.getHTMLAsText(authPost.getResponseBodyAsStream(), authPost.getResponseCharSet());
                System.out.println("Response is: ******************************** \n" + response
                        + "\n **************************");

                // Invalid domain
                if (response.indexOf("you do not have access to the domain") > -1) throw new InvalidDomainException(
                        "Default domain [" + domain + "] could not be used to create mail account!");
                // Account already exists
                if (response.indexOf("already exists!") > -1) throw new AccountAlreadyExistsException("Account ["
                        + constructUserEmail(userName) + "] already exists!");
                // Check password validity
                if (response.indexOf("You must specify a password.") > -1) throw new InvalidPasswordException(
                        "Password is invalid!");
                // Check other failers
                if (response.indexOf("Ignore any messages of success") > -1) throw new MailAccountManagerException(
                        "Account could not be created due to the unknown error!");
                // Check if created
                if (response.indexOf("megs was successfully created.") == -1) throw new MailAccountManagerException(
                        "Invalid response received!");
            } else {
                System.out.println("Invalid status code received!");
                System.out.println("BODY ------------------------------- ");
                System.out.println(authPost.getResponseBodyAsString());

                throw new MailAccountManagerException("Invalid status code received!");
            }

        } catch (HttpException ex) {
            throw new MailAccountManagerSystemException("Fatal HTTP protocol violation!", ex);
        } catch (IOException ex) {
            throw new MailAccountManagerSystemException("Fatal transport error!", ex);
        } catch (MailAccountManagerSystemException ex) {
            throw ex;
        } catch (Exception ex) {
            throw new MailAccountManagerSystemException(ex);
        } finally {
            if (authPost != null) authPost.releaseConnection();
        }

    }



Quote:

// Converting Quota to MegaBytes
Size quotaMB = new Size(quota, SizeUnit.BYTES);
quotaMB = quotaMB.convertTo(SizeUnit.MEGABYTES);


Переводит размер из байтов в мегабайты (код классов не приводится).

this.settings - это instance класса, который хранит настройки для мыла в property файле.
 
Модераторы:Нет
Сейчас эту тему просматривают:Нет