search
HomeBackend DevelopmentPHP TutorialWhy can't PHPMailer send emails?

PHPMailer is a useful PHP class for sending emails. It supports sending mail using smtp server, and also supports Sendmail, qmail, Postfix, Imail, Exchange, Mercury, Courier and other mail servers. The SMTP server also supports verification and multiple SMTP sending (but I’m not sure what it’s used for). Email sending can include multiple TO, CC, BCC and REPLY-TO, supports both text and HTML email formats, can automatically wrap lines, and supports Attachments and pictures in various formats, custom email headers and other basic email functions.
Since PHP only contains one mail function, PHPMailer is a great enhancement to it, and I believe it can meet the needs of many people, haha. It mainly includes two class files: class.phpmailer.php for implementing the mail sending function and class.smtp.php for smtp implementation. Then there are files that can achieve various error outputs, as well as very detailed documentation.

PHPMailer cannot connect to the SMTP server, and it has nothing to do with changing the SMTP case.

(2011-10-22 12:17:35)

Reprint▼

Label:

php

phpmailer

Miscellaneous talk

Category: Default category

PHPmailer cannot send emails, prompting error Error: Could not connect to SMTP host

There are two previous articles on the blog, "PHPMailer::Cannot connect to SMTP server" "Two common reasons why PHPMailer cannot connect to SMTP server"
One is for reprinting, the other is for taking notes, but it ends up misleading people. Not everyone can solve the problem.
Friends wrote to me asking for help, and I was also anxious. Although it was solved later, I still couldn’t figure it out, so I calmed down and looked at it again

PHPMailer cannot connect to the SMTP server. Why? First check it with the code:


function Get_host($host){ //Resolve domain name
$Get_host=gethostbyname($host);
echo "Trying to connect $host ...
rn ";
if(!$Get_host){
$str= "Parse failed (1)


";
}elseif($Get_host==$host){
$str= "Parse failed (2): Possibly an invalid hostname
";
}else{
echo "The domain name is resolved to $Get_host...
rn";
Open_host($host);}
echo $str;
}

Function Open_host($host){ //Connect to the host

if(function_exists('fsockopen')){
$fp = fsockopen($host,25,&$errno,&$errstr,60);
elseif(function_exists('pfsockopen')){
echo "The server does not support Fsockopen, try the pFsockopen function...
rn";
$fp = pfsockopen($host,25,&$errno,&$errstr,60); }
else
exit('The server does not support the Fsockopen function');

if(!$fp){
echo "Code name: $errno,
nError reason: $errstr
";
}else{
echo "SMTP server connection ok!
rn";
fwrite($fp, "");
$out0= fgets($fp, 128);
#echo $out0;
if (strncmp($out0,"220",3)==0){ // Determine the three-character content
echo '220 SMTP server response is normal
';
}else{
echo 'Server-side error
';}
}
}
//SMTP server address
$site = array("smtp.163.com","smtp.sina.cn","smtp.sina.com","smtp.qqq.com","smtp.126.com");

//Transport script
#$host="smtp.163.com";
#echo Get_host($host);


for ($i=0; $i {
$host= $site[$i];
echo Get_host($host);
}



PHPmailer is a great PHP class for sending mail. Error handling focuses on problems during the session with the SMTP server, such as error prompts for incorrect authentication and empty recipients. However, error prompts for the process of connecting to SMTP start with "Could not connect to SMTP host" In a word, it has led to many problems that have not been solved. What is even more ridiculous is that it has led to the spread of some useful but unreasonable methods in the world. It can be seen that everything has a certain fate.

Okay, no more talking nonsense.
If you want to understand the reason why Could not connect to SMTP host, you must understand the steps to connect to the service
A complete and effective SMTP sending process should include: resolving the domain name, connecting to the SMTP server, verifying the identity, determining the recipient and the content of the letter, and sending

The above PHP code is to separate these steps, find out the reason, and then find a method. The echoed results may be as follows:

1. Parsing failed (2): It may be an invalid host name
The domain name cannot be resolved. Might be a DNS level issue. Contact the administrator or change service provider

2. The server does not support Fsockopen, try the pFsockopen function
If the connection to the server using the pfsockopen function is successful, modify $this->smtp_conn = fsockopen( in class.smtp.php to $this->smtp_conn = pfsockopen(. Return PHPmailer to normal use

3. Server-side error
Successfully established a connection with the remote host, but the other party did not install the SMTP protocol and sent a 220 response code, indicating that there may be a problem with the SMTP server

4. 220 SMTP server response is normal

Well, whether it is the fsockopen function or the pfsockopen function, it has been connected to the remote SMTP server normally. If you are unable to send emails using PHPmailer, I strongly suggest you change your account and try again

5. Other error reports, such as this

Warning: fsockopen(): unable to connect to smtp163.com:25
You have absolutely reason to believe that the firewall is responsible! In this case, if you cannot contact the administrator to change the firewall rules, you can try the method in "PHPMailer::Cannot connect to SMTP server",
Search
function IsSMTP() {
$this->Mailer = 'smtp';
}

Change to:
function IsSMTP() {
$this->Mailer = 'SMTP';
}

As my title says, "PHPMailer cannot connect to the SMTP server, and it has nothing to do with changing the SMTP case." Of course, I can't play tricks on you in a bad way, but sometimes it really works. The success rate of cure depends on your character

Let’s analyze the reasons.
This code is probably around line 286 of class.phpmailer.php. This function must be called first when using the PHPmailer class to declare the method of sending mail

Trace this->Mailer to about line 400 of class.smtp.php

switch($this->Mailer) {
case 'sendmail':
        $result = $this->SendmailSend($header, $body);
          break;
Case 'smtp':
        $result = $this->SmtpSend($header, $body);
          break;
case 'mail':
        $result = $this->MailSend($header, $body);
          break;
​​​default:
        $result = $this->MailSend($header, $body);
Break;

First of all, smtp is definitely not equal to SMTP! I have forgotten this basic principle.
Therefore, if the above conditions are not met, PHPmailer will execute $result = $this->MailSend($header, $body);this sentence

Let’s trace the MailSend() function at around line 460 of class.phpmailer.php:

  function MailSend($header, $body) {
    $to = '';
    for($i = 0; $i to); $i++) {
      if($i != 0) { $to .= ', '; }
      $to .= $this->AddrFormat($this->to[$i]);
    }

    $toArr = split(',', $to);

    $params = sprintf("-oi -f %s", $this->Sender);
    if ($this->Sender != '' && strlen(ini_get('safe_mode'))        $old_from = ini_get('sendmail_from');
      ini_set('sendmail_from', $this->Sender);
      if ($this->SingleTo === true && count($toArr) > 1) {
        foreach ($toArr as $key => $val) {
          $rt = @mail($val, $this->EncodeHeader($this->SecureHeader($this->Subject)), $body, $header, $params);
        }
      } else {
        $rt = @mail($to, $this->EncodeHeader($this->SecureHeader($this->Subject)), $body, $header, $params);
      }
    } else {
      if ($this->SingleTo === true && count($toArr) > 1) {
        foreach ($toArr as $key => $val) {
          $rt = @mail($val, $this->EncodeHeader($this->SecureHeader($this->Subject)), $body, $header, $params);
        }
      } else {
        $rt = @mail($to, $this->EncodeHeader($this->SecureHeader($this->Subject)), $body, $header);
      }
    }

    if (isset($old_from)) {
      ini_set('sendmail_from', $old_from);
    }

    if(!$rt) {
      $this->SetError($this->Lang('instantiate'));
      return false;
    }

    return true;
  }


注意$rt = @mail( 这是用PHP内置的mail函数发信啊!


来自W3School的mail发信实例

$to = "somebody@example.com"; //这里改成你的邮箱地址
$subject = "My subject";
$txt = "Hello world!";
$headers = "From: dongfangtianyu@qq.com" . "rn" .
mail($to,$subject,$txt,$headers);
?>


如果在你的服务器上运行这脚本能够收到邮件,那么你完全可以用修改SMTP大小写的方法。不过,毕竟不大好用

 

以上就介绍了PHPMailer为什么不能发送邮件,包括了PHPMailer发送邮件方面的内容,希望对PHP教程有兴趣的朋友有所帮助。

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
What is the difference between unset() and session_destroy()?What is the difference between unset() and session_destroy()?May 04, 2025 am 12:19 AM

Thedifferencebetweenunset()andsession_destroy()isthatunset()clearsspecificsessionvariableswhilekeepingthesessionactive,whereassession_destroy()terminatestheentiresession.1)Useunset()toremovespecificsessionvariableswithoutaffectingthesession'soveralls

What is sticky sessions (session affinity) in the context of load balancing?What is sticky sessions (session affinity) in the context of load balancing?May 04, 2025 am 12:16 AM

Stickysessionsensureuserrequestsareroutedtothesameserverforsessiondataconsistency.1)SessionIdentificationassignsuserstoserversusingcookiesorURLmodifications.2)ConsistentRoutingdirectssubsequentrequeststothesameserver.3)LoadBalancingdistributesnewuser

What are the different session save handlers available in PHP?What are the different session save handlers available in PHP?May 04, 2025 am 12:14 AM

PHPoffersvarioussessionsavehandlers:1)Files:Default,simplebutmaybottleneckonhigh-trafficsites.2)Memcached:High-performance,idealforspeed-criticalapplications.3)Redis:SimilartoMemcached,withaddedpersistence.4)Databases:Offerscontrol,usefulforintegrati

What is a session in PHP, and why are they used?What is a session in PHP, and why are they used?May 04, 2025 am 12:12 AM

Session in PHP is a mechanism for saving user data on the server side to maintain state between multiple requests. Specifically, 1) the session is started by the session_start() function, and data is stored and read through the $_SESSION super global array; 2) the session data is stored in the server's temporary files by default, but can be optimized through database or memory storage; 3) the session can be used to realize user login status tracking and shopping cart management functions; 4) Pay attention to the secure transmission and performance optimization of the session to ensure the security and efficiency of the application.

Explain the lifecycle of a PHP session.Explain the lifecycle of a PHP session.May 04, 2025 am 12:04 AM

PHPsessionsstartwithsession_start(),whichgeneratesauniqueIDandcreatesaserverfile;theypersistacrossrequestsandcanbemanuallyendedwithsession_destroy().1)Sessionsbeginwhensession_start()iscalled,creatingauniqueIDandserverfile.2)Theycontinueasdataisloade

What is the difference between absolute and idle session timeouts?What is the difference between absolute and idle session timeouts?May 03, 2025 am 12:21 AM

Absolute session timeout starts at the time of session creation, while an idle session timeout starts at the time of user's no operation. Absolute session timeout is suitable for scenarios where strict control of the session life cycle is required, such as financial applications; idle session timeout is suitable for applications that want users to keep their session active for a long time, such as social media.

What steps would you take if sessions aren't working on your server?What steps would you take if sessions aren't working on your server?May 03, 2025 am 12:19 AM

The server session failure can be solved through the following steps: 1. Check the server configuration to ensure that the session is set correctly. 2. Verify client cookies, confirm that the browser supports it and send it correctly. 3. Check session storage services, such as Redis, to ensure that they are running normally. 4. Review the application code to ensure the correct session logic. Through these steps, conversation problems can be effectively diagnosed and repaired and user experience can be improved.

What is the significance of the session_start() function?What is the significance of the session_start() function?May 03, 2025 am 12:18 AM

session_start()iscrucialinPHPformanagingusersessions.1)Itinitiatesanewsessionifnoneexists,2)resumesanexistingsession,and3)setsasessioncookieforcontinuityacrossrequests,enablingapplicationslikeuserauthenticationandpersonalizedcontent.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool