Email (class)

Class Email

CakePHP Email class.

This class is used for sending Internet Message Format based on the standard outlined in http://www.rfc-editor.org/rfc/rfc2822.txt

Configuration

Configuration for Email is managed by Email::config() and Email::configTransport(). Email::config() can be used to add or read a configuration profile for Email instances. Once made configuration profiles can be used to re-use across various email messages your application sends.

Cake\Mailer\Email implements JsonSerializable, Serializable uses Cake\Core\StaticConfigTrait, Cake\View\ViewVarsTrait
Namespace: Cake\Mailer
Located at Mailer/Email.php

Method Detail

__clonesource public

__clone( )

Clone ViewBuilder instance when email object is cloned.

__constructsource public

__construct( array|string|null $config null )

Constructor

Parameters

array|string|null $config optional null
Array of configs, or string to load configs from email.php

_addEmailsource protected

_addEmail( string $varName , string|array $email , string $name )

Add email

Parameters

string $varName
Property name
string|array $email
String with email, Array with email as key, name as value or email as value (without name)
string $name
Name

Returns

mixed
$this

Throws

InvalidArgumentException
\InvalidArgumentException

_applyConfigsource protected

_applyConfig( string|array $config )

Apply the config to an instance

Parameters

string|array $config
Configuration options.

Throws

InvalidArgumentException
When using a configuration that doesn't exist.

_attachFilessource protected

_attachFiles( string|null $boundary null )

Attach non-embedded files by adding file contents inside boundaries.

Parameters

string|null $boundary optional null
Boundary to use. If null, will default to $this->_boundary

Returns

array
An array of lines to add to the message

_attachInlineFilessource protected

_attachInlineFiles( string|null $boundary null )

Attach inline/embedded files to the message.

Parameters

string|null $boundary optional null
Boundary to use. If null, will default to $this->_boundary

Returns

array
An array of lines to add to the message

_checkViewVarssource protected

_checkViewVars( mixed $item , string $key )

Iterates through hash to clean up and normalize.

Parameters

mixed $item
Reference to the view var value.
string $key
View var key.

_constructTransportsource protected

_constructTransport( string $name )

Build a transport instance from configuration data.

Parameters

string $name
The transport configuration name to build.

Returns

Cake\Mailer\AbstractTransport
\Cake\Mailer\AbstractTransport

Throws

InvalidArgumentException
When transport configuration is missing or invalid.

_createBoundarysource protected

_createBoundary( )

Create unique boundary identifier

_encodesource protected

_encode( string $text )

Encode the specified string using the current charset

Parameters

string $text
String to encode

Returns

string
Encoded string

_encodeStringsource protected

_encodeString( string $text , string $charset )

Translates a string for one charset to another if the App.encoding value differs and the mb_convert_encoding function exists

Parameters

string $text
The text to be converted
string $charset
the target encoding

Returns

string
string

_formatAddresssource protected

_formatAddress( array $address )

Format addresses

If the address contains non alphanumeric/whitespace characters, it will be quoted as characters like : and , are known to cause issues in address header fields.

Parameters

array $address
Addresses to format.

Returns

array
array

_getContentTransferEncodingsource protected

_getContentTransferEncoding( )

Return the Content-Transfer Encoding value based on the set charset

Returns

string
string

_getContentTypeCharsetsource protected

_getContentTypeCharset( )

Return charset value for Content-Type.

Checks fallback/compatibility types which include workarounds for legacy japanese character sets.

Returns

string
string

_getTypessource protected

_getTypes( )

Gets the text body types that are in this email message

Returns

array
Array of types. Valid types are 'text' and 'html'

_logDeliverysource protected

_logDelivery( array $contents )

Log the email message delivery.

Parameters

array $contents
The content with 'headers' and 'message' keys.

_readFilesource protected

_readFile( string $path )

Read the file contents and return a base64 version of the file contents.

Parameters

string $path
The absolute path to the file to read.

Returns

string
File contents in base64 encoding

_rendersource protected

_render( array $content )

Render the body of the email.

Parameters

array $content
Content to render

Returns

array
Email body ready to be sent

_renderTemplatessource protected

_renderTemplates( string $content )

Build and set all the view properties needed to render the templated emails. If there is no template set, the $content will be returned in a hash of the text content types for the email.

Parameters

string $content
The content passed in from send() in most cases.

Returns

array
The rendered content with html and text keys.

_setEmailsource protected

_setEmail( string $varName , string|array $email , string $name )

Set email

Parameters

string $varName
Property name
string|array $email
String with email, Array with email as key, name as value or email as value (without name)
string $name
Name

Returns

mixed
$this

Throws

InvalidArgumentException
\InvalidArgumentException

_setEmailSinglesource protected

_setEmailSingle( string $varName , string|array $email , string $name , string $throwMessage )

Set only 1 email

Parameters

string $varName
Property name
string|array $email
String with email, Array with email as key, name as value or email as value (without name)
string $name
Name
string $throwMessage
Exception message

Returns

mixed
$this

Throws

InvalidArgumentException
\InvalidArgumentException

_validateEmailsource protected

_validateEmail( string $email )

Validate email address

Parameters

string $email
Email address to validate

Throws

InvalidArgumentException
If email address does not validate

_wrapsource protected

_wrap( string $message , integer $wrapLength Cake\Mailer\Email::LINE_LENGTH_MUST )

Wrap the message to follow the RFC 2822 - 2.1.1

Parameters

string $message
Message to wrap
integer $wrapLength optional Cake\Mailer\Email::LINE_LENGTH_MUST
The line length

Returns

array
Wrapped message

addAttachmentssource public

addAttachments( string|array $attachments )

Add attachments

Parameters

string|array $attachments
String with the filename or array with filenames

Returns

mixed
$this

Throws

InvalidArgumentException
\InvalidArgumentException

See

Cake\Mailer\Email::attachments()

addBccsource public

addBcc( string|array $email , string|null $name null )

Add Bcc

Parameters

string|array $email
Null to get, String with email, Array with email as key, name as value or email as value (without name)
string|null $name optional null
Name

Returns

mixed
$this

addCcsource public

addCc( string|array $email , string|null $name null )

Add Cc

Parameters

string|array $email
Null to get, String with email, Array with email as key, name as value or email as value (without name)
string|null $name optional null
Name

Returns

mixed
$this

addHeaderssource public

addHeaders( array $headers )

Add header for the message

Parameters

array $headers
Headers to set.

Returns

mixed
$this

addTosource public

addTo( string|array $email , string|null $name null )

Add To

Parameters

string|array $email
Null to get, String with email, Array with email as key, name as value or email as value (without name)
string|null $name optional null
Name

Returns

mixed
$this

attachmentssource public

attachments( string|array|null $attachments null )

Add attachments to the email message

Attachments can be defined in a few forms depending on how much control you need:

Attach a single file:

$email->attachments('path/to/file');

Attach a file with a different filename:

$email->attachments(['custom_name.txt' => 'path/to/file.txt']);

Attach a file and specify additional properties:

$email->attachments(['custom_name.png' => [
     'file' => 'path/to/file',
     'mimetype' => 'image/png',
     'contentId' => 'abc123',
     'contentDisposition' => false
   ]
]);

Attach a file from string and specify additional properties:

$email->attachments(['custom_name.png' => [
     'data' => file_get_contents('path/to/file'),
     'mimetype' => 'image/png'
   ]
]);

The contentId key allows you to specify an inline attachment. In your email text, you can use <img src="cid:abc123" /> to display the image inline.

The contentDisposition key allows you to disable the Content-Disposition header, this can improve attachment compatibility with outlook email clients.

Parameters

string|array|null $attachments optional null
String with the filename or array with filenames

Returns

array|$this
$this Either the array of attachments when getting or $this when setting.

Throws

InvalidArgumentException
\InvalidArgumentException

bccsource public

bcc( string|array|null $email null , string|null $name null )

Bcc

Parameters

string|array|null $email optional null
Null to get, String with email, Array with email as key, name as value or email as value (without name)
string|null $name optional null
Name

Returns

array|$this
$this

ccsource public

cc( string|array|null $email null , string|null $name null )

Cc

Parameters

string|array|null $email optional null
Null to get, String with email, Array with email as key, name as value or email as value (without name)
string|null $name optional null
Name

Returns

array|$this
$this

charsetsource public

charset( string|null $charset null )

Charset setter/getter

Parameters

string|null $charset optional null
Character set.

Returns

string
this->charset

configTransportsource public static

configTransport( string|array $key , array|Cake\Mailer\AbstractTransport|null $config null )

Add or read transport configuration.

Use this method to define transports to use in delivery profiles. Once defined you cannot edit the configurations, and must use Email::dropTransport() to flush the configuration first.

When using an array of configuration data a new transport will be constructed for each message sent. When using a Closure, the closure will be evaluated for each message.

The className is used to define the class to use for a transport. It can either be a short name, or a fully qualified classname

Parameters

string|array $key
The configuration name to read/write. Or an array of multiple transports to set.
array|Cake\Mailer\AbstractTransport|null $config optional null
Either an array of configuration data, or a transport instance.

Returns

array|null
Either null when setting or an array of data when reading.

Throws

BadMethodCallException
When modifying an existing configuration.

configuredTransportsource public static

configuredTransport( )

Returns an array containing the named transport configurations

Returns

array
Array of configurations.

createFromArraysource public

createFromArray( array $config )

Configures an email instance object from serialized config.

Parameters

array $config
Email configuration array.

Returns

Cake\Mailer\Email
Configured email instance.

deliversource public static

deliver( string|array $to null , string $subject null , string|array $message null , string|array $transportConfig 'fast' , boolean $send true )

Static method to fast create an instance of \Cake\Mailer\Email

Parameters

string|array $to optional null
Address to send (see Cake\Mailer\Email::to()). If null, will try to use 'to' from transport config
string $subject optional null
String of subject or null to use 'subject' from transport config
string|array $message optional null
String with message or array with variables to be used in render
string|array $transportConfig optional 'fast'
String to use config from EmailConfig or array with configs
boolean $send optional true
Send the email or just return the instance pre-configured

Returns

Cake\Mailer\Email
Instance of Cake\Mailer\Email

Throws

InvalidArgumentException
\InvalidArgumentException

domainsource public

domain( string|null $domain null )

Domain as top level (the part after @)

Parameters

string|null $domain optional null
Manually set the domain for CLI mailing

Returns

string|$this
$this

dropTransportsource public static

dropTransport( string $key )

Delete transport configuration.

Parameters

string $key
The transport name to remove.

emailFormatsource public

emailFormat( string|null $format null )

Email format

Parameters

string|null $format optional null
Formatting string.

Returns

string|$this
$this

Throws

InvalidArgumentException
\InvalidArgumentException

emailPatternsource public

emailPattern( string|boolean|null $regex false )

EmailPattern setter/getter

Parameters

string|boolean|null $regex optional false
The pattern to use for email address validation, null to unset the pattern and make use of filter_var() instead, false or nothing to return the current value

Returns

string|$this
$this

fromsource public

from( string|array|null $email null , string|null $name null )

From

Parameters

string|array|null $email optional null
Null to get, String with email, Array with email as key, name as value or email as value (without name)
string|null $name optional null
Name

Returns

array|$this
$this

Throws

InvalidArgumentException
\InvalidArgumentException

getHeaderssource public

getHeaders( array $include [] )

Get list of headers

Includes:

  • from
  • replyTo
  • readReceipt
  • returnPath
  • to
  • cc
  • bcc
  • subject

Parameters

array $include optional []
List of headers.

Returns

array
array

headerCharsetsource public

headerCharset( string|null $charset null )

HeaderCharset setter/getter

Parameters

string|null $charset optional null
Character set.

Returns

string
this->charset

helperssource public

helpers( array|null $helpers null )

Helpers to be used in render

Parameters

array|null $helpers optional null
Helpers list.

Returns

array|$this
$this

jsonSerializesource public

jsonSerialize( )

Serializes the email object to a value that can be natively serialized and re-used to clone this email instance.

It has certain limitations for viewVars that are good to know:
- ORM\Query executed and stored as resultset - SimpleXmlElements stored as associative array - Exceptions stored as strings - Resources, \Closure and \PDO are not supported.

Returns

array
Serializable array of configuration properties.

Throws

Exception
When a view var object can not be properly serialized.

Implementation of

JsonSerializable::jsonSerialize()

messagesource public

message( string|null $type null )

Get generated message (used by transport classes)

Parameters

string|null $type optional null
Use MESSAGE_* constants or null to return the full message as array

Returns

string|array
String if have type, array if type is null

messageIdsource public

messageId( boolean|string|null $message null )

Message-ID

Parameters

boolean|string|null $message optional null
True to generate a new Message-ID, False to ignore (not send in email), String to set as Message-ID

Returns

boolean|string|$this
$this

Throws

InvalidArgumentException
\InvalidArgumentException

profilesource public

profile( null|string|array $config null )

Get/Set the configuration profile to use for this instance.

Parameters

null|string|array $config optional null
String with configuration name, or an array with config or null to return current config.

Returns

string|array|$this
$this

readReceiptsource public

readReceipt( string|array|null $email null , string|null $name null )

Read Receipt (Disposition-Notification-To header)

Parameters

string|array|null $email optional null
Null to get, String with email, Array with email as key, name as value or email as value (without name)
string|null $name optional null
Name

Returns

array|$this
$this

Throws

InvalidArgumentException
\InvalidArgumentException

replyTosource public

replyTo( string|array|null $email null , string|null $name null )

Reply-To

Parameters

string|array|null $email optional null
Null to get, String with email, Array with email as key, name as value or email as value (without name)
string|null $name optional null
Name

Returns

array|$this
$this

Throws

InvalidArgumentException
\InvalidArgumentException

resetsource public

reset( )

Reset all the internal variables to be able to send out a new email.

Returns

mixed
$this

returnPathsource public

returnPath( string|array|null $email null , string|null $name null )

Return Path

Parameters

string|array|null $email optional null
Null to get, String with email, Array with email as key, name as value or email as value (without name)
string|null $name optional null
Name

Returns

array|$this
$this

Throws

InvalidArgumentException
\InvalidArgumentException

sendsource public

send( string|array|null $content null )

Send an email using the specified content, template and layout

Parameters

string|array|null $content optional null
String with message or array with messages

Returns

array
array

Throws

BadMethodCallException
\BadMethodCallException

sendersource public

sender( string|array|null $email null , string|null $name null )

Sender

Parameters

string|array|null $email optional null
Null to get, String with email, Array with email as key, name as value or email as value (without name)
string|null $name optional null
Name

Returns

array|$this
$this

Throws

InvalidArgumentException
\InvalidArgumentException

serializesource public

serialize( )

Serializes the Email object.

Returns

string
string

Implementation of

Serializable::serialize()

setHeaderssource public

setHeaders( array $headers )

Sets headers for the message

Parameters

array $headers
Associative array containing headers to be set.

Returns

mixed
$this

subjectsource public

subject( string|null $subject null )

Get/Set Subject.

Parameters

string|null $subject optional null
Subject string.

Returns

string|$this
$this

templatesource public

template( boolean|string $template false , boolean|string $layout false )

Template and layout

Parameters

boolean|string $template optional false
Template name or null to not use
boolean|string $layout optional false
Layout name or null to not use

Returns

array|$this
$this

themesource public

theme( string|null $theme null )

Theme to use when rendering

Parameters

string|null $theme optional null
Theme name.

Returns

string|$this
$this

tosource public

to( string|array|null $email null , string|null $name null )

To

Parameters

string|array|null $email optional null
Null to get, String with email, Array with email as key, name as value or email as value (without name)
string|null $name optional null
Name

Returns

array|$this
$this

transportsource public

transport( string|Cake\Mailer\AbstractTransport|null $name null )

Get/set the transport.

When setting the transport you can either use the name of a configured transport or supply a constructed transport.

Parameters

string|Cake\Mailer\AbstractTransport|null $name optional null
Either the name of a configured transport, or a transport instance.

Returns

Cake\Mailer\AbstractTransport|$this
$this

Throws

LogicException
When the chosen transport lacks a send method.
InvalidArgumentException
When $name is neither a string nor an object.

unserializesource public

unserialize( string $data )

Unserializes the Email object.

Parameters

string $data
Serialized string.

Returns

Cake\Mailer\Email
Configured email instance.

Implementation of

Serializable::unserialize()

viewRendersource public

viewRender( string|null $viewClass null )

View class for render

Parameters

string|null $viewClass optional null
View class name.

Returns

string|$this
$this

viewVarssource public

viewVars( array|null $viewVars null )

Variables to be set on render

Parameters

array|null $viewVars optional null
Variables to set for view.

Returns

array|$this
$this

Methods used from Cake\Core\StaticConfigTrait

configsource public static

config( string|array $key , array $config null )

This method can be used to define configuration adapters for an application or read existing configuration.

To change an adapter's configuration at runtime, first drop the adapter and then reconfigure it.

Adapters will not be constructed until the first operation is done.

Usage

Assuming that the class' name is Cache the following scenarios are supported:

Reading config data back:

Cache::config('default');

Setting a cache engine up.

Cache::config('default', $settings);

Injecting a constructed adapter in:

Cache::config('default', $instance);

Configure multiple adapters at once:

Cache::config($arrayOfConfig);

Parameters

string|array $key
The name of the configuration, or an array of multiple configs.
array $config optional null
An array of name => configuration data for adapter.

Returns

array|null
Null when adding configuration or an array of configuration data when reading.

Throws

BadMethodCallException
When trying to modify an existing config.

configuredsource public static

configured( )

Returns an array containing the named configurations

Returns

array
Array of configurations.

dropsource public static

drop( string $config )

Drops a constructed adapter.

If you wish to modify an existing configuration, you should drop it, change configuration and then re-add it.

If the implementing objects supports a $_registry object the named configuration will also be unloaded from the registry.

Parameters

string $config
An existing configuration you wish to remove.

Returns

boolean
Success of the removal, returns false when the config does not exist.

dsnClassMapsource public static

dsnClassMap( array $map null )

Returns or updates the DSN class map for this class

Parameters

array $map optional null
Additions/edits to the class map to apply

Returns

array
array

parseDsnsource public static

parseDsn( string $dsn )

Parses a DSN into a valid connection configuration

This method allows setting a DSN using formatting similar to that used by PEAR::DB. The following is an example of its usage:

$dsn = 'mysql://user:pass@localhost/database?';
$config = ConnectionManager::parseDsn($dsn);

$dsn = 'Cake\Log\Engine\FileLog://?types=notice,info,debug&file=debug&path=LOGS';
$config = Log::parseDsn($dsn);

$dsn = 'smtp://user:secret@localhost:25?timeout=30&client=null&tls=null';
$config = Email::parseDsn($dsn);

$dsn = 'file:///?className=\My\Cache\Engine\FileEngine';
$config = Cache::parseDsn($dsn);

$dsn = 'File://?prefix=myapp_cake_core_&serialize=true&duration=+2 minutes&path=/tmp/persistent/';
$config = Cache::parseDsn($dsn);

For all classes, the value of scheme is set as the value of both the className unless they have been otherwise specified.

Note that querystring arguments are also parsed and set as values in the returned configuration.

Parameters

string $dsn
The DSN string to convert to a configuration array

Returns

array
The configuration array to be stored after parsing the DSN

Throws

InvalidArgumentException
If not passed a string

Methods used from Cake\View\ViewVarsTrait

createViewsource public

createView( string|null $viewClass null )

Constructs the view class instance based on the current configuration.

Parameters

string|null $viewClass optional null
Optional namespaced class name of the View class to instantiate.

Returns

Cake\View\View
\Cake\View\View

Throws

Cake\View\Exception\MissingViewException
If view class was not found.

setsource public

set( string|array $name , string|array|null|boolean $value null )

Saves a variable or an associative array of variables for use inside a template.

Parameters

string|array $name
A string or an array of data.
string|array|null|boolean $value optional null
Value in case $name is a string (which then works as the key). Unused if $name is an associative array, otherwise serves as the values to $name's keys.

Returns

mixed
$this

viewBuildersource public

viewBuilder( )

Get the view builder being used.

Returns

Cake\View\ViewBuilder
\Cake\View\ViewBuilder

viewOptionssource public

viewOptions( string|array|null $options null , boolean $merge true )

Get/Set valid view options in the object's _validViewOptions property. The property is created as an empty array if it is not set. If called without any parameters it will return the current list of valid view options. See createView().

Parameters

string|array|null $options optional null
string or array of string to be appended to _validViewOptions.
boolean $merge optional true
Whether to merge with or override existing valid View options. Defaults to true.

Returns

array
The updated view options as an array.

Constants summary

string EMAIL_PATTERN

Holds the regex pattern for email validation

'/^((?:[\p{L}0-9.!#$%&\'*+\/=?^_`{|}~-]+)*@[\p{L}0-9-.]+)$/ui'
integer LINE_LENGTH_MUST

Line length - no must more - RFC 2822 - 2.1.1

998
integer LINE_LENGTH_SHOULD

Line length - no should more - RFC 2822 - 2.1.1

78
string MESSAGE_HTML

Type of message - HTML

'html'
string MESSAGE_TEXT

Type of message - TEXT

'text'

Properties summary

$_appCharsetsource

protected string

The application wide charset, used to encode headers and body

null

$_attachmentssource

protected array

List of files that should be attached to the email.

Only absolute paths

[]

$_bccsource

protected array

Blind Carbon Copy

List of email's that should receive a copy of the email. The Recipient WILL NOT be able to see this list

[]

$_boundarysource

protected string

If set, boundary to use for multipart mime messages

null

$_ccsource

protected array

Carbon Copy

List of email's that should receive a copy of the email. The Recipient WILL be able to see this list

[]

$_charset8bitsource

protected array

8Bit character sets

['UTF-8', 'SHIFT_JIS']

$_configClasssource

protected string

The class name used for email configuration.

'EmailConfig'

$_contentTypeCharsetsource

protected array

Define Content-Type charset name

[
    'ISO-2022-JP-MS' => 'ISO-2022-JP'
]

$_domainsource

protected string

Domain for messageId generation. Needs to be manually set for CLI mailing as env('HTTP_HOST') is empty

null

$_dsnClassMapsource

protected static array

An array mapping url schemes to fully qualified Transport class names

[
    'debug' => 'Cake\Mailer\Transport\DebugTransport',
    'mail' => 'Cake\Mailer\Transport\MailTransport',
    'smtp' => 'Cake\Mailer\Transport\SmtpTransport',
]

$_emailFormatsource

protected string

What format should the email be sent in

'text'

$_emailFormatAvailablesource

protected array

Available formats to be sent.

['text', 'html', 'both']

$_emailPatternsource

protected string

Regex for email validation

If null, filter_var() will be used. Use the emailPattern() method to set a custom pattern.'

$_fromsource

protected array

The mail which the email is sent from

[]

$_headerssource

protected array

Associative array of a user defined headers Keys will be prefixed 'X-' as per RFC2822 Section 4.7.5

[]

$_htmlMessagesource

protected string

Html message

''

$_messagesource

protected array

Final message to send

[]

$_messageIdsource

protected boolean|string

Message ID

true

$_profilesource

protected array

A copy of the configuration profile for this instance. This copy can be modified with Email::profile().

[]

$_readReceiptsource

protected array

The read receipt email

[]

$_replyTosource

protected array

The email the recipient will reply to

[]

$_returnPathsource

protected array

The mail that will be used in case of any errors like

  • Remote mailserver down
  • Remote user has exceeded his quota
  • Unknown user
[]

$_sendersource

protected array

The sender email

[]

$_subjectsource

protected string

The subject of the email

''

$_textMessagesource

protected string

Text message

''

$_tosource

protected array

Recipient of the email

[]

$_transportsource

protected Cake\Mailer\AbstractTransport

The transport instance to use for sending mail.

null

$_transportConfigsource

protected static array

Configuration profiles for transports.

[]

$charsetsource

public string

Charset the email body is sent in

'utf-8'

$headerCharsetsource

public string

Charset the email header is sent in If null, the $charset property will be used as default

null

Properties used from Cake\Core\StaticConfigTrait

$_configsource

protected static array

Configuration sets.

[]

Properties used from Cake\View\ViewVarsTrait

$_viewBuildersource

protected Cake\View\ViewBuilder

The view builder instance being used.

$viewClasssource

public string

The name of default View class.

Deprecated

3.1.0 Use $this->viewBuilder()->className() instead.
null

$viewVarssource

public array

Variables for the view

[]

© 2005–2016 The Cake Software Foundation, Inc.
Licensed under the MIT License.
CakePHP is a registered trademark of Cake Software Foundation, Inc.
We are not endorsed by or affiliated with CakePHP.
http://api.cakephp.org/3.1/class-Cake.Mailer.Email.html

在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号

意见反馈
返回顶部