onviser/mailer

用于通过SMTP发送带附件的电子邮件的PHP库

1.0.3 2024-04-02 12:40 UTC

This package is auto-updated.

Last update: 2024-10-02 13:42:31 UTC


README

通过套接字简单发送电子邮件。在共享主机上方便使用,因为在共享主机上使用PHP mail()函数可能存在一些问题。

安装

composer require onviser/mailer

如何使用

发送简单电子邮件

$mail = (new Mail())
            ->setSubject('This is a subject')
            ->setBody('This is a body')
            ->setFrom('from@example.com')
            ->to('to@example.com');
            
$socket = new Socket('localhost', 25, 'login', 'password');            
$mailer = new SendToSocketMailer($socket);
if ($mailer->send($mail)) {
    // mail was sent    
} else { // error
    echo "error: {$mailer->getError()}" . PHP_EOL;
    print_r($mailer->getLog());
}

带有抄送和密送头的电子邮件

$mail = (new Mail())
            ->setSubject('This is a subject')
            ->setBody('This is a body')
            ->setFrom('from@example.com')
            ->to('to1@example.com')
            ->to('to2@example.com')
            ->copy('copy1@example.com')
            ->copy('copy2@example.com')
            ->blindCopy('blind-copy@example.com');

带有"回复到"头部的电子邮件

$mail = (new Mail())
            ->setSubject('This is a subject')
            ->setBody('This is a body')
            ->setFrom('from@example.com')
            ->setReplayTo('replay-to@example.com')
            ->to('to@example.com');

带有附件的电子邮件

$attachmentText = (new Attachment())
                    ->setFileName('file.txt')
                    ->setFileType('text/plain')
                    ->setData('This is a text.');
$attachmentHTML = (new Attachment())
                    ->setFileName('file.html')
                    ->setFileType('text/html')
                    ->setData('<p>This is a <strong>HTML</strong>.</p>');
$mail = (new Mail())
            ->setType(Mail::TYPE_HTML)
            ->setSubject('This is a subject')
            ->setBody('<p>This is a <strong>HTML</strong> body</p>')
            ->setFrom('from@example.com')
            ->to('to@example.com')
            ->attachment($attachmentText)
            ->attachment($attachmentHTML);

发送到文件(用于开发环境)

在开发过程中,将电子邮件存储在磁盘上而不是发送它们会更方便。

$mail = (new Mail())
            ->setSubject('This is a subject')
            ->setBody('This is a body')
            ->setFrom('from@example.com')
            ->to('to@example.com');
            
$mailer = new SendToFileMailer('../var/mail/');
if ($mailer->send($mail)) {
    // mail was saved    
} else { // error
    echo "error: {$mailer->getError()}" . PHP_EOL;
}

测试

./vendor/bin/phpunit
./vendor/bin/phpstan

PHP-用于通过SMTP发送带附件的电子邮件的库

通过套接字简单发送电子邮件。在虚拟主机上方便使用,因为在虚拟主机上使用PHP mail()函数可能存在一些问题。