LoginSignup
9
16

More than 5 years have passed since last update.

LaravelでPHPMailerを導入してメール送信する手順

Last updated at Posted at 2016-09-08

初めに

PHPでメール送信したい場合はすぐに思いつくのはmail()関数だが細かい実装に陥る。Laravelではメール送信はもっと簡単にさせられて数行のコードでいけるようです。詳細に知りたい方は以下のリンクをご参照ください。

Laravel > Mail

その以外にあるもう一つのフレキシブルな方法が皆によく使われていると思います。それはPHPMailerというOpenSourceライブラリーです。

PHPMailer

Laravelのメール送信ライブラリーに慣れていないですがPHPMailerをこの前ずっと使っていて好きになったのでLaravelでもPHPMailerを使えるようにしたい方がいると思います。導入するのは難しくないですが素人に向けて手順を書かせていただきます。

導入手順

ComposerでPHPMailerを導入するのができます。

composer require phpmailer/phpmailer

composerを使ったことがない方は以下のリンクに遷移してComposer.pharをダウンロードして自分が持っているLaravelプロジェクトにおいておいてください。composer.pharをプロジェクトのフォルダーにおいてからいかのように実行してphpmailerを導入します。

php composer.phar require phpmailer/phpmailer

メール送信する

導入は完了したら通常にコーディングするだけでいいです。例えばControllerの中にGoogleのSMTPサービスを利用するsendMail関数は以下のように定義して

//PHPMailer Object
$mail = new PHPMailer;

//Enable SMTP debugging. 
$mail->SMTPDebug = 3;                               
//Set PHPMailer to use SMTP.
$mail->isSMTP();            
//Set SMTP host name                          
$mail->Host = "smtp.gmail.com";
//Set this to true if SMTP host requires authentication to send email
$mail->SMTPAuth = true;                          
//Provide username and password     
$mail->Username = "name@gmail.com";                 
$mail->Password = "super_secret_password";                           
//If SMTP requires TLS encryption then set it
$mail->SMTPSecure = "tls";                           
//Set TCP port to connect to 
$mail->Port = 587;                           

//From email address and name
$mail->From = "from@yourdomain.com";
$mail->FromName = "Full Name";

//To address and name
$mail->addAddress("recepient1@example.com", "Recepient Name");
$mail->addAddress("recepient1@example.com"); //Recipient name is optional

//Address to which recipient will reply
$mail->addReplyTo("reply@yourdomain.com", "Reply");

//CC and BCC
$mail->addCC("cc@example.com");
$mail->addBCC("bcc@example.com");

//Send HTML or Plain Text email
$mail->isHTML(true);

$mail->Subject = "Subject Text";
$mail->Body = "<i>Mail body in HTML</i>";
$mail->AltBody = "This is the plain text version of the email content";

//Attachments
$mail->addAttachment("file.txt", "File.txt");        
$mail->addAttachment("images/profile.png"); //Filename is optional


if(!$mail->send()) 
{
    Log::info("Mailer Error: " . $mail->ErrorInfo);
} 
else 
{
    Log::info("Message has been sent successfully");
}

smtp connect() failed
GMailのSMTPにアクセスする際に異常のエラーが発生したらまずローカル環境の設定を確認するのは必要となります。

  • サーバーはアクセス可能状態であるかどうか: ping smtp.gmail.com
  • サービスはまだ生きているかどうか telnet smtp.gmail.com 587
  • Gmail自体の設定はシステムからのアクセスを許可しているかどうか

参考リンク

以上です。

9
16
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
9
16