PHPMailer

PHPMailer - PHP email creation and transport class.

author

Marcus Bointon (Synchro/coolbru) phpmailer@synchromedia.co.uk

author

Jim Jagielski (jimjag) jimjag@gmail.com

author

Andy Prevost (codeworxtech) codeworxtech@users.sourceforge.net

author

Brent R. Matzelle (original founder)

package

Default

Methods

Constructor.

__construct(boolean $exceptions = null)

Arguments

$exceptions

boolean

Should we throw external exceptions?

Destructor.

__destruct()

Get the MIME type for a file extension.

_mime_types(string $ext = ''): string
static

Arguments

$ext

string

File extension

Response

string

MIME type of file

Add a "To" address.

addAddress(string $address,string $name = ''): boolean
Throws
\PHPMailer\PHPMailer\Exception

Arguments

$address

string

The email address to send to

$name

string

Response

boolean

true on success, false if address already used or invalid in some way

Add an address to one of the recipient arrays or to the ReplyTo array.

addAnAddress(string $kind,string $address,string $name = ''): boolean

Addresses that have been added already return false, but do not throw exceptions.

Throws
\PHPMailer\PHPMailer\Exception

Arguments

$kind

string

One of 'to', 'cc', 'bcc', or 'ReplyTo'

$address

string

The email address to send, resp. to reply to

$name

string

Response

boolean

true on success, false if address already used or invalid in some way

Add an attachment from a path on the filesystem.

addAttachment(string $path,string $name = '',string $encoding = self::ENCODING_BASE64,string $type = '',string $disposition = 'attachment'): boolean

Never use a user-supplied path to a file! Returns false if the file could not be found or read. Explicitly does not support passing URLs; PHPMailer is not an HTTP client. If you need to do that, fetch the resource yourself and pass it in via a local file or string.

Throws
\PHPMailer\PHPMailer\Exception

Arguments

$path

string

Path to the attachment

$name

string

Overrides the attachment name

$encoding

string

File encoding (see $Encoding)

$type

string

MIME type, e.g. image/jpeg; determined automatically from $path if not specified

$disposition

string

Disposition to use

Response

boolean

Add a "BCC" address.

addBCC(string $address,string $name = ''): boolean
Throws
\PHPMailer\PHPMailer\Exception

Arguments

$address

string

The email address to send to

$name

string

Response

boolean

true on success, false if address already used or invalid in some way

Add a "CC" address.

addCC(string $address,string $name = ''): boolean
Throws
\PHPMailer\PHPMailer\Exception

Arguments

$address

string

The email address to send to

$name

string

Response

boolean

true on success, false if address already used or invalid in some way

Add a custom header.

addCustomHeader(string $name,string|null $value = null)

$name value can be overloaded to contain both header name and value (name:value).

Throws
\PHPMailer\PHPMailer\Exception

Arguments

$name

string

Custom header name

$value

string|null

Header value

Add an embedded (inline) attachment from a file.

addEmbeddedImage(string $path,string $cid,string $name = '',string $encoding = self::ENCODING_BASE64,string $type = '',string $disposition = 'inline'): boolean

This can include images, sounds, and just about any other document type. These differ from 'regular' attachments in that they are intended to be displayed inline with the message, not just attached for download. This is used in HTML messages that embed the images the HTML refers to using the $cid value in img tags, for example <img src="cid:mylogo">. Never use a user-supplied path to a file!

Throws
\PHPMailer\PHPMailer\Exception

Arguments

$path

string

Path to the attachment

$cid

string

Content ID of the attachment; Use this to reference the content when using an embedded image in HTML

$name

string

Overrides the attachment filename

$encoding

string

File encoding (see $Encoding) defaults to base64

$type

string

File MIME type (by default mapped from the $path filename's extension)

$disposition

string

Disposition to use: inline (default) or attachment (unlikely you want this – {@see addAttachment()} instead)

Response

boolean

True on successfully adding an attachment

Add an address to one of the recipient arrays or to the ReplyTo array. Because PHPMailer can't validate addresses with an IDN without knowing the PHPMailer::$CharSet (that can still be modified after calling this function), addition of such addresses is delayed until send().

addOrEnqueueAnAddress(string $kind,string $address,string $name): boolean

Addresses that have been added already return false, but do not throw exceptions.

Throws
\PHPMailer\PHPMailer\Exception

Arguments

$kind

string

One of 'to', 'cc', 'bcc', or 'ReplyTo'

$address

string

The email address

$name

string

An optional username associated with the address

Response

boolean

true on success, false if address already used or invalid in some way

Create recipient headers.

addrAppend(string $type,array $addr): string

Arguments

$type

string

$addr

array

An array of recipients, where each recipient is a 2-element indexed array with element 0 containing an address and element 1 containing a name, like: [['joe@example.com', 'Joe User'], ['zoe@example.com', 'Zoe User']]

Response

string

Add a "Reply-To" address.

addReplyTo(string $address,string $name = ''): boolean
Throws
\PHPMailer\PHPMailer\Exception

Arguments

$address

string

The email address to reply to

$name

string

Response

boolean

true on success, false if address already used or invalid in some way

Format an address for use in a message header.

addrFormat(array $addr): string

Arguments

$addr

array

A 2-element indexed array, element 0 containing an address, element 1 containing a name like ['joe@example.com', 'Joe User']

Response

string

Add a string or binary attachment (non-filesystem).

addStringAttachment(string $string,string $filename,string $encoding = self::ENCODING_BASE64,string $type = '',string $disposition = 'attachment'): boolean

This method can be used to attach ascii or binary data, such as a BLOB record from a database.

Throws
\PHPMailer\PHPMailer\Exception

Arguments

$string

string

String attachment data

$filename

string

Name of the attachment

$encoding

string

File encoding (see $Encoding)

$type

string

File extension (MIME) type

$disposition

string

Disposition to use

Response

boolean

True on successfully adding an attachment

Add an embedded stringified attachment.

addStringEmbeddedImage(string $string,string $cid,string $name = '',string $encoding = self::ENCODING_BASE64,string $type = '',string $disposition = 'inline'): boolean

This can include images, sounds, and just about any other document type. If your filename doesn't contain an extension, be sure to set the $type to an appropriate MIME type.

Throws
\PHPMailer\PHPMailer\Exception

Arguments

$string

string

The attachment binary data

$cid

string

Content ID of the attachment; Use this to reference the content when using an embedded image in HTML

$name

string

A filename for the attachment. If this contains an extension, PHPMailer will attempt to set a MIME type for the attachment. For example 'file.jpg' would get an 'image/jpeg' MIME type.

$encoding

string

File encoding (see $Encoding), defaults to 'base64'

$type

string

MIME type - will be used in preference to any automatically derived type

$disposition

string

Disposition to use

Response

boolean

True on successfully adding an attachment

Check if this message has an alternative body set.

alternativeExists(): boolean

Response

boolean

Attach all file, string, and binary attachments to the message.

attachAll(string $disposition_type,string $boundary): string

Returns an empty string on failure.

Throws
\PHPMailer\PHPMailer\Exception

Arguments

$disposition_type

string

$boundary

string

Response

string

Check if an attachment (non-inline) is present.

attachmentExists(): boolean

Response

boolean

Encode and wrap long multibyte strings for mail headers without breaking lines within a character.

base64EncodeWrapMB(string $str,string $linebreak = null): string

Adapted from a function by paravoid.

see http://www.php.net/manual/en/function.mb-encode-mimeheader.php#60283

Arguments

$str

string

multi-byte text to wrap encode

$linebreak

string

string to use as linefeed/end-of-line

Response

string

Check if an embedded attachment is present with this cid.

cidExists(string $cid): boolean

Arguments

$cid

string

Response

boolean

Clear all To recipients.

clearAddresses()

Clear all recipient types.

clearAllRecipients()

Clear all filesystem, string, and binary attachments.

clearAttachments()

Clear all BCC recipients.

clearBCCs()

Clear all CC recipients.

clearCCs()

Clear all custom headers.

clearCustomHeaders()

Clear queued addresses of given kind.

clearQueuedAddresses(string $kind)

Arguments

$kind

string

'to', 'cc', or 'bcc'

Clear all ReplyTo recipients.

clearReplyTos()

Assemble the message body.

createBody(): string

Returns an empty string on failure.

Throws
\PHPMailer\PHPMailer\Exception

Response

string

The assembled message body

Assemble message headers.

createHeader(): string

Response

string

The assembled headers

Create the DKIM header and body in a new message header.

DKIM_Add(string $headers_line,string $subject,string $body): string
Throws
\PHPMailer\PHPMailer\Exception

Arguments

$headers_line

string

Header lines

$subject

string

Subject

$body

string

Body

Response

string

Generate a DKIM canonicalization body.

DKIM_BodyC(string $body): string

Uses the 'simple' algorithm from RFC6376 section 3.4.3. Canonicalized bodies should always use CRLF, regardless of mailer setting.

see https://tools.ietf.org/html/rfc6376#section-3.4.3

Arguments

$body

string

Message Body

Response

string

Generate a DKIM canonicalization header.

DKIM_HeaderC(string $signHeader): string

Uses the 'relaxed' algorithm from RFC6376 section 3.4.2. Canonicalized headers should always use CRLF, regardless of mailer setting.

see https://tools.ietf.org/html/rfc6376#section-3.4.2

Arguments

$signHeader

string

Header

Response

string

Quoted-Printable-encode a DKIM header.

DKIM_QP(string $txt): string

Arguments

$txt

string

Response

string

Generate a DKIM signature.

DKIM_Sign(string $signHeader): string
Throws
\PHPMailer\PHPMailer\Exception

Arguments

$signHeader

string

Response

string

The DKIM signature value

Perform a callback.

doCallback(boolean $isSent,array $to,array $cc,array $bcc,string $subject,string $body,string $from,array $extra)

Arguments

$isSent

boolean

$to

array

$cc

array

$bcc

array

$subject

string

$body

string

$from

string

$extra

array

Output debugging info via a user-defined method.

edebug(string $str)

Only generates output if debug output is enabled.

see \PHPMailer\PHPMailer\PHPMailer::Debugoutput\PHPMailer\PHPMailer\PHPMailer::SMTPDebug

Arguments

$str

string

Encode a file attachment in requested format.

encodeFile(string $path,string $encoding = self::ENCODING_BASE64): string

Returns an empty string on failure.

Arguments

$path

string

The full path to the file

$encoding

string

The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable'

Response

string

Encode a header value (not including its label) optimally.

encodeHeader(string $str,string $position = 'text'): string

Picks shortest of Q, B, or none. Result includes folding if needed. See RFC822 definitions for phrase, comment and text positions.

Arguments

$str

string

The header value to encode

$position

string

What context the string will be used in

Response

string

Encode a string using Q encoding.

encodeQ(string $str,string $position = 'text'): string
see http://tools.ietf.org/html/rfc2047#section-4.2

Arguments

$str

string

the text to encode

$position

string

Where the text is going to be used, see the RFC for what that means

Response

string

Encode a string in quoted-printable format.

encodeQP(string $string): string

According to RFC2045 section 6.7.

Arguments

$string

string

The text to encode

Response

string

Encode a string in requested format.

encodeString(string $str,string $encoding = self::ENCODING_BASE64): string

Returns an empty string on failure.

Throws
\PHPMailer\PHPMailer\Exception

Arguments

$str

string

The text to encode

$encoding

string

The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable'

Response

string

Return the end of a message boundary.

endBoundary(string $boundary): string

Arguments

$boundary

string

Response

string

Check whether a file path is safe, accessible, and readable.

fileIsAccessible(string $path): boolean
static

Arguments

$path

string

A relative or absolute path to a file

Response

boolean

Map a file name to a MIME type.

filenameToType(string $filename): string
static

Defaults to 'application/octet-stream', i.e.. arbitrary binary data.

Arguments

$filename

string

A file name or full path, does not need to exist as a file

Response

string

Create a unique ID to use for boundaries.

generateId(): string

Response

string

Allows for public read access to 'all_recipients' property.

getAllRecipientAddresses(): array

Before the send() call, queued addresses (i.e. with IDN) are not yet included.

Response

array

Return the array of attachments.

getAttachments(): array

Response

array

Allows for public read access to 'bcc' property.

getBccAddresses(): array

Before the send() call, queued addresses (i.e. with IDN) are not yet included.

Response

array

Return the start of a message boundary.

getBoundary(string $boundary,string $charSet,string $contentType,string $encoding): string

Arguments

$boundary

string

$charSet

string

$contentType

string

$encoding

string

Response

string

Allows for public read access to 'cc' property.

getCcAddresses(): array

Before the send() call, queued addresses (i.e. with IDN) are not yet included.

Response

array

Returns all custom headers.

getCustomHeaders(): array

Response

array

Return the Message-ID header of the last email.

getLastMessageID(): string

Technically this is the value from the last time the headers were created, but it's also the message ID of the last sent message except in pathological cases.

Response

string

Return the current line break format string.

getLE(): string
static

Response

string

Get the message MIME type headers.

getMailMIME(): string

Response

string

Get the OAuthTokenProvider instance.

getOAuth(): \PHPMailer\PHPMailer\OAuthTokenProvider

Allows for public read access to 'ReplyTo' property.

getReplyToAddresses(): array

Before the send() call, queued addresses (i.e. with IDN) are not yet included.

Response

array

Returns the whole MIME message.

getSentMIMEMessage(): string

Includes complete headers and body. Only valid post preSend().

see \PHPMailer\PHPMailer\PHPMailer::preSend()

Response

string

Build an error message starting with a generic one and adding details if possible.

getSmtpErrorMessage(string $base_key): string

Arguments

$base_key

string

Response

string

Get an instance to use for SMTP operations.

getSMTPInstance(): \PHPMailer\PHPMailer\SMTP

Override this function to load your own SMTP implementation, or set one with setSMTPInstance.

Response

\PHPMailer\PHPMailer\SMTP

Allows for public read access to 'to' property.

getToAddresses(): array

Before the send() call, queued addresses (i.e. with IDN) are not yet included.

Response

array

Get the array of strings for the current language.

getTranslations(): array

Response

array

Does a string contain any 8-bit chars (in any charset)?

has8bitChars(string $text): boolean

Arguments

$text

string

Response

boolean

Detect if a string contains a line longer than the maximum line length allowed by RFC 2822 section 2.1.1.

hasLineLongerThanMax(string $str): boolean
static

Arguments

$str

string

Response

boolean

Check if a string contains multi-byte characters.

hasMultiBytes(string $str): boolean

Arguments

$str

string

multi-byte text to wrap encode

Response

boolean

Format a header line.

headerLine(string $name,string|integer $value): string

Arguments

$name

string

$value

string|integer

Response

string

Convert an HTML string into plain text.

html2text(string $html,boolean|callable $advanced = false): string

This is used by msgHTML(). Note - older versions of this function used a bundled advanced converter which was removed for license reasons in #232. Example usage:

//Use default conversion
$plain = $mail->html2text($html);
//Use your own custom converter
$plain = $mail->html2text($html, function($html) {
    $converter = new MyHtml2text($html);
    return $converter->get_text();
});

Arguments

$html

string

The HTML text to convert

$advanced

boolean|callable

Any boolean value to use the internal converter, or provide your own callable for custom conversion. Never pass user-supplied data into this parameter

Response

string

Tells whether IDNs (Internationalized Domain Names) are supported or not. This requires the `intl` and `mbstring` PHP extensions.

idnSupported(): boolean
static

Response

boolean

true if required functions for IDN support are present

Check if an inline attachment is present.

inlineImageExists(): boolean

Response

boolean

Check if an error occurred.

isError(): boolean

Response

boolean

True if an error did occur

Sets message type to HTML or plain.

isHTML(boolean $isHtml = true)

Arguments

$isHtml

boolean

True for HTML mode

Send messages using PHP's mail() function.

isMail()

Check whether a file path is of a permitted type.

isPermittedPath(string $path): boolean
static

Used to reject URLs and phar files from functions that access local file paths, such as addAttachment.

Arguments

$path

string

A relative or absolute path to a file

Response

boolean

Send messages using qmail.

isQmail()

Send messages using $Sendmail.

isSendmail()

Fix CVE-2016-10033 and CVE-2016-10045 by disallowing potentially unsafe shell characters.

isShellSafe(string $string): boolean
static

Note that escapeshellarg and escapeshellcmd are inadequate for our purposes, especially on Windows.

see https://github.com/PHPMailer/PHPMailer/issues/924

CVE-2016-10045 bug report

Arguments

$string

string

The string to be validated

Response

boolean

Send messages using SMTP.

isSMTP()

Validate whether a string contains a valid value to use as a hostname or IP address.

isValidHost(string $host): boolean
static

IPv6 addresses must include [], e.g. [::1], not just ::1.

Arguments

$host

string

The host name or IP address to check

Response

boolean

Get an error message in the current language.

lang(string $key): string

Arguments

$key

string

Response

string

Call mail() in a safe_mode-aware fashion.

mailPassthru(string $to,string $subject,string $body,string $header,string|null $params): boolean

Also, unless sendmail_path points to sendmail (or something that claims to be sendmail), don't pass params (not a perfect fix, but it will do).

Arguments

$to

string

To

$subject

string

Subject

$body

string

Message Body

$header

string

Additional Header(s)

$params

string|null

Params

Response

boolean

Send mail using the PHP mail() function.

mailSend(string $header,string $body): boolean
see http://www.php.net/manual/en/book.mail.php
Throws
\PHPMailer\PHPMailer\Exception

Arguments

$header

string

The message headers

$body

string

The message body

Response

boolean

Multi-byte-safe pathinfo replacement.

mb_pathinfo(string $path,integer|string $options = null): string|array
static

Drop-in replacement for pathinfo(), but multibyte- and cross-platform-safe.

see http://www.php.net/manual/en/function.pathinfo.php#107461

Arguments

$path

string

A filename or path, does not need to exist as a file

$options

integer|string

Either a PATHINFO_* constant, or a string name to return only the specified piece

Response

string|array

Create a message body from an HTML string.

msgHTML(string $message,string $basedir = '',boolean|callable $advanced = false): string

Automatically inlines images and creates a plain-text version by converting the HTML, overwriting any existing values in Body and AltBody. Do not source $message content from user input! $basedir is prepended when handling relative URLs, e.g. and must not be empty will look for an image file in $basedir/images/a.png and convert it to inline. If you don't provide a $basedir, relative paths will be left untouched (and thus probably break in email) Converts data-uri images into embedded attachments. If you don't want to apply these transformations to your HTML, just set Body and AltBody directly.

see \PHPMailer\PHPMailer\PHPMailer::html2text()
Throws
\PHPMailer\PHPMailer\Exception

Arguments

$message

string

HTML message string

$basedir

string

Absolute path to a base directory to prepend to relative paths to images

$advanced

boolean|callable

Whether to use the internal HTML to text converter or your own custom converter

Response

string

The transformed message body

Normalize line breaks in a string.

normalizeBreaks(string $text,string $breaktype = null): string
static

Converts UNIX LF, Mac CR and Windows CRLF line breaks into a single line break format. Defaults to CRLF (for message bodies) and preserves consecutive breaks.

Arguments

$text

string

$breaktype

string

What kind of line break to use; defaults to static::$LE

Response

string

Parse and validate a string containing one or more RFC822-style comma-separated email addresses of the form "display name <address>" into an array of name/address pairs.

parseAddresses(string $addrstr,boolean $useimap = true,string $charset = self::CHARSET_ISO88591): array
static

Uses the imap_rfc822_parse_adrlist function if the IMAP extension is available. Note that quotes in the name part are removed.

see http://www.andrew.cmu.edu/user/agreen1/testing/mrbs/web/Mail/RFC822.php

A more careful implementation

Arguments

$addrstr

string

The address list string

$useimap

boolean

Whether to use the IMAP extension to parse the list

$charset

string

The charset to use when decoding the address list string.

Response

array

Actually send a message via the selected mechanism.

postSend(): boolean
Throws
\PHPMailer\PHPMailer\Exception

Response

boolean

Prepare a message for sending.

preSend(): boolean
Throws
\PHPMailer\PHPMailer\Exception

Response

boolean

Converts IDN in given email address to its ASCII form, also known as punycode, if possible.

punyencodeAddress(string $address): string

Important: Address must be passed in same encoding as currently set in PHPMailer::$CharSet. This function silently returns unmodified address if:

  • No conversion is necessary (i.e. domain name is not an IDN, or is already in ASCII form)
  • Conversion to punycode is impossible (e.g. required PHP functions are not available) or fails for any reason (e.g. domain contains characters not allowed in an IDN).
see \PHPMailer\PHPMailer\PHPMailer::CharSet

Arguments

$address

string

The email address to convert

Response

string

The encoded address in ASCII form

If a string contains any "special" characters, double-quote the name, and escape any double quotes with a backslash.

quotedString(string $str): string
static
see \PHPMailer\PHPMailer\RFC822

3.4.1

Arguments

$str

string

Response

string

Return an RFC 822 formatted date.

rfcDate(): string
static

Response

string

Strip newlines to prevent header injection.

secureHeader(string $str): string

Arguments

$str

string

Response

string

Create a message and send it.

send(): boolean

Uses the sending method specified by $Mailer.

Throws
\PHPMailer\PHPMailer\Exception

Response

boolean

false on error - See the ErrorInfo property for details of the error

Send mail using the $Sendmail program.

sendmailSend(string $header,string $body): boolean
see \PHPMailer\PHPMailer\PHPMailer::Sendmail
Throws
\PHPMailer\PHPMailer\Exception

Arguments

$header

string

The message headers

$body

string

The message body

Response

boolean

Get the server hostname.

serverHostname(): string

Returns 'localhost.localdomain' if unknown.

Response

string

Set or reset instance properties.

set(string $name,mixed $value = ''): boolean

You should avoid this function - it's more verbose, less efficient, more error-prone and harder to debug than setting properties directly. Usage Example: $mail->set('SMTPSecure', static::ENCRYPTION_STARTTLS); is the same as: $mail->SMTPSecure = static::ENCRYPTION_STARTTLS;.

Arguments

$name

string

The property name to set

$value

mixed

The value to set the property to

Response

boolean

Add an error message to the error container.

setError(string $msg)

Arguments

$msg

string

Set the From and FromName properties.

setFrom(string $address,string $name = '',boolean $auto = true): boolean
Throws
\PHPMailer\PHPMailer\Exception

Arguments

$address

string

$name

string

$auto

boolean

Whether to also set the Sender address, defaults to true

Response

boolean

Set the language for error messages.

setLanguage(string $langcode = 'en',string $lang_path = ''): boolean

The default language is English.

Arguments

$langcode

string

ISO 639-1 2-character language code (e.g. French is "fr") Optionally, the language code can be enhanced with a 4-character script annotation and/or a 2-character country annotation.

$lang_path

string

Path to the language file directory, with trailing separator (slash) Do not set this from user input!

Response

boolean

Returns true if the requested language was loaded, false otherwise.

Set the line break format string, e.g. "\r\n".

setLE(string $le)
static

Arguments

$le

string

Set the message type.

setMessageType()

PHPMailer only supports some preset message types, not arbitrary MIME structures.

Set an OAuthTokenProvider instance.

setOAuth(\PHPMailer\PHPMailer\OAuthTokenProvider $oauth)

Provide an instance to use for SMTP operations.

setSMTPInstance(\PHPMailer\PHPMailer\SMTP $smtp): \PHPMailer\PHPMailer\SMTP

Apply word wrapping to the message body.

setWordWrap()

Wraps the message body to the number of chars set in the WordWrap property. You should only do this to plain-text bodies as wrapping HTML tags may break them. This is called automatically by createBody(), so you don't need to call it yourself.

Set the public and private key files and password for S/MIME signing.

sign(string $cert_filename,string $key_filename,string $key_pass,string $extracerts_filename = '')

Arguments

$cert_filename

string

$key_filename

string

$key_pass

string

Password for private key

$extracerts_filename

string

Optional path to chain certificate

Close the active SMTP session if one exists.

smtpClose()

Initiate a connection to an SMTP server.

smtpConnect(array $options = null): boolean

Returns false if the operation failed.

uses
Throws
\PHPMailer\PHPMailer\Exception

Arguments

$options

array

An array of options compatible with stream_context_create()

Response

boolean

Send mail via SMTP.

smtpSend(string $header,string $body): boolean

Returns false if there is a bad MAIL FROM, RCPT, or DATA input.

see \PHPMailer\PHPMailer\PHPMailer::setSMTPInstance()

to use a different class.

uses
Throws
\PHPMailer\PHPMailer\Exception

Arguments

$header

string

The message headers

$body

string

The message body

Response

boolean

Remove trailing breaks from a string.

stripTrailingWSP(string $text): string
static

Arguments

$text

string

Response

string

The text to remove breaks from

Return a formatted mail line.

textLine(string $value): string

Arguments

$value

string

Response

string

Find the last character boundary prior to $maxLength in a utf-8 quoted-printable encoded string.

utf8CharBoundary(string $encodedText,integer $maxLength): integer

Original written by Colin Brown.

Arguments

$encodedText

string

utf-8 QP text

$maxLength

integer

Find the last character boundary prior to this length

Response

integer

Check that a string looks like an email address.

validateAddress(string $address,string|callable $patternselect = null): boolean
static

Validation patterns supported:

  • auto Pick best pattern automatically;
  • pcre8 Use the squiloople.com pattern, requires PCRE > 8.0;
  • pcre Use old PCRE implementation;
  • php Use PHP built-in FILTER_VALIDATE_EMAIL;
  • html5 Use the pattern given by the HTML5 spec for 'email' type form input elements.
  • noregex Don't use a regex: super fast, really dumb. Alternatively you may pass in a callable to inject your own validator, for example:
PHPMailer::validateAddress('user@example.com', function($address) {
    return (strpos($address, '@') !== false);
});

You can also set the PHPMailer::$validator static to a callable, allowing built-in methods to use your validator.

Arguments

$address

string

The email address to check

$patternselect

string|callable

Which pattern to use

Response

boolean

Validate encodings.

validateEncoding(string $encoding): boolean

Arguments

$encoding

string

Response

boolean

Word-wrap message.

wrapText(string $message,integer $length,boolean $qp_mode = false): string

For use with mailers that do not automatically perform wrapping and for quoted-printable encoded messages. Original written by philippe.

Arguments

$message

string

The message to wrap

$length

integer

The line length to wrap to

$qp_mode

boolean

Whether to run in Quoted-Printable mode

Response

string

Constants

CHARSET_ASCII

CHARSET_ASCII

CHARSET_ISO88591

CHARSET_ISO88591

CHARSET_UTF8

CHARSET_UTF8

CONTENT_TYPE_PLAINTEXT

CONTENT_TYPE_PLAINTEXT

CONTENT_TYPE_TEXT_CALENDAR

CONTENT_TYPE_TEXT_CALENDAR

CONTENT_TYPE_TEXT_HTML

CONTENT_TYPE_TEXT_HTML

CONTENT_TYPE_MULTIPART_ALTERNATIVE

CONTENT_TYPE_MULTIPART_ALTERNATIVE

CONTENT_TYPE_MULTIPART_MIXED

CONTENT_TYPE_MULTIPART_MIXED

ENCODING_7BIT

ENCODING_7BIT

ENCODING_8BIT

ENCODING_8BIT

ENCODING_BASE64

ENCODING_BASE64

ENCODING_BINARY

ENCODING_BINARY

ENCODING_QUOTED_PRINTABLE

ENCODING_QUOTED_PRINTABLE

ENCRYPTION_STARTTLS

ENCRYPTION_STARTTLS

ENCRYPTION_SMTPS

ENCRYPTION_SMTPS

ICAL_METHOD_REQUEST

ICAL_METHOD_REQUEST

ICAL_METHOD_PUBLISH

ICAL_METHOD_PUBLISH

ICAL_METHOD_REPLY

ICAL_METHOD_REPLY

ICAL_METHOD_ADD

ICAL_METHOD_ADD

ICAL_METHOD_CANCEL

ICAL_METHOD_CANCEL

ICAL_METHOD_REFRESH

ICAL_METHOD_REFRESH

ICAL_METHOD_COUNTER

ICAL_METHOD_COUNTER

ICAL_METHOD_DECLINECOUNTER

ICAL_METHOD_DECLINECOUNTER

The PHPMailer Version number.

VERSION
var

Error severity: message only, continue processing.

STOP_MESSAGE
var

Error severity: message, likely ok to continue processing.

STOP_CONTINUE
var

Error severity: message, plus full stop, critical error reached.

STOP_CRITICAL
var

The SMTP standard CRLF line break.

CRLF

If you want to change line break format, change static::$LE, not this.

"Folding White Space" a white space string used for line folding.

FWS

The maximum line length supported by mail().

MAIL_MAX_LINE_LENGTH

Background: mail() will sometimes corrupt messages with headers headers longer than 65 chars, see #818.

var

The maximum line length allowed by RFC 2822 section 2.1.1.

MAX_LINE_LENGTH
var

The lower maximum line length allowed by RFC 2822 section 2.1.1.

STD_LINE_LENGTH

This length does NOT include the line break 76 means that lines will be 77 or 78 chars depending on whether the line break format is LF or CRLF; both are valid.

var

Properties

Email priority.

Priority :integer|null

Options: null (default), 1 = High, 3 = Normal, 5 = low. When null, the header is not set at all.

var

Type(s)

integer|null

The character set of the message.

CharSet :string
var

Type(s)

string

The MIME Content-type of the message.

ContentType :string
var

Type(s)

string

The message encoding.

Encoding :string

Options: "8bit", "7bit", "binary", "base64", and "quoted-printable".

var

Type(s)

string

Holds the most recent mailer error message.

ErrorInfo :string
var

Type(s)

string

The From email address for the message.

From :string
var

Type(s)

string

The From name of the message.

FromName :string
var

Type(s)

string

The envelope sender of the message.

Sender :string

This will usually be turned into a Return-Path header by the receiver, and is the address that bounces will be sent to. If not empty, will be passed via -f to sendmail or as the 'MAIL FROM' value over SMTP.

var

Type(s)

string

The Subject of the message.

Subject :string
var

Type(s)

string

An HTML or plain text message body.

Body :string

If HTML then call isHTML(true).

var

Type(s)

string

The plain-text message body.

AltBody :string

This body can be read by mail clients that do not have HTML email capability such as mutt & Eudora. Clients that can read HTML will view the normal Body.

var

Type(s)

string

An iCal message part body.

Ical :string

Only supported in simple alt or alt_inline message types To generate iCal event structures, use classes like EasyPeasyICS or iCalcreator.

see
var

Type(s)

string

Value-array of "method" in Contenttype header "text/calendar"

IcalMethods :array<mixed,string>
static
var

Type(s)

array<mixed,string>

The complete compiled MIME message body.

MIMEBody :string
var

Type(s)

string

The complete compiled MIME message headers.

MIMEHeader :string
var

Type(s)

string

Extra headers that createHeader() doesn't fold in.

mailHeader :string
var

Type(s)

string

Word-wrap the message body to this number of chars.

WordWrap :integer

Set to 0 to not wrap. A useful value here is 78, for RFC2822 section 2.1.1 compliance.

see
var

Type(s)

integer

Which method to use to send mail.

Mailer :string

Options: "mail", "sendmail", or "smtp".

var

Type(s)

string

The path to the sendmail program.

Sendmail :string
var

Type(s)

string

Whether mail() uses a fully sendmail-compatible MTA.

UseSendmailOptions :boolean

One which supports sendmail's "-oi -f" options.

var

Type(s)

boolean

The email address that a reading confirmation should be sent to, also known as read receipt.

ConfirmReadingTo :string
var

Type(s)

string

The hostname to use in the Message-ID header and as default HELO string.

Hostname :string

If empty, PHPMailer attempts to find one with, in order, $_SERVER['SERVER_NAME'], gethostname(), php_uname('n'), or the value 'localhost.localdomain'.

see
var

Type(s)

string

An ID to be used in the Message-ID header.

MessageID :string

If empty, a unique id will be generated. You can set your own, but it must be in the format "id@domain", as defined in RFC5322 section 3.6.4 or it will be ignored.

see
var

Type(s)

string

The message Date to be used in the Date header.

MessageDate :string

If empty, the current date will be added.

var

Type(s)

string

SMTP hosts.

Host :string

Either a single hostname or multiple semicolon-delimited hostnames. You can also specify a different port for each host by using this format: [hostname:port] (e.g. "smtp1.example.com:25;smtp2.example.com"). You can also specify encryption type, for example: (e.g. "tls://smtp1.example.com:587;ssl://smtp2.example.com:465"). Hosts will be tried in order.

var

Type(s)

string

The default SMTP server port.

Port :integer
var

Type(s)

integer

The SMTP HELO/EHLO name used for the SMTP connection.

Helo :string

Default is $Hostname. If $Hostname is empty, PHPMailer attempts to find one with the same method described above for $Hostname.

see
var

Type(s)

string

What kind of encryption to use on the SMTP connection.

SMTPSecure :string

Options: '', static::ENCRYPTION_STARTTLS, or static::ENCRYPTION_SMTPS.

var

Type(s)

string

Whether to enable TLS encryption automatically if a server supports it, even if `SMTPSecure` is not set to 'tls'.

SMTPAutoTLS :boolean

Be aware that in PHP >= 5.6 this requires that the server's certificates are valid.

var

Type(s)

boolean

Whether to use SMTP authentication.

SMTPAuth :boolean

Uses the Username and Password properties.

see
var

Type(s)

boolean

Options array passed to stream_context_create when connecting via SMTP.

SMTPOptions :array
var

Type(s)

array

SMTP username.

Username :string
var

Type(s)

string

SMTP password.

Password :string
var

Type(s)

string

SMTP authentication type. Options are CRAM-MD5, LOGIN, PLAIN, XOAUTH2.

AuthType :string

If not specified, the first one from that list that the server supports will be selected.

var

Type(s)

string

An implementation of the PHPMailer OAuthTokenProvider interface.

oauth :\PHPMailer\PHPMailer\OAuthTokenProvider

The SMTP server timeout in seconds.

Timeout :integer

Default of 5 minutes (300sec) is from RFC2821 section 4.5.3.2.

var

Type(s)

integer

Comma separated list of DSN notifications 'NEVER' under no circumstances a DSN must be returned to the sender.

dsn :

If you use NEVER all other notifications will be ignored. 'SUCCESS' will notify you when your mail has arrived at its destination. 'FAILURE' will arrive if an error occurred during delivery. 'DELAY' will notify you if there is an unusual delay in delivery, but the actual delivery's outcome (success or failure) is not yet decided.

see

See section 4.1 for more information about NOTIFY

Type(s)

SMTP class debug output mode.

SMTPDebug :integer

Debug output level. Options:

see

No output

Client messages

Client and server messages

As SERVER plus connection status

Noisy, low-level data output, rarely needed

var

Type(s)

integer

How to handle debug output.

Debugoutput :string|callable|\Psr\Log\LoggerInterface

Options:

  • echo Output plain-text as-is, appropriate for CLI
  • html Output escaped, line breaks converted to <br>, appropriate for browser output
  • error_log Output to error log as configured in php.ini By default PHPMailer will use echo if run from a cli or cli-server SAPI, html otherwise. Alternatively, you can provide a callable expecting two params: a message string and the debug level:
$mail->Debugoutput = function($str, $level) {echo "debug level $level; message: $str";};

Alternatively, you can pass in an instance of a PSR-3 compatible logger, though only debug level output is used:

$mail->Debugoutput = new myPsr3Logger;
see
var

Type(s)

string|callable|\Psr\Log\LoggerInterface

Whether to keep the SMTP connection open after each message.

SMTPKeepAlive :boolean

If this is set to true then the connection will remain open after a send, and closing the connection will require an explicit call to smtpClose(). It's a good idea to use this if you are sending multiple messages as it reduces overhead. See the mailing list example for how to use it.

var

Type(s)

boolean

Whether to split multiple to addresses into multiple messages or send them all in one message.

SingleTo :boolean

Only supported in mail and sendmail transports, not in SMTP.

var
deprecated

PHPMailer isn't a mailing list manager!

Type(s)

boolean

Storage for addresses when SingleTo is enabled.

SingleToArray :array
var

Type(s)

array

Whether to generate VERP addresses on send.

do_verp :boolean

Only applicable when sending via SMTP.

see

Postfix VERP info

var

Type(s)

boolean

Whether to allow sending messages with an empty body.

AllowEmpty :boolean
var

Type(s)

boolean

DKIM selector.

DKIM_selector :string
var

Type(s)

string

DKIM Identity.

DKIM_identity :string

Usually the email address used as the source of the email.

var

Type(s)

string

DKIM passphrase.

DKIM_passphrase :string

Used if your key is encrypted.

var

Type(s)

string

DKIM signing domain name.

DKIM_domain :string
example
var

Type(s)

string

DKIM Copy header field values for diagnostic use.

DKIM_copyHeaderFields :boolean
var

Type(s)

boolean

DKIM Extra signing headers.

DKIM_extraHeaders :array
example

'List-Help']

var

Type(s)

array

DKIM private key file path.

DKIM_private :string
var

Type(s)

string

DKIM private key string.

DKIM_private_string :string

If set, takes precedence over $DKIM_private.

var

Type(s)

string

Callback Action function name.

action_function :string

The function that handles the result of the send email action. It is called out by send() for each email sent.

Value can be any php callable: http://www.php.net/is_callable

Parameters: bool $result result of the send action array $to email addresses of the recipients array $cc cc email addresses array $bcc bcc email addresses string $subject the subject string $body the email body string $from email address of sender string $extra extra information of possible use "smtp_transaction_id' => last smtp transaction id

var

Type(s)

string

What to put in the X-Mailer header.

XMailer :string|null

Options: An empty string for PHPMailer default, whitespace/null for none, or a string to use.

var

Type(s)

string|null

Which validator to use by default when validating email addresses.

validator :string|callable
static

May be a callable to inject your own validator, but there are several built-in validators. The default validator uses PHP's FILTER_VALIDATE_EMAIL filter_var option.

see
var

Type(s)

string|callable

An instance of the SMTP sender class.

smtp :\PHPMailer\PHPMailer\SMTP

The array of 'to' names and addresses.

to :array
var

Type(s)

array

The array of 'cc' names and addresses.

cc :array
var

Type(s)

array

The array of 'bcc' names and addresses.

bcc :array
var

Type(s)

array

The array of reply-to names and addresses.

ReplyTo :array
var

Type(s)

array

An array of all kinds of addresses.

all_recipients :array

Includes all of $to, $cc, $bcc.

see
var

Type(s)

array

An array of names and addresses queued for validation.

RecipientsQueue :array

In send(), valid and non duplicate entries are moved to $all_recipients and one of $to, $cc, or $bcc. This array is used only for addresses with IDN.

see
var

Type(s)

array

An array of reply-to names and addresses queued for validation.

ReplyToQueue :array

In send(), valid and non duplicate entries are moved to $ReplyTo. This array is used only for addresses with IDN.

see
var

Type(s)

array

The array of attachments.

attachment :array
var

Type(s)

array

The array of custom headers.

CustomHeader :array
var

Type(s)

array

The most recent Message-ID (including angular brackets).

lastMessageID :string
var

Type(s)

string

The message's MIME type.

message_type :string
var

Type(s)

string

The array of MIME boundary strings.

boundary :array
var

Type(s)

array

The array of available text strings for the current language.

language :array
var

Type(s)

array

The number of errors encountered.

error_count :integer
var

Type(s)

integer

The S/MIME certificate file path.

sign_cert_file :string
var

Type(s)

string

The S/MIME key file path.

sign_key_file :string
var

Type(s)

string

The optional S/MIME extra certificates ("CA Chain") file path.

sign_extracerts_file :string
var

Type(s)

string

The S/MIME password for the key.

sign_key_pass :string

Used only if the key is encrypted.

var

Type(s)

string

Whether to throw exceptions for errors.

exceptions :boolean
var

Type(s)

boolean

Unique ID used for message ID and boundaries.

uniqueid :string
var

Type(s)

string

SMTP RFC standard line ending; Carriage Return, Line Feed.

LE :string
static
var

Type(s)

string