4

I want to send an email from localhost to gmail server forexample (anydomain@gmail.com).

Code sample is:

<?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>");
}
?>

I have also changed the smtp setting in php.ini as

SMTP = mail.gmail.com   
smtp_port = 25

But, its still not working, the function mail() is not working. Please help me

CloudyMarble
  • 36,908
  • 70
  • 97
  • 130
Rahil
  • 281
  • 1
  • 4
  • 13
  • Let me clear the question again "i want to send email from local host to an email address,,, i dont want to send from local host to local host" – Rahil Feb 05 '13 at 13:47

6 Answers6

1

Try using SMTP server with gmail.

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

Good read

Send email from localhost with gmail

Community
  • 1
  • 1
NullPoiиteя
  • 56,591
  • 22
  • 125
  • 143
  • 2
    Gmail's SMTP service will require you to authenticate. You'll have better luck installing `sendmail` or something similar on your linux server to send the emails for you. – Colin M Feb 05 '13 at 14:00
  • yup it can be done by phpmailer or pear mail package or something like that and set gmail username and password – NullPoiиteя Feb 05 '13 at 14:07
1

You can run this snippet of code in python which will allow you to set up a server in localhost. Nothing needs to be changed in php.ini . (In php.ini smtp should be localhost, port should be 25. The default settings). Hope this helps. :)

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()
ppsreejith
  • 3,318
  • 2
  • 25
  • 27
0

100% working, i have used this in my website too

<?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);
}
  • Dont forget to use: $headers = 'MIME-Version: 1.0' . "\r\n"; $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n"; –  Feb 05 '13 at 14:04
0

Colin Morelli is correct in that you will need to authenticate (log in) to use gmail's smtp server. The following is working code. Ref. 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. Can't you just do:

<?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);
?>

Ref. http://php.net/manual/en/function.mail.php

EDIT:

If you want to use a simple class that you can throw in FTP without making server mods, just use 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!";
}

Ref. http://phpmailer.worxware.com/index.php?pg=examplebgmail

Community
  • 1
  • 1
user1477388
  • 20,790
  • 32
  • 144
  • 264
0

The SMTP settings in php.ini only work for Windows hosts.

If you are not running a Windows system you should use an appropriate class to implement SMPT functionality or configure your local sendmail/MTA accordingly.

Ben.
  • 101
  • 1
0

Ok I see the problem I came across this not so long ago

You need a mail server pop3 server or smtp Which requires a static ip and domain named server i.e localhost wont work

Do this set up CURL My Curl Function adjust accordingly

    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);
    }

Then On a Live server with SMTP set up refer to php.ini for these details 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.";
J. Steen
  • 15,470
  • 15
  • 56
  • 63
JonoJames
  • 1,117
  • 8
  • 22