PHP code example of liwenyu / yii2-swiftmailer

1. Go to this page and download the library: Download liwenyu/yii2-swiftmailer library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

liwenyu / yii2-swiftmailer example snippets


// 原来的代码完全兼容
$message = Yii::$app->mailer->compose()
    ->setTo('[email protected]')
    ->setSubject('测试邮件')
    ->setHtmlBody('<h1>Hello World!</h1>')
    ->attachFile('/path/to/file.pdf');

Yii::$app->mailer->send($message);

// 新的配置 - Microsoft Graph API
'mailer' => [
    'class' => 'liwenyu\swiftmailer\Mailer',
    'config' => [
        'class' => 'liwenyu\swiftmailer\MicrosoftMailConfig',
        'clientId' => 'your-client-id',
        'clientSecret' => 'your-client-secret',
        'tenantId' => 'your-tenant-id',
        'userEmail' => '[email protected]',
    ],
],

// 新的配置 - 继续使用 SMTP
'mailer' => [
    'class' => 'liwenyu\swiftmailer\Mailer',
    'useSmtp' => true, // 启用 SMTP 模式
    'transport' => [
        'class' => 'Swift_SmtpTransport',
        'host' => 'smtp.gmail.com',
        'username' => '[email protected]',
        'password' => 'your-password',
        'port' => '587',
        'encryption' => 'tls',
    ],
],

// 原来的代码完全兼容,无需任何修改
$message = Yii::$app->mailer->compose()
    ->setTo('[email protected]')
    ->setSubject('测试邮件')
    ->setHtmlBody('<h1>Hello World!</h1>')
    ->attachFile('/path/to/file.pdf');

Yii::$app->mailer->send($message);

// config/web.php 或 config/console.php
return [
    'components' => [
        'mailer' => [
            'class' => 'liwenyu\swiftmailer\Mailer',
            'config' => [
                'class' => 'liwenyu\swiftmailer\MicrosoftMailConfig',
                'clientId' => 'your-client-id',
                'clientSecret' => 'your-client-secret',
                'tenantId' => 'your-tenant-id',
                'userEmail' => '[email protected]',
            ],
            'debug' => YII_DEBUG, // 可选,启用调试模式
        ],
    ],
];

// config/web.php 或 config/console.php
return [
    'components' => [
        'mailer' => [
            'class' => 'liwenyu\swiftmailer\Mailer',
            'useSmtp' => true, // 启用 SMTP 模式
            'transport' => [
                'class' => 'Swift_SmtpTransport',
                'host' => 'smtp.gmail.com',
                'username' => '[email protected]',
                'password' => 'your-password',
                'port' => '587',
                'encryption' => 'tls',
            ],
            'debug' => YII_DEBUG, // 可选,启用调试模式
        ],
    ],
];

use Yii;

// 发送简单邮件
$result = Yii::$app->mailer->sendSimpleMail(
    '[email protected]',
    '邮件主题',
    '<h1>Hello World!</h1><p>这是一封测试邮件。</p>',
    'text/html'
);

if ($result) {
    echo "邮件发送成功!";
} else {
    echo "邮件发送失败!";
}

use Yii;

$message = Yii::$app->mailer->compose()
    ->setFrom('[email protected]')
    ->setTo('[email protected]')
    ->setCc('[email protected]')
    ->setBcc('[email protected]')
    ->setSubject('邮件主题')
    ->setHtmlBody('<h1>HTML 内容</h1>')
    ->setTextBody('纯文本内容')
    ->attachFile('/path/to/file.pdf')
    ->attach('custom.txt', '自定义内容', 'text/plain');

$result = Yii::$app->mailer->send($message);

use Yii;

$recipients = [
    '[email protected]',
    '[email protected]',
    '[email protected]',
];

$results = Yii::$app->mailer->sendBulkMail(
    $recipients,
    '批量邮件主题',
    '<p>这是批量发送的邮件内容。</p>',
    'text/html'
);

foreach ($results as $email => $success) {
    echo "{$email}: " . ($success ? '成功' : '失败') . "\n";
}

use Yii;
use liwenyu\swiftmailer\GraphApiService;

// 创建 Graph API 服务实例
$graphService = new GraphApiService([
    'config' => Yii::$app->mailer->config,
]);

// 测试连接
if ($graphService->testConnection()) {
    echo "API 连接正常!";
}

// 获取用户信息
$userInfo = $graphService->getUserInfo();
if ($userInfo) {
    echo "用户: " . $userInfo['displayName'];
}

// 获取邮件列表
$messages = $graphService->getMessages(null, null, 5);
if ($messages && isset($messages['value'])) {
    foreach ($messages['value'] as $message) {
        echo "主题: " . $message['subject'] . "\n";
        echo "发件人: " . $message['from']['emailAddress']['address'] . "\n";
    }
}

// 标记邮件为已读
$graphService->markAsRead('message-id');

// 删除邮件
$graphService->deleteMessage('message-id');

use Yii;

$message = Yii::$app->mailer->compose('welcome-email', [
    'userName' => '张三',
    'activationLink' => 'https://example.com/activate?token=123',
])
    ->setTo('[email protected]')
    ->setSubject('欢迎注册!');

Yii::$app->mailer->send($message);


use yii\helpers\Html;

use Yii;

// 创建草稿
$draftData = [
    'subject' => '草稿邮件',
    'body' => [
        'contentType' => 'HTML',
        'content' => '<p>这是草稿内容</p>',
    ],
    'toRecipients' => [
        [
            'emailAddress' => [
                'address' => '[email protected]',
            ],
        ],
    ],
];

$graphService = new GraphApiService([
    'config' => Yii::$app->mailer->config,
]);

$draft = $graphService->createDraft($draftData);
if ($draft) {
    echo "草稿创建成功,ID: " . $draft['id'];

    // 发送草稿
    $result = $graphService->sendDraft($draft['id']);
    if ($result) {
        echo "草稿发送成功!";
    }
}

use Yii;
use liwenyu\swiftmailer\MicrosoftMailConfig;

try {
    // 验证配置
    $config = new MicrosoftMailConfig([
        'clientId' => 'your-client-id',
        'clientSecret' => 'your-client-secret',
        'tenantId' => 'your-tenant-id',
        'userEmail' => '[email protected]',
    ]);

    if (!$config->validateConfig()) {
        throw new \Exception('Microsoft Mail 配置验证失败');
    }

    // 发送邮件
    $result = Yii::$app->mailer->sendSimpleMail(
        '[email protected]',
        '测试邮件',
        '测试内容'
    );

} catch (\Exception $e) {
    Yii::error('邮件发送错误: ' . $e->getMessage());
    // 处理错误
}

'mailer' => [
    'class' => 'liwenyu\swiftmailer\Mailer',
    'config' => [
        // ... 配置选项
    ],
    'debug' => true, // 启用调试模式
],