我在网站上使用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);
?> 

参考:

 

方法二:

使用PHPMailer类,下载地址:https://github.com/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\';
}

 

方法三:

另请查看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   using the Mail::factory method
    $mail_  =& Mail::factory(\"smtp\", $smtpinfo); 

    $mail_ ->send($recipients, $headers, $body);
?> 
收藏 打印