"yurunsoft/phpmailer-swoole":"~1.0"
服務層
<?php
declare(strict_types=1);
namespace App\Service;
use Hyperf\Utils\Context;
use PHPMailer\PHPMailer\PHPMailer;
class SendEmailService
{
public function doSendEmail()
{
$channel = new \Swoole\Coroutine\Channel();
co(function() use ($channel) {
$mail = new PHPMailer; //PHPMailer物件
$mail->CharSet = 'UTF-8'; //設定郵件編碼,預設ISO-8859-1,如果發中文此項必須設定,否則亂碼
$mail->IsSMTP(); // 設定使用SMTP服務
$mail->SMTPDebug = 0; // 關閉SMTP除錯功能
$mail->SMTPAuth = true; // 啟用 SMTP 驗證功能
$mail->SMTPSecure = 'ssl'; // 使用安全協議
$mail->Host = 'smtp.163.com'; // SMTP 伺服器
$mail->Port = '465'; // SMTP伺服器的埠號
$mail->Username = ''; // SMTP伺服器使用者名稱
$mail->Password = ''; // SMTP伺服器密碼
$mail->SetFrom('', ''); // 郵箱,暱稱
$mail->Subject = 'title test';
$mail->MsgHTML('hello world');
$mail->AddAddress(''); // 收件人
$result = $mail->Send();
$channel->push($result);
});
return $channel->pop();
}
}
使用
<?php
declare(strict_types=1);
namespace App\Service;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Guzzle\ClientFactory;
class SendSmsService
{
/**
* @Inject
* @var ClientFactory
*/
private $clientFactory;
public function doSendSms($phone)
{
$code = mt_rand(100000, 999999);
$string = '';
try {
// $options 等同於 GuzzleHttp\Client 建構函式的 $config 引數
$options = [];
// $client 為協程化的 GuzzleHttp\Client 物件
$client = $this->clientFactory->create($options);
$api_send_url = 'https://*.com/sendsms';
//介面引數
$postFields = array (
'clientid' => '',
'password' => '',
'mobile' => $phone,
'content' => $string,
);
$jsonFields = json_encode($postFields);
$response = $client->request('POST', $api_send_url, [
'body' => $jsonFields,
'headers' => array(
'Accept-Encoding: identity',
'Content-Length: ' . strlen($jsonFields),
'Accept:application/json',
'Content-Type: application/json; charset=utf-8' //json版本需要填寫 Content-Type: application/json;
),
]);
$body = $response->getBody();
$result = json_decode($body,true);
if ($result) {
//do something
return ['code' => 200,'msg' => '傳送成功!'];
} else {
return ['code' => 500,'msg' => '傳送失敗!'];
}
} catch (\Throwable $e) {
return ['code' => 500,'msg' => $e->getMessage()];
}
}
}
本作品採用《CC 協議》,轉載必須註明作者和本文連結