LoginSignup
0
1

More than 5 years have passed since last update.

【備忘録】PHPのメール送信

Last updated at Posted at 2019-03-16

メールフォームもどきの実装の備忘録です。

※2019/03/16追記:
コメントにもありますが、今回の用途は、限られたローカルでの利用だったため、
本番利用できるようなものではないです。

javascript

POSTしている箇所(javascript)

submit(){
  const data = {
    from: "hoge@gmail.com",
    to: "fuga@gmail.com",
    title: "メールのタイトル",
    body: "メールの本文"
  };

  const xml = new XMLHttpRequest();
  xml.open("POST", "control_unit.php", false);
  // HTTP リクエストヘッダーの値を設定。setRequestHeader: openの後、sendの前に記述する。
  xml.setRequestHeader("Content-Type", "application/json");
  xml.send(JSON.stringify(data));
}

php

値を受け取ってメールとして送信(php)

$request = json_decode(file_get_contents('php://input'), true);

class mail {
  public function sendMail() {
    global $request;
    mb_language("Japanese"); // 文字化け対応
    mb_internal_encoding("UTF-8"); // 文字化け対応
    $email = $request["from"];
    $subject = $request["title"];
    $body = $request["body"]."\n";
    $to = $request["to"];
    $from = "From: $email\r\nReturn-Path: ".$email;

    mb_send_mail($to, $subject, $body, $from, "-f ".$email);
  }
}

$mail_class = new mail();
echo $mail_class -> sendMail();

XAMPPの設定(windows)

xampp/php/php.iniの設定

;設定前
;sendmail_path =

;設定後
sendmail_path = "\"C:\xampp\sendmail\sendmail.exe\" -t"

xampp/sendmail/sendmail.iniの設定

;outlookの場合
smtp_server=smtp.office365.com
smtp_port=587
auth_username=各自のアドレス
auth_password=各自のパスワード

上記設定したら、Apacheの再起動を忘れずに。

macはSMTP認証なしで送れたけど、windowsのそこらへんがよくわからなかった。

0
1
2

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
1