مرکز آموزش

PHP Script SMTP Setup Print

  • 134

PHP Script SMTP Setup


Adjust the example below for your needs. Make sure you change the following variables:

  • from: the sender's email address and name.
  • to: the recipient's email address and name.
  • username: your SMTP username.
  • password: your SMTP password.
  • host: mail.smtp2go.com.

PHP Script to Send Email Using SMTP Authentication

<?php
 require_once "Mail.php";
 require_once "Mail/mime.php";
 
 $from = "Susan Sender <sender@example.com>";
 $to = "Rachel Recipient <recipient@example.com>";
 $subject = "Hi!";
 $text = "Hi,\n\nIt is a text message";
 $html = "It is a <b>HTML</b> message";
 $mime = new Mail_mime();
 $mime->setHTMLBody($html);
 $mime->setTXTBody($text);
 $body = $mime->get();
 
 $host = "mail.africanlab.co.za";
 $port = "2525";
// 8025, 587 and 25 can also be used.

 $username = "smtp_username";
 $password = "smtp_password";
 
 $headers = array ('From' => $from,
   'To' => $to,
   'Subject' => $subject);
 $headers = $mime->headers($headers);
 $smtp = Mail::factory('smtp',
   array ('host' => $host,
     '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>");
  }
 ?>

PHP Script to Send Email Using SMTP Authentication and SSL Encryption

<?php
 require_once "Mail.php";
 require_once "Mail/mime.php";
 
 $from = "Susan Sender <sender@example.com>";
 $to = "Rachel Recipient <recipient@example.com>";
 $subject = "Hi!";
 $text = "Hi,\n\nIt is a text message";
 $html = "It is a <b>HTML</b> message";
 $mime = new Mail_mime();
 $mime->setHTMLBody($html);
 $mime->setTXTBody($text);
 $body = $mime->get();
 
 $host = "ssl://mail.africanlab.co.za";
 $port = "465";
// 8465 can also be used.

 $username = "smtp_username";
 $password = "smtp_password";
 
 $headers = array ('From' => $from,
   'To' => $to,
   'Subject' => $subject);
 $headers = $mime->headers($headers);
 $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>");
  }
 ?>

Please note: If you experience "timeouts" or problems connecting due to an unreliable internet connection, consider increasing the max_execution_time setting in the php.ini file on your server, to a value such as 120 (instead of the default value 30).


آیا این پاسخ به شما کمک کرد؟
Back