簡體   English   中英

CodeIgnititer 4:無法使用 PHP SMTP 發送 email

[英]CodeIgnititer 4: Unable to send email using PHP SMTP

我閱讀了與該問題相關的所有其他答案,但沒有一個有幫助。

當我嘗試在本地主機生產服務器上運行以下設置時,我收到以下錯誤消息:

Unable to send email using PHP SMTP. Your server might not be configured to send mail using this method.

我安裝了 CodeIgniter 4 並將以下內容添加到.env

email.production.protocol = smtp
email.production.SMTPHost = my.server.com
email.production.SMTPUser = My@Mail.com
email.production.SMTPPass = MyPassword
email.production.SMTPCrypto = ssl
email.production.SMTPPort = 465
email.production.SMTPFromName = "Foo Bar"

對於端口465587和加密ssltsl ,我嘗試了所有可能的選項。 app/Config/Email.php中設置public $newline = "\r\n"; 已經設置(建議來自這里

我成功地能夠運行

telnet my.server.com 465
telnet my.server.com 587

然后我將以下代碼添加到app/Config/Email.php的末尾:

public function __construct()
    {
        $this->protocol = $_ENV['email.production.protocol'];
        $this->SMTPHost = $_ENV['email.production.SMTPHost'];
        $this->SMTPUser = $_ENV['email.production.SMTPUser'];
        $this->SMTPPass = $_ENV['email.production.SMTPPass'];
        $this->SMTPPort = $_ENV['email.production.SMTPPort'];
        $this->SMTPCrypto = $_ENV['email.production.SMTPCrypto'];
        $this->fromEmail = $_ENV['email.production.SMTPUser'];
        $this->fromName = $_ENV['email.production.SMTPFromName'];
    }

在我的 Controller 中,我添加了一個 function :

$email = \Config\Services::email();
$email->setSubject("Test");
$email->setMessage("Test");
$email->setTo("myaddress@example.com");
if ($email->send(false)) {
    return $this->getResponse([
        'message' => 'Email successfully send',
    ]);
} else {
    return $this
        ->getResponse(
            ["error" => $email->printDebugger()],
            ResponseInterface::HTTP_CONFLICT
        );
}

調用此 function 會產生上述錯誤消息。 我假設這與錯誤消息描述的服務器配置無關,因為這是在本地主機和生產環境中發生的。

更新:這一定與 CI 設置有關。 無論我嘗試使用什么服務器,即使使用完全不正確的值(例如不正確的密碼),錯誤也完全相同。

我通常使用 smtp gmail 為我的客戶發送 email。 “通過 smtp gmail 發送 email”最重要的是您必須更新您的 Gmail 安全規則:

  1. 在您的 Gmail 帳戶中,點擊管理您的 Google 帳戶
  2. 單擊選項卡安全
  3. 然后,將“安全性較低的應用程序訪問權限”設置為“開啟”

之后,您可以像這樣設置“app\config\EMail.php”:

    public $protocol = 'smtp';
    public $SMTPHost = 'smtp.gmail.com';
    public $SMTPUser = 'your.googleaccount@gmail.com';
    public $SMTPPass = 'yourpassword';
    public $SMTPPort = 465;
    public $SMTPCrypto = 'ssl';
    public $mailType = 'html';

最后,您可以像這樣在 controller 上創建 sendEmai function:

$email = \Config\Services::email();

$email->setFrom('emailsender@gmail.com', 'Mr Sender');
$email->setTo('emailreceiver@gmail.com');


$email->setSubject('Test Subject');
$email->setMessage('Test My SMTP');

if (!$email->send()) {

    return false;

 }else{

    return true;

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM