阅读(3922) (0)

CodeIgniter4 Email 类

2020-08-14 14:27:46 更新

CodeIgniter强大的电子邮件类支持以下功能:

  • 多种协议:邮件,Sendmail和SMTP
  • SMTP的TLS和SSL加密
  • 多个收件人
  • 抄送和密件抄送
  • HTML或纯文本电子邮件
  • 附件
  • 自动换行
  • 优先事项
  • 密件抄送批处理模式,可将大型电子邮件列表拆分为较小的密件抄送批处理。
  • 电子邮件调试工具

使用电子邮件库

发送邮件

发送电子邮件不仅简单,而且您可以随时对其进行配置,也可以在app / Config / Email.php文件中设置您的首选项。

这是一个基本示例,演示如何发送电子邮件:

$email = \Config\Services::email();


$email->setFrom('your@example.com', 'Your Name');
$email->setTo('someone@example.com');
$email->setCC('another@another-example.com');
$email->setBCC('them@their-example.com');


$email->setSubject('Email Test');
$email->setMessage('Testing the email class.');


$email->send();

设置电子邮件首选项

有21种不同的首选项可用于调整电子邮件的发送方式。您可以按照此处所述手动设置它们,也可以通过存储在配置文件中的偏好设置自动设置它们,如下所述:

通过将一组首选项值传递给电子邮件初始化方法来设置首选项。这是您如何设置某些首选项的示例:

$config['protocol'] = 'sendmail';
$config['mailPath'] = '/usr/sbin/sendmail';
$config['charset']  = 'iso-8859-1';
$config['wordWrap'] = true;


$email->initialize($config);

注解

大多数首选项都具有默认值,如果您未设置它们,则将使用它们。

在配置文件中设置电子邮件首选项

如果您不想使用上述方法来设置首选项,则可以将其放入配置文件中。只需打开 app / Config / Email.php文件,然后在“电子邮件”属性中设置您的配置。然后保存文件,它将自动使用。$email->initialize()如果您在配置文件中设置了首选项,则无需使用该方法。

电子邮件首选项

以下是发送电子邮件时可以设置的所有首选项的列表。

偏爱 默认值 选项 描述
userAgent CodeIgniter None “用户代理”。
protocol mail mail, sendmail, or smtp 邮件发送协议。
mailpath /usr/sbin/sendmail None Sendmail的服务器路径。
SMTPHost No Default None SMTP服务器地址。
SMTPUser No Default None SMTP用户名。
SMTPPass No Default None SMTP密码。
SMTPPort 25 None SMTP端口。
SMTPTimeout 5 None SMTP超时(以秒为单位)。
SMTPKeepAlive FALSE TRUE or FALSE (boolean) 启用持久的SMTP连接。
SMTPCrypto No Default tls or ssl SMTP加密
wordWrap TRUE TRUE or FALSE (boolean) 启用自动换行。
wrapChars 76 要包装的字符数。
mailType text text or html 邮件类型。如果您发送HTML电子邮件,则必须将其作为完整的网页发送。确保您没有任何相对链接或相对图像路径,否则它们将不起作用。
charset utf-8 字符集(utf-8,iso-8859-1等)。
validate TRUE TRUE or FALSE (boolean) 是否验证电子邮件地址。
priority 3 1, 2, 3, 4, 5 电子邮件优先级。1 =最高。5 =最低。3 =正常。
CRLF \n “\r\n” or “\n” or “\r” 换行符。(使用“ \ r \ n”符合RFC 822)。
newline \n “\r\n” or “\n” or “\r” 换行符。(使用“ \ r \ n”符合RFC 822)。).
BCCBatchMode FALSE TRUE or FALSE (boolean) 启用密件抄送批处理模式。
BCCBatchSize 200 None 每个密件抄送批次中的电子邮件数量。
DSN FALSE TRUE or FALSE (boolean) 启用来自服务器的通知消息

覆盖单词包装

如果您启用了自动换行(建议遵循RFC 822),并且电子邮件中的链接很长,则该链接也可能被自动换行,从而导致收信人无法点击它。使用CodeIgniter,您可以手动覆盖部分消息中的自动换行,如下所示:

The text of your email that
gets wrapped normally.


{unwrap}http://example.com/a_long_link_that_should_not_be_wrapped.html{/unwrap}


More text that will be
wrapped normally.

将您不想用文字包装的物品放在以下位置:{unwrap} {/unwrap}

类参考

CodeIgniter\Email\Email

setFrom$ from[, $name = ''[$ returnPath = null]])

参数: $from (string) – “From” e-mail address
$name (string) – “From” display name
$returnPath (string) – Optional email address to redirect undelivered e-mail to
返回: CodeIgniter\Email\Email instance (method chaining)
返回类型: CodeIgniter\Email\Email

设置电子邮件地址和发送电子邮件的人的姓名:

$email->setFrom('you@example.com', 'Your Name');

您还可以设置返回路径,以帮助重定向未送达的邮件:

$email->setFrom('you@example.com', 'Your Name', 'returned_emails@example.com');

注解

如果您已将“ smtp”配置为协议,则无法使用Return-Path。

setReplyTo($replyto[, $name = ''])

参数: $replyto (string) – E-mail address for replies
$name (string) – Display name for the reply-to e-mail address
返回: CodeIgniter\Email\Email instance (method chaining)
返回类型: CodeIgniter\Email\Email

设置回复地址。 如果未提供信息,则使用setFrom方法中的信息。 例:

$email->setReplyTo('you@example.com', 'Your Name');

setTo($to)

参数: $to (mixed) – Comma-delimited string or an array of e-mail addresses
返回: CodeIgniter\Email\Email instance (method chaining)
返回类型: CodeIgniter\Email\Email

设置收件人的电子邮件地址。 可以是一封电子邮件,逗号分隔的列表或数组:

$email->setTo('someone@example.com');
$email->setTo('one@example.com, two@example.com, three@example.com');
$email->setTo(['one@example.com', 'two@example.com', 'three@example.com']);

setCC($cc)

参数: $cc (mixed) – Comma-delimited string or an array of e-mail addresses
返回: CodeIgniter\Email\Email instance (method chaining)
返回类型: CodeIgniter\Email\Email

设置抄送电子邮件地址。 就像“收件人”一样,它可以是一封电子邮件,逗号分隔的列表或数组。

setBCC($bcc[, $limit = ''])

参数: $bcc (mixed) – Comma-delimited string or an array of e-mail addresses
$limit (int) – Maximum number of e-mails to send per batch
返回: CodeIgniter\Email\Email instance (method chaining)
返回类型: CodeIgniter\Email\Email

设置密件抄送电子邮件地址。 就像setTo()方法一样,它可以是一封电子邮件,一个逗号分隔的列表或一个数组。

如果设置了$limit,将启用“批处理模式”,它将以批次发送电子邮件,每个批次不超过指定的$limit

setSubject($subject)

参数: $subject (string) – E-mail subject line
返回: CodeIgniter\Email\Email instance (method chaining)
返回类型: CodeIgniter\Email\Email

设置电子邮件主题:

$email->setSubject('This is my subject');

setMessage($body)

参数: $body (string) – E-mail message body
返回: CodeIgniter\Email\Email instance (method chaining)
返回类型: CodeIgniter\Email\Email

设置电子邮件正文:

$email->setMessage('This is my message');

setAltMessage($str)

参数: $str (string) – Alternative e-mail message body
返回: CodeIgniter\Email\Email instance (method chaining)
返回类型: CodeIgniter\Email\Email

设置备用电子邮件正文:

$email->setAltMessage('This is the alternative message');

这是一个可选的消息字符串,如果您发送HTML格式的电子邮件,则可以使用该字符串。 它使您可以指定不带HTML格式的替代消息,该消息将添加到不接受HTML电子邮件的人的标题字符串中。 如果您未设置自己的消息,CodeIgniter将从HTML电子邮件中提取消息并剥离标签。

setHeader($header, $value)

参数: $header (string) – Header name
$value (string) – Header value
返回: CodeIgniter\Email\Email instance (method chaining)
返回类型: CodeIgniter\Email\Email

将其他标题附加到电子邮件:

$email->setHeader('Header1', 'Value1');
$email->setHeader('Header2', 'Value2');

clear($clearAttachments = false)

参数: $clearAttachments (bool) – Whether or not to clear attachments
返回: CodeIgniter\Email\Email instance (method chaining)
返回类型: CodeIgniter\Email\Email

将所有电子邮件变量初始化为空状态。 如果您循环运行电子邮件发送方法,则允许使用此方法,以便在两次循环之间重置数据。

foreach ($list as $name => $address)
{
        $email->clear();


        $email->setTo($address);
        $email->setFrom('your@example.com');
        $email->setSubject('Here is your info '.$name);
        $email->setMessage('Hi ' . $name . ' Here is the info you requested.');
        $email->send();
}

如果将参数设置为TRUE,则所有附件也会被清除:

$email->clear(true);

send($autoClear = true)

参数: $autoClear (bool) – Whether to clear message data automatically
返回: TRUE on success, FALSE on failure
返回类型: bool

电子邮件发送方法。 根据成功或失败返回布尔值TRUE或FALSE,使其可以有条件地使用:

if (! $email->send())
{
        // Generate error
}

如果请求成功,此方法将自动清除所有参数。 要停止此行为,请通过FALSE:

if ($email->send(false))
{
        // Parameters won't be cleared
}

注解

为了使用printDebugger()方法,您需要避免清除电子邮件参数。

如果启用了BCCBatchMode,并且接收者超过BCCBatchSize,则此方法将始终返回布尔值TRUE

attach($filename[, $disposition = ''[, $newname = null[, $mime = '']]])

参数: $filename (string) – File name
$disposition (string) – ‘disposition’ of the attachment. Most email clients make their own decision regardless of the MIME specification used here. https://www.iana.org/assignments/cont-disp/cont-disp.xhtml
$newname (string) – Custom file name to use in the e-mail
$mime (string) – MIME type to use (useful for buffered data)
返回: CodeIgniter\Email\Email instance (method chaining)
返回类型: CodeIgniter\Email\Email

使您可以发送附件。 将文件路径/名称放在第一个参数中。 对于多个附件,请多次使用该方法。 例如:

$email->attach('/path/to/photo1.jpg');
$email->attach('/path/to/photo2.jpg');
$email->attach('/path/to/photo3.jpg');

要使用默认处置方式(附件),请将第二个参数留空,否则请使用自定义处置方式:

$email->attach('image.jpg', 'inline');

您也可以使用以下网址:

$email->attach('http://example.com/filename.pdf');

如果您想使用自定义文件名,则可以使用第三个参数:

$email->attach('filename.pdf', 'attachment', 'report.pdf');

如果需要使用缓冲字符串而不是实际文件,则可以将第一个参数用作缓冲区,将第三个参数用作文件名,将第四个参数用作mime-type:

$email->attach($buffer, 'attachment', 'report.pdf', 'application/pdf');

setAttachmentCID($filename)

参数: $filename (string) – Existing attachment filename
返回: Attachment Content-ID or FALSE if not found
返回类型: string

设置并返回附件的Content-ID,使您可以将内嵌(图片)附件嵌入HTML。 第一个参数必须是已经附加的文件名。

$filename = '/img/photo1.jpg';
$email->attach($filename);
foreach ($list as $address)
{
        $email->setTo($address);
        $cid = $email->setAttachmentCID($filename);
        $email->setMessage('<img src="cid:'. $cid .'" alt="photo1" />');
        $email->send();
}

注解

必须重新创建每个电子邮件的Content-ID,以使其唯一。

printDebugger($include = ['headers', 'subject', 'body'])

参数: $include (array) – Which parts of the message to print out
返回: Formatted debug data
返回类型: string

返回一个包含任何服务器消息,电子邮件标题和电子邮件消息的字符串。 对调试有用。

您可以选择指定应打印消息的哪些部分。 有效选项包括:headers, subject, body

例如:

// You need to pass FALSE while sending in order for the email data
// to not be cleared - if that happens, printDebugger() would have
// nothing to output.
$email->send(false);


// Will only print the email headers, excluding the message subject and body
$email->printDebugger(['headers']);

注解

默认情况下,将打印所有原始数据。