lithemod/mail

基于PHPMailer的邮件发送包,简化了PHP应用程序中发送SMTP邮件的过程。它提供了与lithemodules/support-env包的集成,使用环境变量确保安全灵活的配置。

v1.0.0 2024-10-02 09:52 UTC

This package is auto-updated.

Last update: 2024-10-02 11:03:14 UTC


README

一个简化PHP应用程序中SMTP邮件发送的包,提供对环境变量的灵活集成,便于配置。

安装

您可以通过 Composer 安装此包。在您的终端中运行以下命令

composer require lithemod/mail

请确保环境变量包配置正确,因为 support-mail 依赖于这些设置。

使用方法

以下是如何使用此包发送电子邮件的全面指南

1. 设置环境变量

在您的项目根目录下创建一个 .env 文件并定义您的邮件设置

MAIL_HOST=smtp.yourprovider.com
MAIL_PORT=587
MAIL_USERNAME=your-email@domain.com
MAIL_PASSWORD=your-password
MAIL_ENCRYPTION=tls
MAIL_FROM_ADDRESS=noreply@domain.com
MAIL_FROM_NAME=Your Name or Company

2. 发送简单的文本邮件

<?php

require 'vendor/autoload.php';

use Lithe\Support\Mail;
use Lithe\Support\Env;

// Load environment variables
Env::load(__DIR__);

// Send the email
$mail = Mail::to('recipient@domain.com', 'Recipient Name')
    ->subject('Email Subject')
    ->text('Body of the email in plain text')
    ->send();

if ($mail) {
    echo 'Email sent successfully!';
} else {
    echo 'Failed to send email.';
}

3. 发送HTML邮件

<?php

$mail = Mail::to('recipient@domain.com', 'Recipient Name')
    ->subject('Email Subject')
    ->html('<h1>Email body in HTML</h1>')
    ->send();

if ($mail) {
    echo 'Email sent successfully!';
} else {
    echo 'Failed to send email.';
}

4. 添加抄送(Cc)和密送(Bcc)收件人

您可以使用以下方法向邮件中添加抄送(Cc)和密送(Bcc)收件人

添加抄送(Cc)

$mail = Mail::to('recipient@domain.com', 'Recipient Name')
    ->cc('cc@example.com', 'CC Name')
    ->subject('Email Subject')
    ->text('Body of the email in plain text')
    ->send();

添加密送(Bcc)

$mail = Mail::to('recipient@domain.com', 'Recipient Name')
    ->bcc('bcc@example.com', 'BCC Name')
    ->subject('Email Subject')
    ->text('Body of the email in plain text')
    ->send();

5. 设置回复地址

您可以使用 replyTo 方法设置回复地址

$mail = Mail::to('recipient@domain.com', 'Recipient Name')
    ->replyTo('replyto@example.com', 'Reply-To Name')
    ->subject('Email Subject')
    ->text('Body of the email in plain text')
    ->send();

6. 添加文件附件

要向邮件添加文件附件,请使用 attach 方法

$mail = Mail::to('recipient@domain.com', 'Recipient Name')
    ->subject('Email Subject')
    ->text('Body of the email in plain text')
    ->attach('/path/to/file.txt', 'CustomFilename.txt')
    ->send();

7. 添加自定义头部

您可以根据以下方式向邮件添加自定义头部

$mail = Mail::to('recipient@domain.com', 'Recipient Name')
    ->subject('Email Subject')
    ->text('Body of the email in plain text')
    ->addHeader('X-Custom-Header', 'HeaderValue')
    ->send();

需求

  • PHP 7.4 或更高版本
  • .env 文件中配置的环境变量

许可证

本项目采用MIT许可证。有关详细信息,请参阅 LICENSE 文件。