PHP邮件从localhost发送到服务器

时间:2013-02-05 13:47:07

标签: smtp gmail php

我想从localhost发送电子邮件到gmail服务器  例如(anydomain@gmail.com)。

代码示例为:

<?php 
$to = "thisizraheel@gmail.com";
$subject = "Hi!";
$body = "Hi,\n\nHow are you?";

if (mail($to, $subject, $body)) {
    echo("<p>Message successfully sent!</p>");
} else {
    echo("<p>Message delivery failed...</p>");
}
?>

我还更改了php.ini中的smtp设置 如

SMTP = mail.gmail.com   
smtp_port = 25

但是,它仍然无法正常工作,函数mail()无效。 请帮帮我

6 个答案:

答案 0 :(得分:1)

尝试使用带有Gmail的SMTP服务器。

ini_set("SMTP","ssl://smtp.gmail.com");
ini_set("smtp_port","465");

好读

Send email from localhost with gmail

答案 1 :(得分:1)

您可以在python中运行此代码段,这样您就可以在localhost中设置服务器。在php.ini中没有什么需要改变。 (在php.ini中smtp应为localhost,端口应为25.默认设置)。希望这可以帮助。 :)

import smtpd
import smtplib
import asyncore
class SMTPServer(smtpd.SMTPServer):

    def __init__(*args, **kwargs):
        print "Running smtp server on port 25"
        smtpd.SMTPServer.__init__(*args, **kwargs)

    def process_message(*args, **kwargs):
        to = args[3][0]
        msg = args[4]
        gmail_user = 'yourgmailhere'
        gmail_pwd = 'yourgmailpassword'
        smtpserver = smtplib.SMTP("smtp.gmail.com",587)
        smtpserver.ehlo()
        smtpserver.starttls()
        smtpserver.ehlo
        smtpserver.login(gmail_user, gmail_pwd)
        smtpserver.sendmail(gmail_user, to, msg)
        print 'sent to '+to
        pass

if __name__ == "__main__":
    smtp_server = SMTPServer(('localhost', 25), None)
    try:
        asyncore.loop()
    except KeyboardInterrupt:
        smtp_server.close()

答案 2 :(得分:0)

100%正常工作,我也在我的网站上使用过这个

<?php
$con=mysql_connect("mysql12","","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
$db=mysql_select_db("data",$con);
if(!$db)
{
die( 'Could not select database'.mysql_error() );
}

$to=$_POST['to'];
$subject=$_POST['subject'];
$body=$_POST['tarea'];

$query="select fname from table where email='$to'";
$fetch=mysql_query($query);

while ($rows=mysql_fetch_array($fetch)) 
{
 $name=$rows['fname'];


$headers  = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= "To:" .$name. "\r\n";
$headers .= 'From: <abcd@gmail.com>' . "\r\n";
mail($to, $subject, $body, $headers);
}

答案 3 :(得分:0)

Colin Morelli是正确的,您需要进行身份验证(登录)才能使用gmail的smtp服务器。以下是工作代码。参考。 Send email using the GMail SMTP server from a PHP page

<?php

       require_once "Mail.php";

        $from = "<from.gmail.com>";
        $to = "<to.yahoo.com>";
        $subject = "Hi!";
        $body = "Hi,\n\nHow are you?";

        $host = "ssl://smtp.gmail.com";
        $port = "465";
        $username = "myaccount@gmail.com";  //<> give errors
        $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-->

P.S。你不能这样做:

<?php
// The message
$message = "Line 1\r\nLine 2\r\nLine 3";

// In case any of our lines are larger than 70 characters, we should use wordwrap()
$message = wordwrap($message, 70, "\r\n");

// Send
mail('caffeinated@example.com', 'My Subject', $message);
?>

参考。 http://php.net/manual/en/function.mail.php

修改

如果你想使用一个简单的类,你可以在不使用服务器mod的情况下抛出FTP,只需使用PHPMailer:

require_once('../class.phpmailer.php');
//include("class.smtp.php"); // optional, gets called from within class.phpmailer.php if not already loaded

$mail             = new PHPMailer();

$body             = file_get_contents('contents.html');
$body             = eregi_replace("[\]",'',$body);

$mail->IsSMTP(); // telling the class to use SMTP
$mail->Host       = "mail.yourdomain.com"; // SMTP server
$mail->SMTPDebug  = 2;                     // enables SMTP debug information (for testing)
                                           // 1 = errors and messages
                                           // 2 = messages only
$mail->SMTPAuth   = true;                  // enable SMTP authentication
$mail->SMTPSecure = "tls";                 // sets the prefix to the servier
$mail->Host       = "smtp.gmail.com";      // sets GMAIL as the SMTP server
$mail->Port       = 587;                   // set the SMTP port for the GMAIL server
$mail->Username   = "yourusername@gmail.com";  // GMAIL username
$mail->Password   = "yourpassword";            // GMAIL password

$mail->SetFrom('name@yourdomain.com', 'First Last');

$mail->AddReplyTo("name@yourdomain.com","First Last");

$mail->Subject    = "PHPMailer Test Subject via smtp (Gmail), basic";

$mail->AltBody    = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test

$mail->MsgHTML($body);

$address = "whoto@otherdomain.com";
$mail->AddAddress($address, "John Doe");

$mail->AddAttachment("images/phpmailer.gif");      // attachment
$mail->AddAttachment("images/phpmailer_mini.gif"); // attachment

if(!$mail->Send()) {
  echo "Mailer Error: " . $mail->ErrorInfo;
} else {
  echo "Message sent!";
}

参考。 http://phpmailer.worxware.com/index.php?pg=examplebgmail

答案 4 :(得分:0)

php.ini中的SMTP设置仅适用于Windows主机。

如果您没有运行Windows系统,则应使用适当的类来实现SMPT功能或相应地配置本地sendmail / MTA。

答案 5 :(得分:0)

好的,我看到不久前遇到的问题

你需要一个邮件服务器pop3服务器或smtp这需要一个静态的ip和域名服务器,即localhost不能工作

这样设置CURL My Curl Function相应地调整

    function CurlMail($The_mail, $The_FamKey, $The_Service ,$The_Client)
{

        //create array of data to be posted

        $post_data['email'] = $The_mail;
        $post_data['FamilyKey'] = $The_FamKey;
        $post_data['Service'] = $The_Service;
        $post_data['Client'] = $The_Client;

        //traverse array and prepare data for posting (key1=value1)
        foreach ( $post_data as $key => $value) 
                {
                    $post_items[] = $key . '=' . $value;
                }
        //create the final string to be posted using implode()
        $post_string = implode ('&', $post_items);
        //create cURL connection
        $curl_connection =  curl_init('http://foo.com/mail.php');
        //set options
        curl_setopt($curl_connection, CURLOPT_CONNECTTIMEOUT, 30);
        curl_setopt($curl_connection, CURLOPT_USERAGENT,  "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)");
        curl_setopt($curl_connection, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl_connection, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl_connection, CURLOPT_FOLLOWLOCATION, 0);
        //set data to be posted
        curl_setopt($curl_connection, CURLOPT_POSTFIELDS, $post_string);
        //perform our request
        $result = curl_exec($curl_connection);
        //show information regarding the request
        print_r(curl_getinfo($curl_connection));
        echo curl_errno($curl_connection) . '-' .curl_error($curl_connection);
        //close the connection
        curl_close($curl_connection);
    }

然后在设置了SMTP的Live服务器上,请参阅php.ini以获取这些详细信息 MAIL.PHP

ini_set('SMTP', "127.0.0.1");
ini_set('smtp_port', "25");

 $to = "abc@gmail.com";
 $subject = "Test mail";
 $message = "Hello! This is a simple email message.";
 $from = "jono@bay.org";
 $headers = "From:" . $from;
 mail($to,$subject,$message,$headers);
 echo "Mail Sent.";