Class Message
Email message class.
This class is used for sending Internet Message Format based on the standard outlined in https://www.rfc-editor.org/rfc/rfc2822.txt
Constants
-
stringEMAIL_PATTERN ¶'/^((?:[\p{L}0-9.!#$%&\'*+\/=?^_`{|}~-]+)*@[\p{L}0-9-._]+)$/ui'Holds the regex pattern for email validation
-
intLINE_LENGTH_MUST ¶998Line length - must not exceed - RFC 2822 - 2.1.1
-
intLINE_LENGTH_SHOULD ¶78Line length - should not exceed - RFC 2822 - 2.1.1
-
stringMESSAGE_BOTH ¶'both'Type of message - BOTH
-
stringMESSAGE_HTML ¶'html'Type of message - HTML
-
stringMESSAGE_TEXT ¶'text'Type of message - TEXT
Property Summary
-
$appCharset protected
string|nullThe application wide charset, used to encode headers and body
-
$attachments protected
array<string, array>List of files that should be attached to the email.
Only absolute paths
-
$bcc protected
arrayBlind Carbon Copy
List of email's that should receive a copy of the email. The Recipient WILL NOT be able to see this list
-
$boundary protected
string|nullIf set, boundary to use for multipart mime messages
-
$cc protected
arrayCarbon Copy
List of email's that should receive a copy of the email. The Recipient WILL be able to see this list
-
$charset protected
stringCharset the email body is sent in
-
$charset8bit protected
array<string>8Bit character sets
-
$contentTypeCharset protected
array<string, string>Define Content-Type charset name
-
$domain protected
stringDomain for messageId generation. Needs to be manually set for CLI mailing as env('HTTP_HOST') is empty
-
$emailFormat protected
stringWhat format should the email be sent in
-
$emailFormatAvailable protected
array<string>Available formats to be sent.
-
$emailPattern protected
string|nullRegex for email validation
If null, filter_var() will be used. Use the emailPattern() method to set a custom pattern.
-
$from protected
arrayThe mail which the email is sent from
-
$headerCharset protected
string|nullCharset the email header is sent in If null, the $charset property will be used as default
-
$headers protected
arrayAssociative array of a user defined headers Keys will be prefixed 'X-' as per RFC2822 Section 4.7.5
-
$htmlMessage protected
stringHtml message
-
$message protected
arrayFinal message to send
-
$messageId protected
string|boolMessage ID
-
$priority protected
int|nullContains the optional priority of the email.
-
$readReceipt protected
arrayThe read receipt email
-
$replyTo protected
arrayList of email(s) that the recipient will reply to
-
$returnPath protected
arrayThe mail that will be used in case of any errors like
- Remote mailserver down
- Remote user has exceeded his quota
- Unknown user
-
$sender protected
arrayThe sender email
-
$serializableProperties protected
array<string>Properties that could be serialized
-
$subject protected
stringThe subject of the email
-
$textMessage protected
stringText message
-
$to protected
arrayRecipient of the email
-
$transferEncoding protected
string|nullThe email transfer encoding used. If null, the $charset property is used for determined the transfer encoding.
-
$transferEncodingAvailable protected
array<string>Available encoding to be set for transfer.
Method Summary
-
__construct() public
Constructor
-
__serialize() public
Magic method used for serializing the Message object.
-
__unserialize() public
Magic method used to rebuild the Message object.
-
addAttachment() public
Add attachment.
-
addAttachments() public
Add attachments
-
addBcc() public
Add "bcc" address.
-
addCc() public
Add "cc" address.
-
addEmail() protected
Add email
-
addHeaders() public
Add header for the message
-
addReplyTo() public
Add "Reply-To" address.
-
addTo() public
Add "To" address.
-
attachFiles() protected
Attach non-embedded files by adding file contents inside boundaries.
-
attachInlineFiles() protected
Attach inline/embedded files to the message.
-
createBoundary() protected
Create unique boundary identifier
-
createFromArray() public
Configures an email instance object from serialized config.
-
decodeForHeader() protected
Decode the specified string
-
encodeBodyContent() protected
Applies the message's transfer encoding to a body part.
base64andquoted-printabledescribe a transformation of the content. Without applying it the header announces an encoding that was never performed, and a conforming reader decodes the body into garbage.7bit,8bitandbinarymean "no transformation" and pass through.The content is normalised to CRLF before encoding because that is how it reaches the wire: getBody() splits on "\n" and the renderer joins the lines with "\r\n" again. Encoding the same bytes keeps the delivered body identical to an 8bit delivery — only its representation changes. The return value is "\n"-separated for exactly that reason.
-
encodeForHeader() protected
Encode the specified string using the current charset
-
encodeString() protected
Translates a string for one charset to another if the App.encoding value differs and the mb_convert_encoding function exists
-
formatAddress() public
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. -
generateMessage() protected
Generate full message.
-
getAttachments() public
Gets attachments to the email message.
-
getBcc() public
Gets "bcc" address.
-
getBody() public
Get generated message body as array.
-
getBodyHtml() public
Get HTML body of message.
-
getBodyString() public
Get generated body as string.
-
getBodyText() public
Get text body of message.
-
getBodyTypes() public
Gets the body types that are in this email message
-
getCc() public
Gets "cc" address.
-
getCharset() public
Charset getter.
-
getContentTransferEncoding() public
Return the Content-Transfer Encoding value based on the set transferEncoding or set charset.
-
getContentTypeCharset() public
Return charset value for Content-Type.
Checks fallback/compatibility types which include workarounds for legacy japanese character sets.
-
getDomain() public
Gets domain.
-
getEmailFormat() public
Gets email format.
-
getEmailPattern() public
EmailPattern setter/getter
-
getFrom() public
Gets "from" address.
-
getHeaderCharset() public
HeaderCharset getter.
-
getHeaders() public
Get list of headers
Includes:
fromreplyToreadReceiptreturnPathtoccbccsubject
-
getHeadersString() public
Get headers as string.
-
getMessageId() public
Gets message ID.
-
getOriginalSubject() public
Get original subject without encoding
-
getPriority() public
Gets priority.
-
getReadReceipt() public
Gets Read Receipt (Disposition-Notification-To header).
-
getReplyTo() public
Gets "Reply-To" address.
-
getReturnPath() public
Gets return path.
-
getSender() public
Gets the "sender" address. See RFC link below for full explanation.
-
getSubject() public
Gets subject.
-
getTo() public
Gets "to" address
-
getTransferEncoding() public
TransferEncoding getter.
-
jsonSerialize() public
Serializes the email object to a value that can be natively serialized and re-used to clone this email instance.
-
readFile() protected
Read the file contents and return a base64 version of the file contents.
-
reset() public
Reset all the internal variables to be able to send out a new email.
-
setAttachments() public
Add attachments to the email message
Attachments can be defined in a few forms depending on how much control you need:
Attach a file:
$this->setAttachments(['custom_name.txt' => 'path/to/file.txt']);Attach a file and specify additional properties:
$this->setAttachments(['custom_name.png' => [ 'file' => 'path/to/file', 'mimetype' => 'image/png', 'contentId' => 'abc123', 'contentDisposition' => false ] ]);Attach a file from string and specify additional properties:
$this->setAttachments(['custom_name.png' => [ 'data' => file_get_contents('path/to/file'), 'mimetype' => 'image/png' ] ]);The
contentIdkey allows you to specify an inline attachment. In your email text, you can use<img src="cid:abc123">to display the image inline.The
contentDispositionkey allows you to disable theContent-Dispositionheader, this can improve attachment compatibility with outlook email clients. -
setBcc() public
Sets "bcc" address.
-
setBody() public
Set message body.
-
setBodyHtml() public
Set HTML body for message.
-
setBodyText() public
Set text body for message.
-
setCc() public
Sets "cc" address.
-
setCharset() public
Charset setter.
-
setConfig() public
Sets the configuration for this instance.
-
setDomain() public
Sets domain.
Domain as top level (the part after @).
-
setEmail() protected
Set email
-
setEmailFormat() public
Sets email format.
-
setEmailPattern() public
EmailPattern setter/getter
-
setEmailSingle() protected
Set only 1 email
-
setFrom() public
Sets "from" address.
-
setHeaderCharset() public
HeaderCharset setter.
-
setHeaders() public
Sets headers for the message
-
setMessageId() public
Sets message ID.
-
setPriority() public
Sets priority.
-
setReadReceipt() public
Sets Read Receipt (Disposition-Notification-To header).
-
setReplyTo() public
Sets "Reply-To" address.
-
setReturnPath() public
Sets return path.
-
setSender() public
Sets the "sender" address. See RFC link below for full explanation.
-
setSubject() public
Sets subject.
-
setTo() public
Sets "to" address.
-
setTransferEncoding() public
TransferEncoding setter.
-
validateEmail() protected
Validate email address
-
wrap() protected
Wrap the message to follow the RFC 2822 - 2.1.1
Method Detail
__construct() ¶ public
__construct(array<string, mixed>|null $config = null)
Constructor
Parameters
-
array<string, mixed>|null$config optional Array of configs, or string to load configs from app.php
__serialize() ¶ public
__serialize(): array
Magic method used for serializing the Message object.
Returns
array__unserialize() ¶ public
__unserialize(array $data): void
Magic method used to rebuild the Message object.
Parameters
-
array$data Data array.
Returns
voidaddAttachment() ¶ public
addAttachment(Psr\Http\Message\UploadedFileInterface|string $path, string|null $name = null, string|null $mimetype = null, string|null $contentId = null, bool|null $contentDisposition = null): $this
Add attachment.
Parameters
-
Psr\Http\Message\UploadedFileInterface|string$path Path to the file or UploadedFileInterface instance.
-
string|null$name optional Overrides the attachment name.
-
string|null$mimetype optional Mimetype of the file.
-
string|null$contentId optional Content ID for inline attachments.
-
bool|null$contentDisposition optional Allows you to disable the
Content-Dispositionheader
Returns
$thisaddAttachments() ¶ public
addAttachments(array $attachments): $this
Add attachments
Parameters
-
array$attachments Array of filenames.
Returns
$thisThrows
InvalidArgumentExceptionSee Also
addBcc() ¶ public
addBcc(array|string $email, string|null $name = null): $this
Add "bcc" address.
Parameters
-
array|string$email String with email, Array with email as key, name as value or email as value (without name)
-
string|null$name optional Name
Returns
$thisaddCc() ¶ public
addCc(array|string $email, string|null $name = null): $this
Add "cc" address.
Parameters
-
array|string$email String with email, Array with email as key, name as value or email as value (without name)
-
string|null$name optional Name
Returns
$thisaddEmail() ¶ protected
addEmail(string $varName, array|string $email, string|null $name): $this
Add email
Parameters
-
string$varName Property name
-
array|string$email String with email, Array with email as key, name as value or email as value (without name)
-
string|null$name Name
Returns
$thisThrows
InvalidArgumentExceptionaddHeaders() ¶ public
addHeaders(array $headers): $this
Add header for the message
Parameters
-
array$headers Headers to set.
Returns
$thisaddReplyTo() ¶ public
addReplyTo(array|string $email, string|null $name = null): $this
Add "Reply-To" address.
Parameters
-
array|string$email String with email, Array with email as key, name as value or email as value (without name)
-
string|null$name optional Name
Returns
$thisaddTo() ¶ public
addTo(array|string $email, string|null $name = null): $this
Add "To" address.
Parameters
-
array|string$email String with email, Array with email as key, name as value or email as value (without name)
-
string|null$name optional Name
Returns
$thisattachFiles() ¶ protected
attachFiles(string|null $boundary = null): array<string>
Attach non-embedded files by adding file contents inside boundaries.
Parameters
-
string|null$boundary optional Boundary to use. If null, will default to $this->boundary
Returns
array<string>An array of lines to add to the message
attachInlineFiles() ¶ protected
attachInlineFiles(string|null $boundary = null): array<string>
Attach inline/embedded files to the message.
Parameters
-
string|null$boundary optional Boundary to use. If null, will default to $this->boundary
Returns
array<string>An array of lines to add to the message
createFromArray() ¶ public
createFromArray(array<string, mixed> $config): $this
Configures an email instance object from serialized config.
Parameters
-
array<string, mixed>$config Email configuration array.
Returns
$thisdecodeForHeader() ¶ protected
decodeForHeader(string $text): string
Decode the specified string
Parameters
-
string$text String to decode
Returns
stringDecoded string
encodeBodyContent() ¶ protected
encodeBodyContent(string $content): string
Applies the message's transfer encoding to a body part.
base64 and quoted-printable describe a transformation of the
content. Without applying it the header announces an encoding that was
never performed, and a conforming reader decodes the body into garbage.
7bit, 8bit and binary mean "no transformation" and pass through.
The content is normalised to CRLF before encoding because that is how it reaches the wire: getBody() splits on "\n" and the renderer joins the lines with "\r\n" again. Encoding the same bytes keeps the delivered body identical to an 8bit delivery — only its representation changes. The return value is "\n"-separated for exactly that reason.
Parameters
-
string$content Body part to encode.
Returns
stringEncoded content, lines separated by "\n".
encodeForHeader() ¶ protected
encodeForHeader(string $text): string
Encode the specified string using the current charset
Parameters
-
string$text String to encode
Returns
stringEncoded string
encodeString() ¶ protected
encodeString(string $text, string $charset): string
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
stringformatAddress() ¶ public
formatAddress(array $address): array<string>
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<string>generateMessage() ¶ protected
generateMessage(): array<string>
Generate full message.
Returns
array<string>getAttachments() ¶ public
getAttachments(): array<string, array>
Gets attachments to the email message.
Returns
array<string, array>Array of attachments.
getBodyString() ¶ public
getBodyString(string $eol = "\r\n"): string
Get generated body as string.
Parameters
-
string$eol optional End of line string for imploding.
Returns
stringSee Also
getBodyTypes() ¶ public
getBodyTypes(): array
Gets the body types that are in this email message
Returns
arrayArray of types. Valid types are Email::MESSAGE_TEXT and Email::MESSAGE_HTML
getContentTransferEncoding() ¶ public
getContentTransferEncoding(): string
Return the Content-Transfer Encoding value based on the set transferEncoding or set charset.
Returns
stringgetContentTypeCharset() ¶ public
getContentTypeCharset(): string
Return charset value for Content-Type.
Checks fallback/compatibility types which include workarounds for legacy japanese character sets.
Returns
stringgetEmailPattern() ¶ public
getEmailPattern(): string|null
EmailPattern setter/getter
Returns
string|nullgetHeaders() ¶ public
getHeaders(array<int|string, string> $include = []): array<string, string>
Get list of headers
Includes:
fromreplyToreadReceiptreturnPathtoccbccsubject
Parameters
-
array<int|string, string>$include optional List of headers.
Returns
array<string, string>getHeadersString() ¶ public
getHeadersString(array<string> $include = [], string $eol = "\r\n", Closure|null $callback = null): string
Get headers as string.
Parameters
-
array<string>$include optional List of headers.
-
string$eol optional End of line string for concatenating headers.
-
Closure|null$callback optional Callback to run each header value through before stringifying.
Returns
stringSee Also
getOriginalSubject() ¶ public
getOriginalSubject(): string
Get original subject without encoding
Returns
stringOriginal subject
getReadReceipt() ¶ public
getReadReceipt(): array
Gets Read Receipt (Disposition-Notification-To header).
Returns
arraygetSender() ¶ public
getSender(): array
Gets the "sender" address. See RFC link below for full explanation.
Returns
arrayLinks
getTransferEncoding() ¶ public
getTransferEncoding(): string|null
TransferEncoding getter.
Returns
string|nullEncoding
jsonSerialize() ¶ public
jsonSerialize(): array
Serializes the email object to a value that can be natively serialized and re-used to clone this email instance.
Returns
arraySerializable array of configuration properties.
Throws
ExceptionWhen a view var object can not be properly serialized.
readFile() ¶ protected
readFile(Psr\Http\Message\UploadedFileInterface|string $file): string
Read the file contents and return a base64 version of the file contents.
Parameters
-
Psr\Http\Message\UploadedFileInterface|string$file The absolute path to the file to read or UploadedFileInterface instance.
Returns
stringFile contents in base64 encoding
reset() ¶ public
reset(): $this
Reset all the internal variables to be able to send out a new email.
Returns
$thissetAttachments() ¶ public
setAttachments(array $attachments): $this
Add attachments to the email message
Attachments can be defined in a few forms depending on how much control you need:
Attach a file:
$this->setAttachments(['custom_name.txt' => 'path/to/file.txt']);
Attach a file and specify additional properties:
$this->setAttachments(['custom_name.png' => [
'file' => 'path/to/file',
'mimetype' => 'image/png',
'contentId' => 'abc123',
'contentDisposition' => false
]
]);
Attach a file from string and specify additional properties:
$this->setAttachments(['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
-
array$attachments Array of filenames.
Returns
$thisThrows
InvalidArgumentExceptionsetBcc() ¶ public
setBcc(array|string $email, string|null $name = null): $this
Sets "bcc" address.
Parameters
-
array|string$email String with email, Array with email as key, name as value or email as value (without name)
-
string|null$name optional Name
Returns
$thissetBody() ¶ public
setBody(array<string, string> $content): $this
Set message body.
Parameters
-
array<string, string>$content Content array with keys "text" and/or "html" with content string of respective type.
Returns
$thissetBodyHtml() ¶ public
setBodyHtml(string $content): $this
Set HTML body for message.
Parameters
-
string$content Content string
Returns
$thissetBodyText() ¶ public
setBodyText(string $content): $this
Set text body for message.
Parameters
-
string$content Content string
Returns
$thissetCc() ¶ public
setCc(array|string $email, string|null $name = null): $this
Sets "cc" address.
Parameters
-
array|string$email String with email, Array with email as key, name as value or email as value (without name)
-
string|null$name optional Name
Returns
$thissetCharset() ¶ public
setCharset(string $charset): $this
Charset setter.
Parameters
-
string$charset Character set.
Returns
$thissetConfig() ¶ public
setConfig(array<string, mixed> $config): $this
Sets the configuration for this instance.
Parameters
-
array<string, mixed>$config Config array.
Returns
$thissetDomain() ¶ public
setDomain(string $domain): $this
Sets domain.
Domain as top level (the part after @).
Parameters
-
string$domain Manually set the domain for CLI mailing.
Returns
$thissetEmail() ¶ protected
setEmail(string $varName, array|string $email, string|null $name): $this
Set email
Parameters
-
string$varName Property name
-
array|string$email String with email, Array with email as key, name as value or email as value (without name)
-
string|null$name Name
Returns
$thisThrows
InvalidArgumentExceptionsetEmailFormat() ¶ public
setEmailFormat(string $format): $this
Sets email format.
Parameters
-
string$format Formatting string.
Returns
$thisThrows
InvalidArgumentExceptionsetEmailPattern() ¶ public
setEmailPattern(string|null $regex): $this
EmailPattern setter/getter
Parameters
-
string|null$regex The pattern to use for email address validation, null to unset the pattern and make use of filter_var() instead.
Returns
$thissetEmailSingle() ¶ protected
setEmailSingle(string $varName, array|string $email, string|null $name, string $throwMessage): $this
Set only 1 email
Parameters
-
string$varName Property name
-
array|string$email String with email, Array with email as key, name as value or email as value (without name)
-
string|null$name Name
-
string$throwMessage Exception message
Returns
$thisThrows
InvalidArgumentExceptionsetFrom() ¶ public
setFrom(array|string $email, string|null $name = null): $this
Sets "from" address.
Parameters
-
array|string$email String with email, Array with email as key, name as value or email as value (without name)
-
string|null$name optional Name
Returns
$thisThrows
InvalidArgumentExceptionsetHeaderCharset() ¶ public
setHeaderCharset(string|null $charset): $this
HeaderCharset setter.
Parameters
-
string|null$charset Character set.
Returns
$thissetHeaders() ¶ public
setHeaders(array $headers): $this
Sets headers for the message
Parameters
-
array$headers Associative array containing headers to be set.
Returns
$thissetMessageId() ¶ public
setMessageId(string|bool $message): $this
Sets message ID.
Parameters
-
string|bool$message True to generate a new Message-ID, False to ignore (not send in email), String to set as Message-ID.
Returns
$thisThrows
InvalidArgumentExceptionsetPriority() ¶ public
setPriority(int|null $priority): $this
Sets priority.
Parameters
-
int|null$priority 1 (highest) to 5 (lowest)
Returns
$thissetReadReceipt() ¶ public
setReadReceipt(array|string $email, string|null $name = null): $this
Sets Read Receipt (Disposition-Notification-To header).
Parameters
-
array|string$email String with email, Array with email as key, name as value or email as value (without name)
-
string|null$name optional Name
Returns
$thisThrows
InvalidArgumentExceptionsetReplyTo() ¶ public
setReplyTo(array|string $email, string|null $name = null): $this
Sets "Reply-To" address.
Parameters
-
array|string$email String with email, Array with email as key, name as value or email as value (without name)
-
string|null$name optional Name
Returns
$thisThrows
InvalidArgumentExceptionsetReturnPath() ¶ public
setReturnPath(array|string $email, string|null $name = null): $this
Sets return path.
Parameters
-
array|string$email String with email, Array with email as key, name as value or email as value (without name)
-
string|null$name optional Name
Returns
$thisThrows
InvalidArgumentExceptionsetSender() ¶ public
setSender(array|string $email, string|null $name = null): $this
Sets the "sender" address. See RFC link below for full explanation.
Parameters
-
array|string$email String with email, Array with email as key, name as value or email as value (without name)
-
string|null$name optional Name
Returns
$thisThrows
InvalidArgumentExceptionLinks
setSubject() ¶ public
setSubject(string $subject): $this
Sets subject.
Parameters
-
string$subject Subject string.
Returns
$thissetTo() ¶ public
setTo(array|string $email, string|null $name = null): $this
Sets "to" address.
Parameters
-
array|string$email String with email, Array with email as key, name as value or email as value (without name)
-
string|null$name optional Name
Returns
$thissetTransferEncoding() ¶ public
setTransferEncoding(string|null $encoding): $this
TransferEncoding setter.
Parameters
-
string|null$encoding Encoding set.
Returns
$thisThrows
InvalidArgumentExceptionvalidateEmail() ¶ protected
validateEmail(string $email, string $context): void
Validate email address
Parameters
-
string$email Email address to validate
-
string$context Which property was set
Returns
voidThrows
InvalidArgumentExceptionIf email address does not validate
wrap() ¶ protected
wrap(string|null $message = null, int $wrapLength = self::LINE_LENGTH_MUST): array<string>
Wrap the message to follow the RFC 2822 - 2.1.1
Parameters
-
string|null$message optional Message to wrap
-
int$wrapLength optional The line length
Returns
array<string>Wrapped message
Property Detail
$appCharset ¶ protected
The application wide charset, used to encode headers and body
Type
string|null$attachments ¶ protected
List of files that should be attached to the email.
Only absolute paths
Type
array<string, array>$bcc ¶ protected
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
Type
array$cc ¶ protected
Carbon Copy
List of email's that should receive a copy of the email. The Recipient WILL be able to see this list
Type
array$domain ¶ protected
Domain for messageId generation. Needs to be manually set for CLI mailing as env('HTTP_HOST') is empty
Type
string$emailPattern ¶ protected
Regex for email validation
If null, filter_var() will be used. Use the emailPattern() method to set a custom pattern.
Type
string|null$headerCharset ¶ protected
Charset the email header is sent in If null, the $charset property will be used as default
Type
string|null$headers ¶ protected
Associative array of a user defined headers Keys will be prefixed 'X-' as per RFC2822 Section 4.7.5
Type
array$returnPath ¶ protected
The mail that will be used in case of any errors like
- Remote mailserver down
- Remote user has exceeded his quota
- Unknown user
Type
array$transferEncoding ¶ protected
The email transfer encoding used. If null, the $charset property is used for determined the transfer encoding.
Type
string|null$transferEncodingAvailable ¶ protected
Available encoding to be set for transfer.
Type
array<string>