dadadev / imap-bundle
1.0.1
2022-01-10 06:47 UTC
Requires
- php: >=7.4.0
- php-imap/php-imap: ~3.0|~4.0
- symfony/dependency-injection: ~4.0|~5.0|~6.0
- symfony/framework-bundle: ~4.0|~5.0|~6.0
README
为 Symfony 2.8, 3.x, 4.x, 5.x 和 6.x 提供简单的 php-imap 集成。
安装
1. Composer
从命令行运行
$ composer require dadadev/imap-bundle
如果你使用 Symfony Flex,那么你已经完成并可以进入配置部分。否则,你必须手动注册此包。
2. 注册包
如果你没有使用 Symfony Flex,你必须通过在你的 AppKernel 中添加包声明来手动注册此包。
class AppKernel extends Kernel { public function registerBundles() { $bundles = [ ... new DaDaDev\ImapBundle\ImapBundle(), ]; ... } }
配置
设置您的邮箱配置。如果你使用的是 symfony 2.8 或 3.x 而没有使用 Symfony Flex,请将配置添加到 app/config/config.yml 中。如果你使用的是 Symfony 4 或使用 Flex 的 Symfony 3.x,请打开 config/packages/imap.yaml 并调整其内容。
以下是一个示例配置
imap: connections: example_connection: mailbox: "{localhost:993/imap/ssl/novalidate-cert}INBOX" username: "email@example.com" password: "password" another_connection: mailbox: "{localhost:143}INBOX" username: "username" password: "password" attachments_dir: "%kernel.root_dir%/../var/imap/attachments" server_encoding: "UTF-8"
如果你使用 Symfony 连接到 Microsoft 365 商业环境,你很可能需要连接到共享邮箱。在这种情况下,你需要指定参数 authuser 和 user。其中 shared_account 是不带域的用户名,例如
imap: connections: example_connection: mailbox: "{outlook.office365.com:993/imap/ssl/authuser=first.last@example.com/user=shared_account}Root/Folder" username: "email@example.com" password: "password"
使用方法
使用自动注入
在你的控制器中
<?php namespace App\Controller; use DaDaDev\ImapBundle\Service\Imap; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; class IndexController extends AbstractController { public function indexAction(Imap $imap) { $exampleConnection = $imap->get('example_connection'); $anotherConnection = $imap->get('another_connection'); ... } ... }
使用服务容器
在你的控制器中
<?php namespace App\Controller; use DaDaDev\ImapBundle\Service\Imap; use Symfony\Bundle\FrameworkBundle\Controller\Controller; class IndexController extends Controller { public function indexAction() { $exampleConnection = $this->get('dadadev.imap')->get('example_connection'); $anotherConnection = $this->get('dadadev.imap')->get('another_connection'); ... } ... }
从这一点开始,你可以使用由 php-imap 库提供的任何方法。例如
$exampleConnection = $this->get('dadadev.imap')->get('example_connection'); $exampleConnection->getMailboxInfo();
要快速测试与服务器的连接,你可以使用 testConnection() 方法
// testing with a boolean response $isConnectable = $this->get('dadadev.imap')->testConnection('example_connection'); var_dump($isConnectable); // testing with a full error message try { $isConnectable = $this->get('dadadev.imap')->testConnection('example_connection', true); } catch (\Exception $exception) { echo $exception->getMessage(); }
请注意,这将断开你当前的连接并在成功时创建一个新的连接。在大多数情况下,这不会成问题。