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

use*_*849 296 php email wamp wampserver

我在网站上使用PHP,我想添加电子邮件功能.

我安装了WAMPSERVER.

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

Mut*_*ran 423

使用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);
?> 
Run Code Online (Sandbox Code Playgroud)

参考:

  • 您需要在本地服务器上配置SMTP.看看这篇类似的帖子,http://stackoverflow.com/questions/4652566/php-mail-setup-in-xampp (18认同)
  • 如果我需要从本地服务器发送电子邮件怎么办?我的意思是有没有办法访问最近的邮件服务器,让它为我发送邮件.我的意思是我可以找到雅虎邮件服务器的地址,然后我使用该服务器进行邮寄......这可能吗? (5认同)

nor*_*teo 115

您也可以在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';
}
Run Code Online (Sandbox Code Playgroud)

  • 如果不使用作曲家:`使用PHPMailer \ PHPMailer \ PHPMailer; 使用PHPMailer \ PHPMailer \ Exception; require_once('src / PHPMailer.php'); require_once('src / Exception.php');` (3认同)

Sum*_*and 42

如果您对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);
Run Code Online (Sandbox Code Playgroud)

有关更多详细信息,请检查php 邮件功能.


Kev*_*n S 14

另请查看PEAR邮件包Pear Mail Page

它似乎比内置的标准mail()函数更强大(如果标准函数不足).

以下是此页面的摘录,展示了如何使用它. PEAR Mail 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);
?> 
Run Code Online (Sandbox Code Playgroud)


Joh*_*ers 12

对于大多数项目,我最近使用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);
}
Run Code Online (Sandbox Code Playgroud)

有关如何使用Swift邮件程序的更多信息,请参阅官方文档.


Aht*_*ham 9

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

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;
}
?>
Run Code Online (Sandbox Code Playgroud)


AMB*_*AMB 7

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

<?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);
Run Code Online (Sandbox Code Playgroud)


小智 7

试试这个:

<?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);
?>
Run Code Online (Sandbox Code Playgroud)


Dib*_*hoo 7

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

  1. 迅捷邮递员
  2. PHPMailer
  3. Pepipost(通过 HTTP 工作,因此可以避免 SMTP 端口阻塞问题)
  4. 发邮件

PS 我受雇于 Pepipost。

  • 您受雇于 Pepipost,并将 Pepipost 排在第 3 位。+1 (7认同)
  • @DibyaSahoo 对你的评价很高 (5认同)
  • @GeneCode,如果有什么是最好的,那就是。不管你是否受雇于他们 :) Swiftmailer 和 PHPMailer,绝对是发送电子邮件的最佳开源工具之一(因此我将它们保留在 1 和 2 中)。但是,与此同时,它们也有我们试图在我们的 Pepipost SDK 中解决的某些限制和障碍。 (4认同)

emo*_*aus 5

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

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

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


Mr.*_* HK 5

完整的代码示例..

尝试一次..

<?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));
?>
Run Code Online (Sandbox Code Playgroud)


Pau*_*aum 5

本机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');
Run Code Online (Sandbox Code Playgroud)

在此之后,它只是代码:

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();
}
Run Code Online (Sandbox Code Playgroud)

它像一个魅力

  • 谢谢您的回答。您的建议与@norteo的回答相同。请记住,v5.2已过时,并且未收到安全更新。对于v6,您可以直接要求:`使用PHPMailer \ PHPMailer \ PHPMailer; 使用PHPMailer \ PHPMailer \ Exception; require_once('src / PHPMailer.php'); require_once('src / Exception.php');` (2认同)