Search code examples
phpsmtpphpmailer

Phpmailer working fine in localhost But not in server


date_default_timezone_set('Asia/Dubai');
include("classes/class.phpmailer.php");

$mail = new PHPMailer();
$body = "this is <strong>testing</strong> mail ". date('Y-m-d H:i:s');

$mail->IsSMTP(); // telling the class to use SMTP
$mail->SMTPDebug  = 1;


$mail->SMTPAuth   = true;
$mail->SMTPSecure = "ssl";               
$mail->Host       = "smtp.gmail.com";      
$mail->Port       = 465;              
$mail->Username   = 'my@email.com';
$mail->Password   = '*******';

$mail->SetFrom('my@email.com', 'First Last');
$mail->AddReplyTo('my@email.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 = "to@email.com"; // add your address here 
$mail->AddAddress($address, "Gmail Test");

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

I have script like this.Its working fine with localhost but when i moving to windows or linux servers it won't work.I want to work on both windows and linux servers.What should i do?

Error like this: SMTP -> ERROR: Failed to connect to server: Connection timed out (110) SMTP Error: Could not connect to SMTP host. Mailer Error: SMTP Error: Could not connect to SMTP host.


Solution

  • try using this :

    require_once ( 'class.phpmailer.php' ); // Add the path as appropriate
    $Mail = new PHPMailer();
    $Mail->IsSMTP(); // Use SMTP
    $Mail->Host        = "smtp.gmail.com"; // Sets SMTP server
     $Mail->SMTPDebug   = 2; // 2 to enable SMTP debug information
    $Mail->SMTPAuth    = TRUE; // enable SMTP authentication
    $Mail->SMTPSecure  = "tls"; //Secure conection
    $Mail->Port        = 587; // set the SMTP port
    $Mail->Username    = 'MyGmail@gmail.com'; // SMTP account username
    $Mail->Password    = 'MyGmailPassword'; // SMTP account password
    $Mail->Priority    = 1; // Highest priority - Email priority (1 = High, 3 = Normal, 5 = low)
    $Mail->CharSet     = 'UTF-8';
    $Mail->Encoding    = '8bit';
    $Mail->Subject     = 'Test Email Using Gmail';
    $Mail->ContentType = 'text/html; charset=utf-8\r\n';
    $Mail->From        = 'MyGmail@gmail.com';
    $Mail->FromName    = 'GMail Test';
    $Mail->WordWrap    = 900; // RFC 2822 Compliant for Max 998 characters per  line
    
    $Mail->AddAddress( $ToEmail ); // To:
    $Mail->isHTML( TRUE );
    $Mail->Body    = $MessageHTML;
    $Mail->AltBody = $MessageTEXT;
    $Mail->Send();
    $Mail->SmtpClose();
    
     if ( $Mail->IsError() ) { 
      echo "ERROR<br /><br />";
     }
     else {
      echo "OK<br /><br />";
      }