LoginSignup
0
2

PHP: PHPMailer の使い方

Last updated at Posted at 2021-04-19

こちらでは、 SwiftMailer を使いましたが、PHPMailer を使ってみました。

ライブラリーのインストール

sudo apt install libphp-phpmailer
sudo apt install php-vlucas-phpdotenv

プログラム

phpmailer_ex01.php
#! /usr/bin/php

<?php
// ------------------------------------------------------------------
//	phpmailer_ex01.php
//
//				 	Apr/19/2021
//
// ------------------------------------------------------------------
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
require_once '/usr/share/php/libphp-phpmailer/autoload.php';
require_once '/usr/share/php/Dotenv/autoload.php';

$dotenv = Dotenv\Dotenv::createImmutable(__DIR__);
$dotenv->load();

$from = $_ENV['FROM'];
$to = $_ENV['TO'];

date_default_timezone_set('Asia/Tokyo');
$today = date ("Y-m-d");
$now = date("Y年m月d日 H時i分s秒");


$mailer = new PHPMailer;

$mailer->IsSMTP();
$mailer->Host = $_ENV['SERVER'];
$mailer->SMTPAuth = true;
$mailer->Username = $_ENV['USR'];
$mailer->Password = $_ENV['PASSWORD'];
$mailer->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
$mailer->Port = $_ENV['PORT'];

$mailer->CharSet = 'utf-8';

$str_out = "";
$str_out .= 'This is TEST.' . PHP_EOL;
$str_out .= 'こんにちは。' . PHP_EOL;
$str_out .= '晴れています。' . PHP_EOL;
$str_out .= $today . PHP_EOL;
$str_out .= $now . PHP_EOL;

$mailer->setFrom($from);
$mailer->addAddress($to);
$mailer->Subject = 'Test Apr/19/2021 ' . date ("H:i:s") ;
$mailer->Body = $str_out;

if(!$mailer->send()) {
	echo 'Email is not sent.\n';
	echo 'Email error: ' . $mailer->ErrorInfo;
} else {
	echo '*** Email has been sent. ***' . PHP_EOL;
}

// ------------------------------------------------------------------
?>
.env
SERVER = 'hi-ho.mose-mail.jp'
PORT = 587
USR = '****@hi-ho.ne.jp'
PASSWORD = '****'
FROM = '****@hi-ho.ne.jp'
TO = 'sample@example.com'

確認したバージョン

$ php --version
PHP 8.2.10-2ubuntu1 (cli) (built: Sep  5 2023 14:37:47) (NTS)
Copyright (c) The PHP Group
Zend Engine v4.2.10, Copyright (c) Zend Technologies
    with Zend OPcache v8.2.10-2ubuntu1, Copyright (c), by Zend Technologies
0
2
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
0
2