安装symfony/mailer
composer require symfony/mailer
简单使用
<?php
namespace unitls;
use Symfony\Component\Mailer\Transport;
use Symfony\Component\Mailer\Mailer;
use Symfony\Component\Mime\Email;
/**
* @description: 使用smtp发送邮件
*/
class SendMail
{
/**
* @description: 邮件host
* 使用163邮箱,对应值是smtp.163.com,
* 使用QQ邮箱,对应值是smtp.qq.com
* 使用腾讯企业邮箱,对应值是smtp.exmail.qq.com
* @var string
*/
private $_host = '';
/**
* @description: 邮件port
* 默认值是25,
* 使用SSL加密,值为465或587
* @var string
*/
private $_port = '';
/**
* @description: 邮件用户名
* @var string
*/
private $_username = '';
/**
* @description: 邮件授权码
* @var string
*/
private $_password = '';
/**
* @description: 邮件对象
* @var Mailer
*/
private $_mailer;
/**
* @description: 邮件内容
* @var Email
*/
public $email;
public function __construct()
{
$dsn = "smtp://{$this->_username}:{$this->_password}@{$this->_host}:{$this->_port}";
$transport = Transport::fromDsn($dsn);
$this->_mailer = new Mailer($transport);
$this->email = new Email();
$this->setFrom();
}
/**
* @description: 设置邮件发送者
* @param array|string $from 发送者邮箱
* @return {*}
*/
public function setFrom($from = '')
{
$from = $from ?: $this->_username;
$this->email->from($from);
return $this;
}
/**
* @description: 设置邮件接收者者
* @param array|string $from 接收者邮箱
* @return {*}
*/
public function setTo($to)
{
$this->email->to($to);
return $this;
}
/**
* @description: 设置邮件内容
* @param string $subject 主题
* @param string $content 内容
* @return {*}
*/
public function setContent($subject, $content)
{
$this->email->subject($subject)->text($content);
return $this;
}
/**
* @description: 发送邮件
* @param {*}
* @return {*}
*/
public function send()
{
$this->_mailer->send($this->email);
}
}