如何使用 PHP 发送电子邮件?

How can I send an email using PHP?

提问人:user590849 提问时间:3/17/2011 最后编辑:Peter Mortensenuser590849 更新时间:2/3/2023 访问量:1221811

问:

我正在一个网站上使用PHP,我想添加电子邮件功能。

我安装了 WampServer

如何使用 PHP 发送电子邮件?

PHP 电子邮件 WAMP WAMP服务器

评论

24赞 xkeshav 3/17/2011
阅读手册

答:

508赞 Muthu Kumaran 3/17/2011 #1

可以使用 PHP 的 mail() 函数。请记住,邮件功能在本地服务器上不起作用。

<?php
    $to      = '[email protected]';
    $subject = 'the subject';
    $message = 'hello';
    $headers = 'From: [email protected]'       . "\r\n" .
                 'Reply-To: [email protected]' . "\r\n" .
                 'X-Mailer: PHP/' . phpversion();

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

参考:

评论

12赞 user590849 3/17/2011
如果我需要从本地服务器发送电子邮件怎么办?我的意思是有没有办法访问最近的邮件服务器并让它为我发送邮件。我的意思是我可以找到雅虎邮件服务器的地址,然后我使用该服务器进行邮件......这可能吗?
28赞 Muthu Kumaran 3/17/2011
您需要在本地服务器上配置 SMTP。看看这个类似的帖子,stackoverflow.com/questions/4652566/php-mail-setup-in-xampp
1赞 Muhammad Ashikuzzaman 12/3/2014
您好@MuthuKumaran如果这是垃圾邮件,是否有任何好的解决方案可以解决它,请回答。
0赞 Uli Köhler 7/26/2015
@MuhammadAshikuzzaman 您无法解决PHP中的垃圾邮件问题。如果这仍然相关,请在相应的 StackExchange 网站上提出新问题。
1赞 abhishah901 8/23/2016
如何确保或验证这是否适用于我的本地服务器?如果不可能这样做,请建议一些替代方案。谢谢。
21赞 Kevin S 3/17/2011 #2

另请查看 PEAR 邮件包 Pear 邮件页面

它似乎比内置的标准 mail() 函数更强大一些(如果标准函数不够)。

以下是此页面的摘录,显示了它的使用方式。PEAR 邮件 send() 用法

<?php
    include('Mail.php');

    $recipients = '[email protected]';

    $headers['From']    = '[email protected]';
    $headers['To']      = '[email protected]';
    $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);
?> 

评论

0赞 Muhammad Ashikuzzaman 12/3/2014
请提供您使用的邮件 .php 链接和文件夹中所有其他相关文件的下载链接。谢谢
1赞 Kevin S 12/3/2014
@Ashik 我的示例中引用的文件是 Pear Mail 包的一部分。如果您下载并安装 Pear Mail 软件包,您将能够包括 .如果您单击上面的“Pear Mail Page”链接,则会有一个包含说明的下载链接。Mail.phpMail.php
51赞 Sumoanand 9/20/2013 #3

如果您对 html 格式的电子邮件感兴趣,请务必传入标题。例:Content-type: text/html;

// multiple recipients
$to  = '[email protected]' . ', '; // note the comma
$to .= '[email protected]';

// 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 <[email protected]>, Kelly <[email protected]>' . "\r\n";
$headers .= 'From: Birthday Reminder <[email protected]>' . "\r\n";
$headers .= 'Cc: [email protected]' . "\r\n";
$headers .= 'Bcc: [email protected]' . "\r\n";

// Mail it
mail($to, $subject, $message, $headers);

有关更多详细信息,请查看 php mail 函数。

评论

0赞 antf 11/5/2014
您好,我厌倦了这段代码,我添加了 3 个收件人,一个 Hotmail,一个 Gmail 和一个我的网站电子邮件。除了 Hotmail 之外,我收到了所有内容。您知道为什么它不适用于 Hotmail 吗?
0赞 Sumoanand 11/5/2014
在这种情况下,请检查垃圾邮件文件夹。
0赞 antf 11/6/2014
我已经做到了,它不在垃圾邮件中,根本没有到达。我读了更多关于这个主题的信息,似乎 Hotmail 需要一些特殊的标头,或者它不允许电子邮件通过他们的服务器......不过,我仍然没有找到解决方案。
0赞 antf 11/6/2014
我通过使用 PHPMailer 并在 PHPMailer 的电子邮件对象中使用 SSL 输入我的电子邮件帐户数据解决了我的问题。
0赞 9/16/2016
如果邮件包含 HTML 和 php 内容怎么办?
140赞 norteo 5/28/2014 #4

您也可以在 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 = '[email protected]';                 // SMTP username
$mail->Password = 'secret';                           // SMTP password
$mail->SMTPSecure = 'tls';                            // Enable encryption, 'ssl' also accepted

$mail->From = '[email protected]';
$mail->FromName = 'Mailer';
$mail->addAddress('[email protected]', 'Joe User');     // Add a recipient
$mail->addAddress('[email protected]');               // Name is optional
$mail->addReplyTo('[email protected]', 'Information');
$mail->addCC('[email protected]');
$mail->addBCC('[email protected]');

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

评论

7赞 Wtower 1/28/2019
如果不使用 composer:use PHPMailer\PHPMailer\PHPMailer; use PHPMailer\PHPMailer\Exception; require_once('src/PHPMailer.php'); require_once('src/Exception.php');
1赞 webcoder.co.uk 3/25/2021
在端口 465 上使用 gmail 时,您需要将 host 设置为$mail->Host = 'ssl://smtp.gmail.com';
8赞 user1642018 8/17/2014 #5

这是使用邮件功能发送纯文本电子邮件的非常基本的方法。

<?php
$to = '[email protected]';
$subject = 'This is subject';
$message = 'This is body of email';
$from = "From: FirstName LastName <SomeE[email protected]>";
mail($to,$subject,$message,$from);
5赞 emolaus 3/6/2015 #6

您可以使用邮件网络服务,例如 Postmark、Sendgrid 等。

Sendgrid vs Postmark vs Amazon SES 和其他电子邮件/SMTP API 提供商?

编辑:我现在只使用Google Gmail API。由于严格的过滤器,我无法向雇主的组织发送提醒电子邮件。但是,只要您不向人们发送垃圾邮件,Gmail 就会起作用。

9赞 lyndact 11/22/2015 #7

试试这个:

<?php
$to = "[email protected]";
$subject = "My subject";
$txt = "Hello world!";
$headers = "From: [email protected]" . "\r\n" .
"CC: some[email protected]";

mail($to,$subject,$txt,$headers);
?>
15赞 John Slegers 2/10/2016 #8

对于大多数项目,我现在都使用 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('[email protected]' => 'Jane Doe'))
    // The to address(es)
    ->setTo(array('[email protected]' => '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 邮件程序的更多信息,请参阅官方文档

评论

0赞 Yevgeniy Afanasyev 2/1/2018
你好。你说当你的文档链接说.这是否意味着您指的是旧版本的 swift mailer,或者这是一个错别字,或者我误解了什么?我需要安装旧版本的swift-mailer,因为我的服务器上没有php7。因此,我需要知道当前版本的文档是否与旧版本的软件包一起使用。谢谢。Swift_MailTransportSwift_SendmailTransport
1赞 John Slegers 2/1/2018
@YevgeniyAfanasyev :我的回答是 2 年前的正确做事方式,但自 Swiftmailer v5.4.5 以来,Swift_MailTransport已被弃用。无论如何,如果你不能将 PHP 7 用于你的项目,你应该使用 Swiftmailer v5.4.9。这是最后一个仍然支持 PHP 5 的稳定版本。有关版本 v5.4.9 的文档或有关 v5.4.9 和 v6.0.2 之间差异的详细信息,您可能需要联系 Fabien Potencier在 Github 上提出问题。
0赞 Yevgeniy Afanasyev 2/2/2018
谢谢。因此,当分发版可用时,旧版本没有免费可用的文档。很高兴知道。
6赞 Hardik Kalathiya 1/21/2017 #9

完整代码示例..

尝试一次..

<?php
// Multiple recipients
$to = '[email protected], [email protected]'; // 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 <[email protected]>, Kelly <[email protected]>';
$headers[] = 'From: Birthday Reminder <[email protected]>';
$headers[] = 'Cc: [email protected]';
$headers[] = 'Bcc: [email protected]';

// Mail it
mail($to, $subject, $message, implode("\r\n", $headers));
?>
3赞 Hiren Parghi 12/4/2017 #10

使用此脚本发送电子邮件

<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("[email protected]",$subject,$message,"From: $from\n");
    echo "Thank you for sending an email";
    }
  }
?>

按下发送电子邮件按钮后,电子邮件将发送到 [email protected]

8赞 Paulo Buchsbaum 2/7/2018 #11

原生PHP函数对我不起作用。它发出消息:mail()

503 此邮件服务器在尝试发送邮件时需要身份验证 发送到非本地电子邮件地址

所以,我通常使用包PHPMailer

我已经从以下位置下载了 5.2.23 版本: GitHub.

我刚刚选择了 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  = "[email protected]";
  $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();
}

它就像一个魅力

评论

2赞 Wtower 1/28/2019
谢谢你的回答。您的建议与他的回答中指出@norteo相同。请记住,v5.2 已弃用,并且不会收到安全更新。对于 v6,您可以直接要求:use PHPMailer\PHPMailer\PHPMailer; use PHPMailer\PHPMailer\Exception; require_once('src/PHPMailer.php'); require_once('src/Exception.php');
2赞 Pooja Khatri 2/14/2018 #12
<?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 = "[email protected]";
    $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 = "[email protected]";
        $mail->Password = "demopassword";
        $mail->SetFrom("[email protected]", "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);
}


?>

上面的代码对我有用。

13赞 Dibya Sahoo 9/6/2018 #13

从 PHP 发送电子邮件的核心方式是使用其内置功能,但有几个现成的 SDK 可以简化集成:mail()

  1. 斯威夫特邮件
  2. PHP编器
  3. Pepipost(通过HTTP工作,因此可以避免SMTP端口阻止问题)
  4. 发送邮件

P.S. 我受雇于 Pepipost。

评论

13赞 GeneCode 1/28/2019
您受雇于 Pepipost,您将 Pepipost 排在第 3 位。+1
7赞 Dibya Sahoo 3/5/2019
@GeneCode,如果某件事是最好的,那么它就是。无论您是否受雇于他们,都无关紧要:)Swiftmailer 和 PHPMailer 绝对是发送电子邮件的最佳开源工具之一(因此我将它们保留在 1 和 2 中)。但是,与此同时,它们也有一定的局限性和阻碍因素,我们试图在Pepipost SDK中解决这些问题。
5赞 skini82 11/19/2020
@DibyaSahoo对你有很高的评价
12赞 Ahtisham 1/19/2019 #14

对于未来的读者:如果其他答案不起作用,请尝试这样做(就像我的情况一样):

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 = '[email protected]';  // sender gmail host              
    $mail->Password = 'password'; // sender gmail host password                          
    $mail->SMTPSecure = 'tls';  // for encrypted connection                           
    $mail->Port = 587;   // port for SMTP     

    $mail->setFrom('[email protected]', "Sender"); // sender's email and name
    $mail->addAddress('[email protected]', "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;
}
?>
0赞 Caique Andrade 3/4/2021 #15

如果你需要,你可以做一个 TESTE 通过 tinker 来做,如下代码所示

# SSH into droplet
# go to project
$ php artisan tinker
$ Mail::send('errors.401', [], function ($message) { $message->to('[email protected]')->subject('this works!'); });
# check your mailbox
1赞 Vishal K 5/9/2021 #16

使用 PHPMailer 通过电子邮件发送用户密码的过程:

第 1 步:首先,从 GitHub 下载 PHPMailer 包

您可以下载PHPMailer源文件并手动包含所需的文件。

您可以从 PHPMailer 主页下载带有源代码的 ZIP 文件[1], 单击“克隆或下载”绿色按钮(右侧),然后选择“下载ZIP”。 将包解压缩到要保存源文件的目录中。

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

步骤2:然后,打开(从Gmail地址)Google帐户并执行以下步骤:

  1. 禁用谷歌帐户中的双因素密码验证。
  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/

评论

1赞 Skgland 5/9/2021
发出禁用 2FA 的指令并打开较低的安全性,从而危及其他帐户,即使不是恶意的,至少也是疏忽大意。相反,添加 App-Password 应该可以工作,同时使帐户处于不太不安全的状态。
0赞 Vishal K 5/9/2021
嗨,@Skgland,很抱歉问这个问题,您提到App-Password应该可以正常工作。你能告诉我如何在这个代码中使用它吗?
0赞 Skgland 5/10/2021
您可以创建一个应用程序密码,然后使用该密码而不是您的帐户密码,而不是禁用 2FA 并打开较低的安全性。我只是用上面的源代码对其进行了测试,虽然减少到不使用数据库并且只是发送静态电子邮件,但为了进行测试,我还需要替换所需的行,因为我无法对自动分配器 .php 文件进行微调。
0赞 Mahvash Fatima 7/1/2021 #17

纯文本电子邮件

<?php

$to       = '[email protected]';
$subject  = 'Your email subject here';
$message  = 'Your message here';

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

$headers  = "Reply-To: Name <[email protected]>".$eol;
$headers .= "Return-Path: Name <[email protected]>".$eol;
$headers .= "From: Name <[email protected]>".$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       = '[email protected]';
$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 <[email protected]>".$eol;
$headers .= "Return-Path: Name <[email protected]>".$eol;
$headers .= "From: Name <[email protected]>".$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      = '[email protected]';
$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 <[email protected]>'.$eol;
$headers .= 'Return-Path: Name <[email protected]>'.$eol;
$headers .= 'From: Name <[email protected]>'.$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       = '[email protected]';
$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 <[email protected]>".$eol;
$headers .= "Return-Path: Name <[email protected]>".$eol;
$headers .= "From: Name <[email protected]>".$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);
-1赞 Anupam Verma 9/2/2021 #18
   $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 = '[email protected]';                 // 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('[email protected]', 'study'); // provide your gmail username 
    $mail->addAddress('[email protected]', 'study');     // Add a recipient
    $mail->addReplyTo('[email protected]', '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;
}
     

    
    
0赞 Wesley-Sinde 10/24/2021 #19

我在快速的时间内尝试了这个,我遇到了同样的问题,但在适当的研究之后,我解决了它。这是我的方法。您必须下载 PHPMailer 源文件并在您的项目中手动包含所需的文件。

您可以从 PHPMailer 主页1 下载带有源代码的 ZIP 文件,单击“克隆或下载”绿色按钮(右侧),然后选择“下载 ZIP”。将包解压缩到要保存源文件的目录中。

1 来自:GitHub。步骤2:然后,打开(从Gmail地址)Google帐户并执行以下步骤:

禁用谷歌帐户中的双因素密码验证。

  • 打开安全性较低。

  • 允许第三方应用。 给你。。

     <?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 = '[email protected]';
                 $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('[email protected]');
    
                 //Recipients
                 $mail->addAddress($email);
                 $mail->addReplyTo('[email protected]');
    
                 //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");
    
0赞 Mahdi Bashirpour 2/3/2023 #20

我在cPanel中使用了这种方法,一切正常:

<?php 
  $dest = "[email protected]"; 
  $fromaddy = "[email protected]"; 
  mail("<$dest>","Test from php mail","Test","From:<$fromaddy>","-f$fromaddy"); 
?>