2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

CodeIgniter3でPHPMailerを使ってメールを送る

Posted at

仕事で必要だったので超急ぎで作りました。
メールサーバのホスト名だのパスワードだのはconfigファイルから読み込むべきだと思いますが、
まあそのあたりはよしなに

PHPMailerはcomposerとかなにかで読み込んでください

ソースコード

これを /application/helpers/phpmailer_helper.php としてサーバに置きます

/application/helpers/phpmailer_helper.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class PHPMailerHelper
{
    private $_mail;

    public function __construct()
    {
        $this->_mail = $this->_init();
    }

    private function _init()
    {
        $mail = new PHPMailer\PHPMailer\PHPMailer(true); // enable phpmailer debug when true
        $mail->Debugoutput = function($str, $level) { syslog(LOG_ERR, "PHP Mailer:" . $str); };
        $mail->SMTPDebug = 3;

        $mail->isSMTP();
        $mail->setFrom('from@example.com', mb_encode_mimeheader('From Name'));
        $mail->CharSet = 'UTF-8';
        $mail->Wordwrap = 76; // It equals CodeIgniter word wrapping length @link https://codeigniter.jp/user_guide/3/libraries/email.html

        $mail->Host = 'email-smtp.ap-northeast-1.amazonaws.com'; // AWS SESの場合
        $mail->Port = 587; // ssl:465 tls:587
        $mail->Username = 'SMTP_USER_NAME_HERE';
        $mail->Password = 'SMTP_PASSWORD_HERE';

        $mail->SMTPAuth = true;
        $mail->SMTPSecure = 'tls'; // tls or ssl

        // remove this commentout to disable ssl validate if you need
        //$mail->SMTPOptions = array(
        //    'ssl' => array(
        //        'verify_peer' => false,
        //        'verify_peer_name' => false,
        //        // 'allow_self_signed' => true
        //    )
        //);

        return $mail;
    }

    /**
     * Override mailer from address and name if you need
     */
    public function setFrom($email, $name = "")
    {
        //$this->_mail->setFrom('from@example.com', mb_encode_mimeheader('From Name'));
        $this->_mail->setFrom($email, mb_encode_mimeheader($name));
    }

    public function test()
    {
        $this->_mail->addAddress('myname@example.com');
        $this->_mail->Subject = '[Sample] これはサンプルメールです';
        $this->_mail->isHTML(false);
        $this->_mail->Body = "サンプルメール\nサンプルメール\nサンプルメール\n\nサンプルメール";

        $isSent = $this->_mail->Send();

        return $isSent; // boolean
    }

    public function send($toAddresses, $subject = "", $message = "", $attachement = [])
    {
        $name = '';

        if(is_array($toAddresses)){
            foreach($toAddresses as $email) {
                $this->_mail->addAddress($email, $name);
            }
        }
        else {
            $email = $toAddresses;
            $this->_mail->addAddress($email, $name);
        }

        $this->_mail->Subject = $subject;

        $this->_mail->isHTML(false);
        $this->_mail->Body = $message;

        if (isset($attachment) && is_array($attachement)) {
            $this->_mail->addStringAttachment($attachement['value'], $attachement['name'], 'base64', $attachement['type']);
        }

        $isSent = $this->_mail->Send();

        return $isSent; // boolean
    }
}

使い方

使いたいControllerにこんな感じに記述します

/application/controllers/Contact.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Contact extends CI_Controller
{
	public function __construct()
	{
		parent::__construct();
		
		$this->load->helper('phpmailer');
	}

	public function test()
	{
		$mail = new PHPMailerHelper();
		$isSent = $mail->test();

		if($isSent){
			die("sent");
		}
		else {
			die("not send");
		}
	}

	public function test2()
	{
		$mail = new PHPMailerHelper();
		$isSent = $mail->send('myname@example.com', "件名", "本文");

		if($isSent){
			die("sent");
		}
		else {
			die("not send");
		}
	}

	public function test3()
	{
		$mail = new PHPMailerHelper();

		$toAddresses = array(
			'myname@example.com',
			'myname2@example.com'
		);

		$isSent = $mail->send($toAddresses, "件名", "本文");

		if($isSent){
			die("sent");
		}
		else {
			die("not send");
		}
	}

確認方法

ブラウザでページにアクセスしたらメールが届くと思います(メールサーバの設定が正しければ)

https://www.example.com/contact/test1
https://www.example.com/contact/test2
https://www.example.com/contact/test3
2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?