WebサイトでPHPを使用していますが、メール機能を追加したいと考えています。
WAMPSERVERをインストールしました。
PHPを使用してメールを送信するにはどうすればよいですか?
WebサイトでPHPを使用していますが、メール機能を追加したいと考えています。
WAMPSERVERをインストールしました。
PHPを使用してメールを送信するにはどうすればよいですか?
回答:
PHPのmail()関数を使用することは可能です。ローカルサーバーではメール機能が機能しないことに注意してください。
<?php
$to      = 'nobody@example.com';
$subject = 'the subject';
$message = 'hello';
$headers = 'From: webmaster@example.com' . "\r\n" .
    'Reply-To: webmaster@example.com' . "\r\n" .
    'X-Mailer: PHP/' . phpversion();
mail($to, $subject, $message, $headers);
?> 
参照:
https://github.com/PHPMailer/PHPMailerで PHPMailerクラスを使用することもできます。
メール機能を利用したり、SMTPサーバーを透過的に利用したりできます。また、HTMLベースの電子メールと添付ファイルを処理するため、独自の実装を作成する必要はありません。
このクラスは安定しており、Drupal、SugarCRM、Yii、Joomlaなどの他の多くのプロジェクトで使用されています。
上記のページの例を次に示します。
<?php
require 'PHPMailerAutoload.php';
$mail = new PHPMailer;
$mail->isSMTP();                                      // Set mailer to use SMTP
$mail->Host = 'smtp1.example.com;smtp2.example.com';  // Specify main and backup SMTP servers
$mail->SMTPAuth = true;                               // Enable SMTP authentication
$mail->Username = 'user@example.com';                 // SMTP username
$mail->Password = 'secret';                           // SMTP password
$mail->SMTPSecure = 'tls';                            // Enable encryption, 'ssl' also accepted
$mail->From = 'from@example.com';
$mail->FromName = 'Mailer';
$mail->addAddress('joe@example.net', 'Joe User');     // Add a recipient
$mail->addAddress('ellen@example.com');               // Name is optional
$mail->addReplyTo('info@example.com', 'Information');
$mail->addCC('cc@example.com');
$mail->addBCC('bcc@example.com');
$mail->WordWrap = 50;                                 // Set word wrap to 50 characters
$mail->addAttachment('/var/tmp/file.tar.gz');         // Add attachments
$mail->addAttachment('/tmp/image.jpg', 'new.jpg');    // Optional name
$mail->isHTML(true);                                  // Set email format to HTML
$mail->Subject = 'Here is the subject';
$mail->Body    = 'This is the HTML message body <b>in bold!</b>';
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
if(!$mail->send()) {
    echo 'Message could not be sent.';
    echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
    echo 'Message has been sent';
}
use PHPMailer\PHPMailer\PHPMailer; use PHPMailer\PHPMailer\Exception; require_once('src/PHPMailer.php'); require_once('src/Exception.php');
                    html形式のメールに関心がある場合Content-type: text/html;は、ヘッダーを渡してください。例:
// multiple recipients
$to  = 'aidan@example.com' . ', '; // note the comma
$to .= 'wez@example.com';
// subject
$subject = 'Birthday Reminders for August';
// message
$message = '
<html>
<head>
  <title>Birthday Reminders for August</title>
</head>
<body>
  <p>Here are the birthdays upcoming in August!</p>
  <table>
    <tr>
      <th>Person</th><th>Day</th><th>Month</th><th>Year</th>
    </tr>
    <tr>
      <td>Joe</td><td>3rd</td><td>August</td><td>1970</td>
    </tr>
    <tr>
      <td>Sally</td><td>17th</td><td>August</td><td>1973</td>
    </tr>
  </table>
</body>
</html>
';
// To send HTML mail, the Content-type header must be set
$headers  = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
// Additional headers
$headers .= 'To: Mary <mary@example.com>, Kelly <kelly@example.com>' . "\r\n";
$headers .= 'From: Birthday Reminder <birthday@example.com>' . "\r\n";
$headers .= 'Cc: birthdayarchive@example.com' . "\r\n";
$headers .= 'Bcc: birthdaycheck@example.com' . "\r\n";
// Mail it
mail($to, $subject, $message, $headers);
詳細については、phpのメール機能を確認してください。
PEARメールパッケージPear Mail Pageもご覧ください。
組み込みの標準のmail()関数よりも少し堅牢であるようです(標準の関数では不十分な場合)。
これは、このページからの抜粋であり、使用方法を示しています。 PEARメールsend()の使用法
<?php
    include('Mail.php');
    $recipients = 'joe@example.com';
    $headers['From']    = 'richard@example.com';
    $headers['To']      = 'joe@example.com';
    $headers['Subject'] = 'Test message';
    $body = 'Test message';
    $smtpinfo["host"] = "smtp.server.com";
    $smtpinfo["port"] = "25";
    $smtpinfo["auth"] = true;
    $smtpinfo["username"] = "smtp_user";
    $smtpinfo["password"] = "smtp_password";
    // Create the mail object using the Mail::factory method
    $mail_object =& Mail::factory("smtp", $smtpinfo); 
    $mail_object->send($recipients, $headers, $body);
?> Mail.php私の例で参照されているファイルは、Pear Mailパッケージの一部です。Pear Mailパッケージをダウンロードしてインストールすると、を含めることができますMail.php。上記の「Pear Mail Page」リンクをクリックすると、ダウンロードリンクが表示されます。
                    最近のほとんどのプロジェクトでは、Swiftメーラーを使用しています。これは、メールを送信するための非常に柔軟でエレガントなオブジェクト指向のアプローチであり、人気のあるSymfonyフレームワークとTwigテンプレートエンジンを提供してくれたのと同じ人々によって作成されました。
require 'mail/swift_required.php';
$message = Swift_Message::newInstance()
    // The subject of your email
    ->setSubject('Jane Doe sends you a message')
    // The from address(es)
    ->setFrom(array('jane.doe@gmail.com' => 'Jane Doe'))
    // The to address(es)
    ->setTo(array('frank.stevens@gmail.com' => 'Frank Stevens'))
    // Here, you put the content of your email
    ->setBody('<h3>New message</h3><p>Here goes the rest of my message</p>', 'text/html');
if (Swift_Mailer::newInstance(Swift_MailTransport::newInstance())->send($message)) {
    echo json_encode([
        "status" => "OK",
        "message" => 'Your message has been sent!'
    ], JSON_PRETTY_PRINT);
} else {
    echo json_encode([
        "status" => "error",
        "message" => 'Oops! Something went wrong!'
    ], JSON_PRETTY_PRINT);
}Swiftメーラーの使用方法の詳細については、公式ドキュメントを参照してください。
Swift_MailTransportドキュメンテーションへのリンクが言うときあなたは言ったSwift_SendmailTransport。古いバージョンのSwift Mailerを参照していたのでしょうか、それともタイプミスですか、それとも私は何かを誤解していますか?サーバーにphp7がないため、古いバージョンのswift-mailerをインストールする必要があります。そのため、現在のバージョンのドキュメントが古いバージョンのパッケージに同梱されるかどうかを知る必要があります。ありがとう。
                    これは、メール機能を使用してプレーンテキストのメールを送信するための非常に基本的な方法です。
<?php
$to = 'SomeOtherEmailAddress@Domain.com';
$subject = 'This is subject';
$message = 'This is body of email';
$from = "From: FirstName LastName <SomeEmailAddress@Domain.com>";
mail($to,$subject,$message,$from);完全なコード例...
一度お試しください。
<?php
// Multiple recipients
$to = 'johny@example.com, sally@example.com'; // note the comma
// Subject
$subject = 'Birthday Reminders for August';
// Message
$message = '
<html>
<head>
  <title>Birthday Reminders for August</title>
</head>
<body>
  <p>Here are the birthdays upcoming in August!</p>
  <table>
    <tr>
      <th>Person</th><th>Day</th><th>Month</th><th>Year</th>
    </tr>
    <tr>
      <td>Johny</td><td>10th</td><td>August</td><td>1970</td>
    </tr>
    <tr>
      <td>Sally</td><td>17th</td><td>August</td><td>1973</td>
    </tr>
  </table>
</body>
</html>
';
// To send HTML mail, the Content-type header must be set
$headers[] = 'MIME-Version: 1.0';
$headers[] = 'Content-type: text/html; charset=iso-8859-1';
// Additional headers
$headers[] = 'To: Mary <mary@example.com>, Kelly <kelly@example.com>';
$headers[] = 'From: Birthday Reminder <birthday@example.com>';
$headers[] = 'Cc: birthdayarchive@example.com';
$headers[] = 'Bcc: birthdaycheck@example.com';
// Mail it
mail($to, $subject, $message, implode("\r\n", $headers));
?>将来の読者のために:他の回答がうまくいかない場合は、これを試してください(私と同じように):
1.)PHPMailerをダウンロードし、zipファイルを開いて、フォルダをプロジェクトディレクトリに抽出します。
3.)抽出したディレクトリの名前をPHPMailerに変更し、phpスクリプト内に以下のコードを記述します(スクリプトはPHPMailerフォルダーの外にある必要があります)
<?php
// PHPMailer classes into the global namespace
use PHPMailer\PHPMailer\PHPMailer; 
use PHPMailer\PHPMailer\Exception;
// Base files 
require 'PHPMailer/src/Exception.php';
require 'PHPMailer/src/PHPMailer.php';
require 'PHPMailer/src/SMTP.php';
// create object of PHPMailer class with boolean parameter which sets/unsets exception.
$mail = new PHPMailer(true);                              
try {
    $mail->isSMTP(); // using SMTP protocol                                     
    $mail->Host = 'smtp.gmail.com'; // SMTP host as gmail 
    $mail->SMTPAuth = true;  // enable smtp authentication                             
    $mail->Username = 'sender@gmail.com';  // sender gmail host              
    $mail->Password = 'password'; // sender gmail host password                          
    $mail->SMTPSecure = 'tls';  // for encrypted connection                           
    $mail->Port = 587;   // port for SMTP     
    $mail->setFrom('sender@gmail.com', "Sender"); // sender's email and name
    $mail->addAddress('receiver@gmail.com', "Receiver");  // receiver's email and name
    $mail->Subject = 'Test subject';
    $mail->Body    = 'Test body';
    $mail->send();
    echo 'Message has been sent';
} catch (Exception $e) { // handle error.
    echo 'Message could not be sent. Mailer Error: ', $mail->ErrorInfo;
}
?>ネイティブPHP関数mail()が機能しません。それはメッセージを出します:
503このメールサーバーは、ローカル以外の電子メールアドレスに送信するときに認証が必要です
だから、私は通常PHPMailerパッケージを使用します
GitHubからバージョン5.2.23をダウンロードしました。
私はちょうど2つのファイルを選んで、それらを私のソースPHPルートに入れました
class.phpmailer.php
class.smtp.php
PHPでは、ファイルを追加する必要があります
require_once('class.smtp.php');
require_once('class.phpmailer.php');この後、それはただのコードです:
require_once('class.smtp.php');
require_once('class.phpmailer.php');
... 
//----------------------------------------------
// Send an e-mail. Returns true if successful 
//
//   $to - destination
//   $nameto - destination name
//   $subject - e-mail subject
//   $message - HTML e-mail body
//   altmess - text alternative for HTML.
//----------------------------------------------
function sendmail($to,$nameto,$subject,$message,$altmess)  {
  $from  = "yourcontact@yourdomain.com";
  $namefrom = "yourname";
  $mail = new PHPMailer();  
  $mail->CharSet = 'UTF-8';
  $mail->isSMTP();   // by SMTP
  $mail->SMTPAuth   = true;   // user and password
  $mail->Host       = "localhost";
  $mail->Port       = 25;
  $mail->Username   = $from;  
  $mail->Password   = "yourpassword";
  $mail->SMTPSecure = "";    // options: 'ssl', 'tls' , ''  
  $mail->setFrom($from,$namefrom);   // From (origin)
  $mail->addCC($from,$namefrom);      // There is also addBCC
  $mail->Subject  = $subject;
  $mail->AltBody  = $altmess;
  $mail->Body = $message;
  $mail->isHTML();   // Set HTML type
//$mail->addAttachment("attachment");  
  $mail->addAddress($to, $nameto);
  return $mail->send();
}それは魅力のように機能します
use PHPMailer\PHPMailer\PHPMailer; use PHPMailer\PHPMailer\Exception; require_once('src/PHPMailer.php'); require_once('src/Exception.php');
                    PHPからメールを送信する中心的な方法は、組み込みのmail()関数を使用することですが、すぐに使用できるSDKがいくつかあり、統合を容易にすることができます。
PS私はPepipostで働いています。
消印、SendgridなどのメールWebサービスを使用できます。
Sendgrid vs Postmark vs Amazon SESおよびその他のEメール/ SMTP APIプロバイダー?
編集:今はGoogle Gmail APIを使用しています。厳格なフィルターが原因で、リマインダーメールを雇用主の組織に送信できませんでした。しかし、Gmailは、スパムを送信しない限り機能します。
このスクリプトでメールを送信しました
<h2>Test Mail</h2>
<?php
if (!isset($_POST["submit"]))
  {
  ?>
  <form method="post" action="<?php echo $_SERVER["PHP_SELF"];?>">
  From: <input type="text" name="from"><br>
  Subject: <input type="text" name="subject"><br>
  Message: <textarea rows="10" cols="40" name="message"></textarea><br>
  <input type="submit" name="submit" value="Click To send mail">
  </form>
  <?php
  }
else
  {
  if (isset($_POST["from"]))
    {
    $from = $_POST["from"]; // sender
    $subject = $_POST["subject"];
    $message = $_POST["message"];
    $message = wordwrap($message, 70);
    mail("Test@example.com",$subject,$message,"From: $from\n");
    echo "Thank you for sending an email";
    }
  }
?>[メールを送信]ボタンを押すと、メールはTest@example.comに送信されます
<?php
include "db_conn.php";//connection file
require "PHPMailerAutoload.php";// it will be in PHPMailer
require "class.smtp.php";// it will be in PHPMailer
require "class.phpmailer.php";// it will be in PHPMailer
$response = array();
$params = json_decode(file_get_contents("php://input"));
if(!empty($params->email_id)){
    $email_id = $params->email_id;
    $flag=false;
    echo "something";
    if(!filter_var($email_id, FILTER_VALIDATE_EMAIL))
    {
        $response['ERROR']='EMAIL address format error'; 
        echo json_encode($response,JSON_UNESCAPED_SLASHES);
        return;
    }
    $sql="SELECT * from sales where email_id ='$email_id' ";
    $result = mysqli_query($conn,$sql);
    $count = mysqli_num_rows($result);
    $to = "demo@gmail.com";
    $subject = "DEMO Subject";
    $messageBody ="demo message .";
    if($count ==0){
        $response["valid"] = false;
        $response["message"] = "User is not registered yet";
        echo json_encode($response);
        return;
    }
    else {
        $mail = new PHPMailer();
        $mail->IsSMTP();
        $mail->SMTPAuth = true; // authentication enabled
        $mail->IsHTML(true); 
        $mail->SMTPSecure = 'ssl';//turn on to send html email
        // $mail->Host = "ssl://smtp.zoho.com";
        $mail->Host = "p3plcpnl0749.prod.phx3.secureserver.net";//you can use gmail 
        $mail->Port = 465;
        $mail->Username = "demousername@example.com";
        $mail->Password = "demopassword";
        $mail->SetFrom("demousername@example.com", "Any demo alert");
        $mail->Subject = $subject;
        $mail->Body = $messageBody;
        $mail->AddAddress($to);
        echo "yes";
        if(!$mail->send()) {
           echo "Mailer Error: " . $mail->ErrorInfo;
       } 
       else {
           echo "Message has been sent successfully";
      }
    }
}
else{
    $response["valid"] = false;
    $response["message"] = "Required field(s) missing";
    echo json_encode($response);
}
?>上記のコードは私のために働いています。