【3分で完了】CodeIgniterをつかって『Gmailからメール送信する』方法
CodeIgniterでGmailから送信機能を実装するする方法です。
備忘録的なまとめです。
それでは書いていきます。
Emailクラスとコンストラクタを作成する
新規作成ファイル:application/controller/email.php
class Email extends CI_Controller{
function __construct(){
parent::__construct();
}
コンストラクタの説明は以下がわかりやすいです。
PHP classの教室
独学PHP はじめよう、PHPでオブジェクト指向
GmailのConfigオプションを作成して、EmailライブラリでConfigを読み込む
編集ファイル:application/controller/email.php
function index(){
$config = array(
"protocol" =>"smtp",
"smtp_host" => "ssl://smtp.googlemail.com",
"smtp_port"=>465,
"smtp_usre"=>"あなたのGmail",
"smtp_pass"=>"あなたのGmailのパスワード"
);
$this->load->library("email", $config);
$this->email->set_newline("rn"); //エラー回避のおまじない
}
メール送信に必要な情報をハードコーディングしていく
編集ファイル:application/controller/email.php
$this->load->library("email", $config);
$this->email->set_newline("rn"); //エラー回避のおまじない
$this->email->from("送信元のメールアドレス", "Your name");
$this->email->to("宛先のメールアドレス");
$this->email->subject("This is an email test");
$this->email->message("it it working:)");
メール送信時のサクセスメッセージを表示する
編集ファイル:application/controller/email.php
if($this->email->send()){
echo "Your email was sent.";
}else{
show_error($this->email->print_debugger()); //エラー表示用のデバッガーを起動する
}
以上で簡単なメール送信ができるようになります。
おまけ:コードをきれいにする
新規作成ファイル:application/config/email.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
$config["protocol"] = "smtp";
$config["smtp_host"] = "ssl://smtp.googlemail.com";
$config["smtp_port"] = "465";
$config["smtp_usre"] = "あなたのEmail";
$config["smtp_pass"] = "あなたのGmailのパスワード";
つぎに、Emailコントローラーを以下のように書き換えます。
function index(){
// $config = array(
// "protocol" =>"smtp",
// "smtp_host" => "ssl://smtp.googlemail.com",
// "smtp_port"=>465,
// "smtp_usre"=>"[email protected]",
// "smtp_pass"=>"gwtHA8XMGWVCgWnnFseVEgNWw8iLHX"
// );
// $this->load->library("email", $config);
$this->load->library("email");
以上でコードを見やすくすることができました( ◜◡ ̄)
※P.S:無料メルマガで発信中:過去の僕は「ブログ発信で5億円」を稼ぎました。次は「30億円」を目指します。挑戦しつつ、裏側の思考を「メルマガ」から発信します。不満足なら1秒で解約できます。無料登録は「こちら」です。