PHP邮件与gmail示例

时间:2011-04-18 16:34:15

标签: php

我有以下代码,我相信它会起作用,但它需要Mail.php。我安装了梨邮件,但没有Mail.php文件的示例。有人有例子吗?我需要帮助将它放到位,以便代码执行。感谢

   require_once "Mail.php";

    $from = "<me1@gmail.com>";
    $to = "<me2@gmail.com>";
    $subject = "Test from iyearbook!";
    $body = "Hi,\n\nHow are you?";

    $host = "ssl://smtp.gmail.com";
    $port = "465";
    $username = "me@gmail.com";
    $password = "password";

    $headers = array ('From' => $from,
      'To' => $to,
      'Subject' => $subject);
    $smtp = Mail::factory('smtp',
      array ('host' => $host,
        'port' => $port,
        'auth' => true,
        'username' => $username,
        'password' => $password));

    $mail = $smtp->send($to, $headers, $body);

    if (PEAR::isError($mail)) {
      echo("<p>" . $mail->getMessage() . "</p>");
     } else {
      echo("<p>Message successfully sent!</p>");
     }

?>  <!-- end of php tag--->

2 个答案:

答案 0 :(得分:5)

您不必手动编写Mail.php类文件。当您通过pear安装它时,它会自行安装。关于inlude路径,如果正确设置了包含路径,Mail.php将可供使用。

检查您的梨包含路径。当你需要Mail.php时,它会给你任何错误吗?打开错误报告并查看。很可能你的梨包含路径没有设置

试试这个:

<?php
require_once 'Mail.php';
var_dump(class_exists('Mail', false));
?> 

验证/修复pear include路径检查: http://pear.php.net/manual/en/installation.checking.php

答案 1 :(得分:2)

为了简化电子邮件处理过程,我最终创建了自己的函数,例如pearMail($ to,$ subject,$ message,$ header,$ returnEmail);

//To define $to , $subject , $html
//Optional defines  $sender1 , $sender2


//REQUIRED EXAMPLE
   // $to = '';               // Email address of the person the mail goes to
   // $subject = $subject;    // Subject for the email
   //  $html = '<html><body><p>This is a html message</p></body></html>';  // HTML version of the email
   // $filename = 'mail/contact.html  // and create an array called $params to replace in the email.


//POINT CORRECTLY
include('PEAR/Mail.php');
include('PEAR/mime.php');

//INFO UNCHANGABLE
$crlf = "\n";
$headers = array('From' => $sender1, 'Return-Path' => $sender2, 'Subject' => $subject);
$mime = new Mail_mime($crlf);
$mime->setHTMLBody($html);
$body = $mime->get();
$headers = $mime->headers($headers);
$smtp_params["host"] = "ssl://smtp.gmail.com"; // SMTP host
$smtp_params["port"] = "465"; // SMTP host
$smtp_params["auth"] = true;               
$smtp_params["username"] = "YOUR@EMAIL.COM";        // authentication.
$smtp_params["password"] = 'YOURPASSWORD'; 
$mail =& Mail::factory("smtp", $smtp_params);
$result = $mail->send($to, $headers, $body);