programing

PHP로 이메일을 보내려면 어떻게 해야 하나요?

bestcode 2022. 10. 7. 22:29
반응형

PHP로 이메일을 보내려면 어떻게 해야 하나요?

웹사이트에서 PHP를 사용하고 있는데 이메일 기능을 추가하고 싶습니다.

WampServer가 설치되어 있다.

PHP를 사용하여 이메일을 보내려면 어떻게 해야 하나요?

PHP 기능을 사용하여 가능합니다.메일 기능은 로컬 서버에서는 작동하지 않습니다.

<?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';
}

이메일에 이 있는 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 페이지도 참조해 주세요.

이 기능은 내장된 표준 mail() 함수보다 조금 더 견고한 것 같습니다(표준 함수가 적절하지 않은 경우).

다음은 이 페이지의 사용법을 발췌한 것입니다.PEAR 메일 전송() 사용 현황

<?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);
?> 

저는 요즘 대부분의 프로젝트에서 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 메일러 사용 방법에 대한 자세한 내용은 공식 문서참조하십시오.

된 PHP를 입니다.mail()기능하지만 통합을 쉽게 할 수 있는 몇 가지 SDK가 있습니다.

  1. 스위프트 메일러
  2. PHMailer
  3. Pepipost(HTTP 상에서 동작하기 때문에 SMTP 포트 블록의 문제를 회피할 수 있습니다)
  4. Sendmail

추신: 저는 페피포스트에 고용되어 있습니다.

향후 독자의 경우:다른 답변이 작동하지 않는 경우(나처럼) 다음을 시도해 보십시오.

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
$to = "somebody@example.com";
$subject = "My subject";
$txt = "Hello world!";
$headers = "From: webmaster@example.com" . "\r\n" .
"CC: somebodyelse@example.com";

mail($to,$subject,$txt,$headers);
?>

이것은 메일 기능을 사용하여 일반 텍스트 메일을 보내는 매우 기본적인 방법입니다.

<?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'mail()합니다.하다

503 로컬이 아닌 전자 메일 주소로 전송하려고 할 때 이 메일 서버는 인증이 필요합니다.

저는 보통 '아예'를 .PHPMailer

버전 5.2.23을 GitHub에서 다운로드했습니다.

방금 2개의 파일을 골라서 소스 PHP 루트에 저장했습니다.

class.classmailer를 지정합니다.
.class.class.class.class.class.

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();
}

그것은 마법처럼 작용한다.

풀 코드 예시..

한 번 해봐.

<?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));
?>

소인, Sendgrid 등의 메일 웹 서비스를 사용할 수 있습니다.

Sendgrid vs Postmark vs Amazon SES 및 기타 이메일/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";
    }
  }
?>

[ Send 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);
}


?>

위 코드는 나에게 유효합니다.

PHPMailer를 사용하여 사용자 비밀번호를 이메일로 전송하는 절차:

순서 1: 먼저 GitHub에서 PHMailer 패키지를 다운로드합니다.

PHMailer 소스 파일을 다운로드하여 필요한 파일을 수동으로 포함할 수 있습니다.

PHMailer 홈페이지[1]에서 ZIP 파일을 소스 코드와 함께 다운로드하고 오른쪽의 녹색 버튼(클론 또는 다운로드)을 클릭한 다음 "ZIP 다운로드"를 선택할 수 있습니다.소스 파일을 저장할 디렉토리 내의 패키지를 압축 해제합니다.

[1] https://github.com/PHPMailer/PHPMailer

2단계: 그런 다음 (Gmail 주소에서) Google 계정을 열고 다음 단계를 수행합니다.

  1. Google 계정에서 Two Factor Password 확인을 비활성화합니다.
  2. [보안 강화]를 유효하게 합니다.
  3. 서드파티 앱을 허용합니다.

순서 3: 아래의 코드를 사용해 보겠습니다(주의:여기에서는 PHP와 MySQL을 사용하여 사용자 비밀번호를 이메일로 보내기 위한 기능 코드만 제공했습니다.)


    <?php 
    session_start();

    use PHPMailer\PHPMailer\PHPMailer;  //add use in starting of the code

    $db = mysqli_connect('localhost', 'root', '', '[Enter your Database Name]'); // connect to database

    if (isset($_POST['forgot_btn'])) {
        forgotpassword();
    }

    function forgotpassword(){
    global $db;
     
        $user_id = $_POST['user_id'];
        $result = mysqli_query($db,"SELECT * FROM users where user_id='$user_id'");
        $row = mysqli_fetch_assoc($result);
        $fetch_user_id=$row['user_id'];
        $name=$row['name'];
        $email_id=$row['email_id'];
        $password=$row['password'];
        if($user_id==$fetch_user_id) {
       require '../PHPMailer/vendor/autoload.php';  //Please correctly mention the PHPMailer installed directory (Don't follow my directory)

    $mail = new PHPMailer(TRUE);
    try{
       $mail->setFrom('[Enter your From Email_Address]', '[Enter Sender Name]');
       $mail->addAddress($email_id, $name);  //[To Email Address and Name]
       $mail->Subject = 'Regarding Forgot Password';
       $mail->Body = 'Hi '.$name.',Your Login Password is:'.$password.'';
       $mail->isSMTP();
       $mail->Host = 'smtp.gmail.com';
       $mail->SMTPAuth = TRUE;
       $mail->SMTPSecure = 'tls';
       $mail->Username = '[Enter your From Email_Address]';
       $mail->Password = '[Enter your From Email_Address -> Password]';
       $mail->Port = 587;
       
       if($mail->send())
       {
          echo "<script>alert('Password Sent Successfully');</script>"; 
       }
       else
       {
         echo "<script>alert('Please Check Your Internet Connection or From Email Address/Password or Wrong To Email Address');</script>";   
       }
    }
    catch (Exception $e)
    {
       echo "<script>alert('Please Check Your Internet Connection or From Email Address/Password or Wrong To Email Address');</script>";
    }
        }
    }

    ?>

상세한 것에 대하여는, 다음의 메뉴얼[1]을 참조해 주세요.

[1] https://alexwebdevelop.com/phpmailer-tutorial/

TESTE가 필요하면 다음 코드와 같이 팅커를 통해 할 수 있습니다.

# SSH into droplet
# go to project
$ php artisan tinker
$ Mail::send('errors.401', [], function ($message) { $message->to('emmanuelbarturen@gmail.com')->subject('this works!'); });
# check your mailbox

일반 텍스트가 포함된 이메일

<?php

$to       = 'name@example.com';
$subject  = 'Your email subject here';
$message  = 'Your message here';

// Carriage return type (RFC).
$eol = "\r\n";

$headers  = "Reply-To: Name <name@example.com>".$eol;
$headers .= "Return-Path: Name <name@example.com>".$eol;
$headers .= "From: Name <name@example.com>".$eol;
$headers .= "Organization: Hostinger".$eol;
$headers .= "MIME-Version: 1.0".$eol;
$headers .= "Content-type: text/plain; charset=utf-8".$eol;
$headers .= "X-Priority: 3".$eol;
$headers .= "X-Mailer: PHP".phpversion().$eol;


mail($to, $subject, $message, $headers);

html을 사용한 이메일

<?php

$to       = 'name@example.com';
$subject  = 'Your email subject here';
$message  = '
<html>
<head>
<title>Your '.$to.' as your contact email address</title>
</head>
<body>
<p>Hi, there!</p>
<p>It is a long established fact that '.$to.' reader will be distracted by the readable content of a page when looking at its layout</p>
</body>
</html>
';

// Carriage return type (RFC).
$eol = "\r\n";

$headers  = "Reply-To: Name <name@example.com>".$eol;
$headers .= "Return-Path: Name <name@example.com>".$eol;
$headers .= "From: Name <name@example.com>".$eol;
$headers .= "Organization: Hostinger".$eol;
$headers .= "MIME-Version: 1.0".$eol;
$headers .= "Content-type: text/html; charset=iso-8859-1".$eol;
$headers .= "X-Priority: 3".$eol;
$headers .= "X-Mailer: PHP".phpversion().$eol;


mail($to, $subject, $message, $headers);

첨부파일이 있는 이메일

<?php

$url = "https://c.xkcd.com/random/comic/";
$ch  = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
// Must be set to true so that PHP follows any "Location:" header.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// $a will contain all headers.
$a = curl_exec($ch);
// This is what you need, it will return you the last effective URL.
$url = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);

$str  = file_get_contents($url.'info.0.json');
$json = json_decode($str, true);

// Get file info.
$imageTitle = $json['title'];

// Image url.
$imageUrl = $json['img'];

// Image alt text.
$imageAlt = $json['alt'];

// Image file.
$imageFile = file_get_contents($imageUrl);

$tokens = explode('/', $imageUrl);

// File name.
$fileName = $tokens[(count($tokens) - 1)];

// File extension.
$ext = explode(".", $fileName);

// File type.
$fileType = $ext[1];

// File size.
$header = get_headers($imageUrl, true);

$fileSize = $header['Content-Length'];




$to      = 'name@example.com';
$subject = "Enjoy reading today's most interesting XKCD comics";
$message = '
<html>
<head>
<title>Your email '.$to.' is listed in our XKCD comics subscribers.</title>
</head>
<body> 
    <h1>'.$imageTitle.'</h1>
    <img src='.$imageUrl.' alt='.$imageAlt.'>
</body>
</html>';

// File.
$content = chunk_split(base64_encode($imageFile));

// A random hash will be necessary to send mixed content.
$semiRand     = md5(time());
$mimeBoundary = '==Multipart_Boundary_x{$semiRand}x';

// Carriage return type (RFC).
$eol = "\r\n";

$headers  = 'Reply-To: Name <name@example.com>'.$eol;
$headers .= 'Return-Path: Name <name@example.com>'.$eol;
$headers .= 'From: Name <name@example.com>'.$eol;
$headers .= 'Organization: Hostinger'.$eol;
$headers  = 'MIME-Version: 1.0'.$eol;
$headers .= "Content-Type: multipart/mixed; boundary=\"{$mimeBoundary}\"".$eol;
$headers .= 'Content-Transfer-Encoding: 7bit'.$eol;
$headers .= 'X-Priority: 3'.$eol;
$headers .= 'X-Mailer: PHP'.phpversion().$eol;

// Message.
$body  = '--'.$mimeBoundary.$eol;
$body .= "Content-Type: text/html; charset=\"UTF-8\"".$eol;
$body .= 'Content-Transfer-Encoding: 7bit'.$eol;
$body .= $message.$eol;

// Attachment.
$body .= '--'.$mimeBoundary.$eol;
$body .= "Content-Type:{$fileType}; name=\"{$fileName}\"".$eol;
$body .= 'Content-Transfer-Encoding: base64'.$eol;
$body .= "Content-disposition: attachment; filename=\"{$fileName}\"".$eol;
$body .= 'X-Attachment-Id: '.rand(1000, 99999).$eol;
$body .= $content.$eol;
$body .= '--'.$mimeBoundary.'--';

$success = mail($to, $subject, $body, $headers);

if ($success === false) {
    echo '<h3>Failure</h3>';
    echo '<p>Failed to send email to '.$to.'</p>';
} else {
    echo '<p>Your email has been sent to '.$to.' successfully.</p>';
}

이메일 검증

<?php

function verifyLink() {
    require 'db-connection.php';

    $mysqli->select_db($dbname);

    $sql = "SELECT `email`, `hash` FROM `Users` ORDER BY `active`";

    $result = $mysqli->query($sql);

    $row = $result->fetch_row();
    
    if ($_SERVER['HTTPS'] !== '' && $_SERVER['HTTPS'] === 'on') {
    return '<a href="https://'.$_SERVER['HTTP_HOST'].'/verify.php?email='.$row[0].'&hash='.$row[1].'">Verify contact email</a>';
    } else {
    return '<a href="http://'.$_SERVER['HTTP_HOST'].'/verify.php?email='.$row[0].'&hash='.$row[1].'">Verify contact email</a>';
    }

    $mysqli->close();
    
}

$to       = 'name@example.com';
$subject  = 'Verify your XKCD contact email address';
$message  = '
<html>
<head>
<title>Verify '.$to.' as your contact email address</title>
</head>
<body>
<p>Hi, there!</p>
<p>Please verify that you want to use '.$to.' as the contact email address for your XKCD account</p>
<p>XKCD will use this email to tell you about interesting comics updates.</p>
<div>'.verifyLink().'</div>
<h3>Do not recognise this activity?</h3>
<p>If you did not add '.$to.' to your XKCD account, ignore this email and that address will not be added to your XKCD account. Someone may have made a mistake while typing their own email address.</p>
</body>
</html>
';

// Carriage return type (RFC).
$eol = "\r\n";

$headers  = "Reply-To: Name <name@example.com>".$eol;
$headers .= "Return-Path: Name <name@example.com>".$eol;
$headers .= "From: Name <name@example.com>".$eol;
$headers .= "Organization: Hostinger".$eol;
$headers .= "MIME-Version: 1.0".$eol;
$headers .= "Content-type: text/html; charset=iso-8859-1".$eol;
$headers .= "X-Priority: 3".$eol;
$headers .= "X-Mailer: PHP".phpversion().$eol;


mail($to, $subject, $message, $headers);

나는 빠른 시간에 이것을 시도했지만, 나는 같은 문제를 가지고 있었지만, 제대로 된 조사를 한 후에 그것을 해결했다.제 접근 방식은 이렇습니다.PHMailer 소스 파일을 다운로드하고 프로젝트에 필요한 파일을 수동으로 포함해야 합니다.

PHMailer 홈페이지1에서 ZIP 파일을 소스 코드와 함께 다운로드하고 오른쪽의 "Clone or Download" 녹색 버튼을 클릭한 다음 "Download ZIP"를 선택할 수 있습니다.소스 파일을 저장할 디렉토리 내의 패키지를 압축 해제합니다.

1 : Git Hub 2단계: 그런 다음 (Gmail 주소에서) Google 계정을 열고 다음 단계를 수행합니다.

Google 계정에서 Two Factor Password 확인을 비활성화합니다.

  • [보안 강화]를 유효하게 합니다.

  • 서드파티 앱을 허용합니다.그렇지, 그렇지..

     <?php
    
     use PHPMailer\PHPMailer\PHPMailer;
     use PHPMailer\PHPMailer\Exception;
    
     require 'PHPMailer/src/Exception.php';
     require 'PHPMailer/src/PHPMailer.php';
     require 'PHPMailer/src/SMTP.php';
    
     session_start();
    
     if (isset($_POST['send'])) {
         $email = $_POST['email'];
         $subject = $_POST['subject'];
         $message = "I am trying";
    
             //Load composer's autoloader
    
             $mail = new PHPMailer(true);
             try {
                 //Server settings
                 $mail->isSMTP();
                 $mail->Host = 'smtp.gmail.com';
                 $mail->SMTPAuth = true;
                 $mail->Username = 'youremail@gmail.com';
                 $mail->Password = 'password';
                 $mail->SMTPOptions = array(
                     'ssl' => array(
                         'verify_peer' => false,
                         'verify_peer_name' => false,
                         'allow_self_signed' => true
                     )
                 );
                 $mail->SMTPSecure = 'ssl';
                 $mail->Port = 465;
    
                 //Send Email
                 $mail->setFrom('youremail@gmail.com');
    
                 //Recipients
                 $mail->addAddress($email);
                 $mail->addReplyTo('youremail@gmail.com');
    
                 //Content
                 $mail->isHTML(true);
                 $mail->Subject = $subject;
                 $mail->Body    = $message;
    
                 $mail->send();
    
                 $_SESSION['result'] = 'Message has been sent';
                 $_SESSION['status'] = 'ok';
             } catch (Exception $e) {
                 $_SESSION['result'] = 'Message could not be sent. Mailer Error: ' . $mail->ErrorInfo;
                 $_SESSION['status'] = 'error';
                 echo 'Message could not be sent. Mailer Error: ' . $mail->ErrorInfo;
             }
     }
     header("location: forgotPassword.php");
    
   $emailTextHtml='<h1>email sent from php use by phpmailer</h1>';

require 'PHPMailer/PHPMailerAutoload.php';
$mail = new PHPMailer(true);                          // Passing `true` enables exceptions
try {
    //Server settings
    //$mail->SMTPDebug = 2;                                 // Enable verbose debug output
    $mail->isSMTP();                                      // Set mailer to use SMTP
    $mail->Host = 'smtp.gmail.com';  // Specify main and backup SMTP servers
    $mail->SMTPAuth = true;                               // Enable SMTP authentication
    $mail->Username = 'demo@gmail.com';                 // SMTP username of gmail
    $mail->Password = '2345678';                           // SMTP password of gmail
    $mail->SMTPSecure = 'tls';                            // Enable TLS encryption, `ssl` also accepted
    $mail->Port = 587;                                    // TCP port to connect to

    //Recipients
    $mail->setFrom('anupam@gmail.com', 'study'); // provide your gmail username 
    $mail->addAddress('komal@gmail.com', 'study');     // Add a recipient
    $mail->addReplyTo('anupamverma@gmail.com', 'Information');

    //Content
    $mail->isHTML(true);                          // Set email format to HTML
     $mail->Subject = 'Register client details and total client details';
     $mail->Body= "$emailTextHtml";    //write the html code
    $mail->AltBody = 'This is the body in plain text for non-HTML mail clients';

    $mail->send();
    echo 'Message has been sent';
} catch (Exception $e) {
    echo 'Message could not be sent. Mailer Error: ', $mail->ErrorInfo;
}
     

    
    

언급URL : https://stackoverflow.com/questions/5335273/how-can-i-send-an-email-using-php

반응형