"Diary" インターネットさんへの恩返し

いつもソースコードコピペばかりなので,みなさまへ少しばかりの恩返しを

ConohaでPHPからメールアドレスを作る方法(作ると同時に転送設定も)

f:id:azumami:20190125012325p:plain
Conohaのメールサービス便利ですねぇ~。(よくサービス障害が起こるのがんんんん、、て感じですが)

レンタルサーバでWebサーバとメールがセットになっているのが一般的ですが、メール機能だけ欲しい場合にかなり便利。

そんなこんなで、メールシステムとしてよく使うConohaのメールサービスですがAPI経由でメールアドレスが作れたりいろんなことができるので今回はメールアドレス作成APIで、Web画面からメールアドレス作成+転送設定をするプログラムを作りました。

[参照]
自動実行作成 - Mail API v1.0 / ConoHa API

準備

対象のメールサービス契約+ドメイン割り当て

手順は割愛します。

API有効化

conohaでAPIを使うユーザを作成、作成された内容を控えます。ログインすると、左メニューにAPIってのがあるので、それをクリックしてユーザを作ります。
作ったら以下の情報がでるので控えます。

・テナントID
APIユーザ名
APIユーザパスワード
・エンドポイント>Mail Service

あと、作りたいメルアドのドメインIDを取得しないといけないので以下をお手本に取得します。
ConoHa の メール API でアドレスの登録・一覧・削除をする。 - Qiita

ドメインID

それぞれ、こんな感じでConfigとかに書いておきます。

    conoha_ep_token: "https://identity.tyo1.conoha.io/v2.0/tokens"
    conoha_ep_email: "https://mail-hosting.tyo1.conoha.io/v1/emails"
    conoha_ep_forwarding: "https://mail-hosting.tyo1.conoha.io/v1/forwarding"
    conoha_tenant_id: "xxxxxxxxx"
    conoha_username: "xxxxxxxxx"
    conoha_password: "xxxxxxxxx"
    conoha_domain_id: ""

プログラム

フロントからajaxで命令して、以下のバックエンドのコード処理する感じです。例ではSymfonyでやっているのでSymfonyの書き方で書いてます。

    public function emailCreateAction(Request $request)
    {

        $prefix = '作りたいメールアドレスの@前の部分';
        $address = '';

        if($prefix){
            //トークンは3日ぐらいしか有効じゃないので、処理するたびトークンを取ってきます。
            $token = $this->getConohaAPIToken();

            if(property_exists($token,'error')) {
                $error   = 500;
                $message = $token->error->message;
            }else{

                //メールアドレス作成処理
                try{

                    $emailToken = $this->createEmailAddress($prefix,$token->access->token->id);

                    //作成失敗したとき
                    if(property_exists($emailToken,'error')){
                        $error = 500;
                        $message = $emailToken->error->details;

                    //作成成功したとき
                    }else{

                        $address = $emailToken->email->username;

                        //メールアドレス転送設定処理
                            $rs = $this->addForwardEmail($emailToken->email->email_id,$token->access->token->id);

                            if($rs['error'] == 0){
                                $error = 200;
                                $message = $address."を作成しました";
                            }else{
                                $error = 500;
                                $message = $address."を作成しましたが転送設定が失敗しました。";
                            }
                        }
                    }
                }catch (\Exception $e){
                    $error = 500;
                    $message = $e->getMessage();
                }
            }

        }else{
            $error = 1;
            $message = 'ドメイン名の前の箇所が不適切なためメールアドレスが作成できませんでした。';
        }

        $data = [
            'message' => $message,
            'email' => $address,
        ];

        return new JsonResponse($data, $error);

    }

    private function addForwardEmail($emailUuid,$tokenId){

        $ch = curl_init();

        try{

            $headers = array(
                "Accept: application/json",
                "Content-type: application/json",
                "X-Auth-Token: ".$tokenId
            );

            $data = [
                "email_id" => $emailUuid,
                "address" => "転送先メールアドレス",
            ];

            curl_setopt($ch, CURLOPT_URL, $this->getParameter('conoha_ep_forwarding'));
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

            $token_result = curl_exec($ch);
            $token = json_decode($token_result);

            $rs = [];
            $rs['error'] = 0;
            $rs['message'] = "";

        }catch (\Exception $e){
            $rs['error'] = 1;
            $rs['message'] = "メールアドレス転送設定中にエラー";
        }

        curl_close($ch);

        return $rs;

    }



    private function createEmailAddress($prefix,$tokenId){

        $address = $prefix."@ドメイン";

        $headers = array(
            "Accept: application/json",
            "Content-type: application/json",
            "X-Auth-Token: ".$tokenId
        );

        $data = [
            "domain_id" => $this->getParameter('conoha_domain_id'),
            "email" => $address,
            "password" => "パスワード"
        ];

        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, $this->getParameter('conoha_ep_email'));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

        $token_result = curl_exec($ch);
        $token = json_decode($token_result);

        curl_close($ch);

        return $token;
    }


    public function _getConohaAPIToken()
    {

        $url = $this->getParameter('conoha_ep_token');

        $headers = array(
            "Accept: application/json",
            "Content-type: application/json",
        );

        $data = [
            "auth" => [
                "passwordCredentials" => [
                    "username" => $this->getParameter('conoha_username'),
                    "password" => $this->getParameter('conoha_password'),
                ],
                "tenantId" => $this->getParameter('conoha_tenant_id'),
            ]
        ];

        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

        $token_result = curl_exec($ch);
        $token = json_decode($token_result);

        curl_close($ch);

        return $token;

    }