【PHP】メールを送信する – 5分で分かる –

その他

メールの送信例

こんなメールをWebから送ります。

まずは、ソースを見よう

  • $footerに「ほげほげ株式会社」あるので、URLなどを必要に応じて修正します。
  • $to、$subject、$from、$from_nameを必要に応じて修正します。
  • 黄色の下線は、メール本文です。(ヒアドキュメントと言われるもを使用しています)必要に応じて修正します。もちろん変数、{$userName}、{$mailAdress}も使用できます。
<?php

class Mail2
{
 //フッター
  public  $footer;

  //コンストラクタ
  function Mail2()
  {
     $this->footer  = "---------------------------------------------\n";
     $this->footer .= " ほげほげ株式会社\n";
     $this->footer .= " URL : https://hogehoge.co.jp  \n";
     $this->footer .= "---------------------------------------------\n";
  }

  function SendRegistToAdmin($userName,$mailAdress)
  {
    //言語と文字コードの使用宣言
    mb_language("ja");
    mb_internal_encoding("UTF-8");

    // 宛先
    $to = "hege@hogehoge.co.jp";

    // 件名
    $subject = "【テスト】テスト送信";

    // 送信元メールアドレス
    $from =  "contact@hogehoge.co.jp";

    // 送信者名
    $from_name = "ほげほげサポート";

    // 送信者情報の設定
    $header = '';
    $header .= "Content-Type: text/plain \r\n";
    $header .= "Return-Path: " . $from . " \r\n";
    $header .= "From: " . $from ." \r\n";
    $header .= "Sender: " . $from ." \r\n";
    $header .= "Reply-To: " . $from . " \r\n";
    $header .= "Organization: " . $from_name . " \r\n";
    $header .= "X-Sender: " . $from . " \r\n";
    $header .= "X-Priority: 3 \r\n";

    //ヒアドキュメント
    $body=<<<EOF
    ユーザー登録が行われました。

    登録者の名前:{$userName}
    登録者のメールアドレス:{$mailAdress}

    EOF;

    $body .=  $this->footer;

    mb_send_mail($to, $subject, $body, $header);
  }
}

?>

使ってみる

以下のような感じで使用できます。

<?php
$mail = new Mail2; $mail->SendRegistToAdmin($username,$email)
?>
スポンサーリンク
その他
Engineerをフォローする
レンサバ