\PHPMailer\PHPMailerPHPMailer

PHPMailer - PHP email creation and transport class.

Summary

Methods
Properties
Constants
__construct()
__destruct()
isHTML()
isSMTP()
isMail()
isSendmail()
isQmail()
addAddress()
addCC()
addBCC()
addReplyTo()
parseAddresses()
setFrom()
getLastMessageID()
validateAddress()
idnSupported()
punyencodeAddress()
send()
preSend()
postSend()
getSMTPInstance()
setSMTPInstance()
smtpConnect()
smtpClose()
setLanguage()
getTranslations()
addrAppend()
addrFormat()
wrapText()
utf8CharBoundary()
setWordWrap()
createHeader()
getMailMIME()
getSentMIMEMessage()
createBody()
headerLine()
textLine()
addAttachment()
getAttachments()
encodeString()
encodeHeader()
hasMultiBytes()
has8bitChars()
base64EncodeWrapMB()
encodeQP()
encodeQ()
addStringAttachment()
addEmbeddedImage()
addStringEmbeddedImage()
inlineImageExists()
attachmentExists()
alternativeExists()
clearQueuedAddresses()
clearAddresses()
clearCCs()
clearBCCs()
clearReplyTos()
clearAllRecipients()
clearAttachments()
clearCustomHeaders()
rfcDate()
isValidHost()
isError()
addCustomHeader()
getCustomHeaders()
msgHTML()
html2text()
_mime_types()
filenameToType()
mb_pathinfo()
set()
secureHeader()
normalizeBreaks()
stripTrailingWSP()
getLE()
sign()
DKIM_QP()
DKIM_Sign()
DKIM_HeaderC()
DKIM_BodyC()
DKIM_Add()
hasLineLongerThanMax()
quotedString()
getToAddresses()
getCcAddresses()
getBccAddresses()
getReplyToAddresses()
getAllRecipientAddresses()
getOAuth()
setOAuth()
$Priority
$CharSet
$ContentType
$Encoding
$ErrorInfo
$From
$FromName
$Sender
$Subject
$Body
$AltBody
$Ical
$WordWrap
$Mailer
$Sendmail
$UseSendmailOptions
$ConfirmReadingTo
$Hostname
$MessageID
$MessageDate
$Host
$Port
$Helo
$SMTPSecure
$SMTPAutoTLS
$SMTPAuth
$SMTPOptions
$Username
$Password
$AuthType
$Timeout
$dsn
$SMTPDebug
$Debugoutput
$SMTPKeepAlive
$SingleTo
$do_verp
$AllowEmpty
$DKIM_selector
$DKIM_identity
$DKIM_passphrase
$DKIM_domain
$DKIM_copyHeaderFields
$DKIM_extraHeaders
$DKIM_private
$DKIM_private_string
$action_function
$XMailer
$validator
CHARSET_ASCII
CHARSET_ISO88591
CHARSET_UTF8
CONTENT_TYPE_PLAINTEXT
CONTENT_TYPE_TEXT_CALENDAR
CONTENT_TYPE_TEXT_HTML
CONTENT_TYPE_MULTIPART_ALTERNATIVE
CONTENT_TYPE_MULTIPART_MIXED
CONTENT_TYPE_MULTIPART_RELATED
ENCODING_7BIT
ENCODING_8BIT
ENCODING_BASE64
ENCODING_BINARY
ENCODING_QUOTED_PRINTABLE
ENCRYPTION_STARTTLS
ENCRYPTION_SMTPS
ICAL_METHOD_REQUEST
ICAL_METHOD_PUBLISH
ICAL_METHOD_REPLY
ICAL_METHOD_ADD
ICAL_METHOD_CANCEL
ICAL_METHOD_REFRESH
ICAL_METHOD_COUNTER
ICAL_METHOD_DECLINECOUNTER
VERSION
STOP_MESSAGE
STOP_CONTINUE
STOP_CRITICAL
CRLF
FWS
MAIL_MAX_LINE_LENGTH
MAX_LINE_LENGTH
STD_LINE_LENGTH
edebug()
addOrEnqueueAnAddress()
addAnAddress()
sendmailSend()
isShellSafe()
isPermittedPath()
fileIsAccessible()
mailSend()
smtpSend()
generateId()
getBoundary()
endBoundary()
setMessageType()
attachAll()
encodeFile()
validateEncoding()
cidExists()
setError()
serverHostname()
lang()
setLE()
doCallback()
$IcalMethods
$MIMEBody
$MIMEHeader
$mailHeader
$oauth
$SingleToArray
$smtp
$to
$cc
$bcc
$ReplyTo
$all_recipients
$RecipientsQueue
$ReplyToQueue
$attachment
$CustomHeader
$lastMessageID
$message_type
$boundary
$language
$error_count
$sign_cert_file
$sign_key_file
$sign_extracerts_file
$sign_key_pass
$exceptions
$uniqueid
$LE
N/A
mailPassthru()
getSmtpErrorMessage()
No private properties found
N/A

Constants

CHARSET_ASCII

CHARSET_ASCII = 'us-ascii'

CHARSET_ISO88591

CHARSET_ISO88591 = 'iso-8859-1'

CHARSET_UTF8

CHARSET_UTF8 = 'utf-8'

CONTENT_TYPE_PLAINTEXT

CONTENT_TYPE_PLAINTEXT = 'text/plain'

CONTENT_TYPE_TEXT_CALENDAR

CONTENT_TYPE_TEXT_CALENDAR = 'text/calendar'

CONTENT_TYPE_TEXT_HTML

CONTENT_TYPE_TEXT_HTML = 'text/html'

CONTENT_TYPE_MULTIPART_ALTERNATIVE

CONTENT_TYPE_MULTIPART_ALTERNATIVE = 'multipart/alternative'

CONTENT_TYPE_MULTIPART_MIXED

CONTENT_TYPE_MULTIPART_MIXED = 'multipart/mixed'

ENCODING_7BIT

ENCODING_7BIT = '7bit'

ENCODING_8BIT

ENCODING_8BIT = '8bit'

ENCODING_BASE64

ENCODING_BASE64 = 'base64'

ENCODING_BINARY

ENCODING_BINARY = 'binary'

ENCODING_QUOTED_PRINTABLE

ENCODING_QUOTED_PRINTABLE = 'quoted-printable'

ENCRYPTION_STARTTLS

ENCRYPTION_STARTTLS = 'tls'

ENCRYPTION_SMTPS

ENCRYPTION_SMTPS = 'ssl'

ICAL_METHOD_REQUEST

ICAL_METHOD_REQUEST = 'REQUEST'

ICAL_METHOD_PUBLISH

ICAL_METHOD_PUBLISH = 'PUBLISH'

ICAL_METHOD_REPLY

ICAL_METHOD_REPLY = 'REPLY'

ICAL_METHOD_ADD

ICAL_METHOD_ADD = 'ADD'

ICAL_METHOD_CANCEL

ICAL_METHOD_CANCEL = 'CANCEL'

ICAL_METHOD_REFRESH

ICAL_METHOD_REFRESH = 'REFRESH'

ICAL_METHOD_COUNTER

ICAL_METHOD_COUNTER = 'COUNTER'

ICAL_METHOD_DECLINECOUNTER

ICAL_METHOD_DECLINECOUNTER = 'DECLINECOUNTER'

VERSION

VERSION = '6.6.4' : string

The PHPMailer Version number.

STOP_MESSAGE

STOP_MESSAGE = 0 : int

Error severity: message only, continue processing.

STOP_CONTINUE

STOP_CONTINUE = 1 : int

Error severity: message, likely ok to continue processing.

STOP_CRITICAL

STOP_CRITICAL = 2 : int

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

CRLF

CRLF = "\r\n"

The SMTP standard CRLF line break.

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

FWS

FWS = ' '

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

MAIL_MAX_LINE_LENGTH

MAIL_MAX_LINE_LENGTH = 63 : int

The maximum line length supported by mail().

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

MAX_LINE_LENGTH

MAX_LINE_LENGTH = 998 : int

The maximum line length allowed by RFC 2822 section 2.1.1.

STD_LINE_LENGTH

STD_LINE_LENGTH = 76 : int

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

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.

Properties

$Priority

$Priority : int|null

Email priority.

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

Type

int|null

$CharSet

$CharSet : string

The character set of the message.

Type

string

$ContentType

$ContentType : string

The MIME Content-type of the message.

Type

string

$Encoding

$Encoding : string

The message encoding.

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

Type

string

$ErrorInfo

$ErrorInfo : string

Holds the most recent mailer error message.

Type

string

$From

$From : string

The From email address for the message.

Type

string

$FromName

$FromName : string

The From name of the message.

Type

string

$Sender

$Sender : string

The envelope sender of the message.

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.

Type

string

$Subject

$Subject : string

The Subject of the message.

Type

string

$Body

$Body : string

An HTML or plain text message body.

If HTML then call isHTML(true).

Type

string

$AltBody

$AltBody : string

The plain-text message body.

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.

Type

string

$Ical

$Ical : string

An iCal message part body.

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

Type

string

$WordWrap

$WordWrap : int

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

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

Type

int

$Mailer

$Mailer : string

Which method to use to send mail.

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

Type

string

$Sendmail

$Sendmail : string

The path to the sendmail program.

Type

string

$UseSendmailOptions

$UseSendmailOptions : bool

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

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

Type

bool

$ConfirmReadingTo

$ConfirmReadingTo : string

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

Type

string

$Hostname

$Hostname : string

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

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

Type

string

$MessageID

$MessageID : string

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

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.

Type

string

$MessageDate

$MessageDate : string

The message Date to be used in the Date header.

If empty, the current date will be added.

Type

string

$Host

$Host : string

SMTP hosts.

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.

Type

string

$Port

$Port : int

The default SMTP server port.

Type

int

$Helo

$Helo : string

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

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

Type

string

$SMTPSecure

$SMTPSecure : string

What kind of encryption to use on the SMTP connection.

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

Type

string

$SMTPAutoTLS

$SMTPAutoTLS : bool

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

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

Type

bool

$SMTPAuth

$SMTPAuth : bool

Whether to use SMTP authentication.

Uses the Username and Password properties.

Type

bool

$SMTPOptions

$SMTPOptions : array

Options array passed to stream_context_create when connecting via SMTP.

Type

array

$Username

$Username : string

SMTP username.

Type

string

$Password

$Password : string

SMTP password.

Type

string

$AuthType

$AuthType : string

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

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

Type

string

$Timeout

$Timeout : int

The SMTP server timeout in seconds.

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

Type

int

$dsn

$dsn

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

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.

$Debugoutput

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

How to handle debug output.

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;

Type

LoggerInterface

$SMTPKeepAlive

$SMTPKeepAlive : bool

Whether to keep the SMTP connection open after each message.

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.

Type

bool

$SingleTo

$SingleTo : bool

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

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

Type

bool

$do_verp

$do_verp : bool

Whether to generate VERP addresses on send.

Only applicable when sending via SMTP.

Type

bool

$AllowEmpty

$AllowEmpty : bool

Whether to allow sending messages with an empty body.

Type

bool

$DKIM_selector

$DKIM_selector : string

DKIM selector.

Type

string

$DKIM_identity

$DKIM_identity : string

DKIM Identity.

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

Type

string

$DKIM_passphrase

$DKIM_passphrase : string

DKIM passphrase.

Used if your key is encrypted.

Type

string

$DKIM_domain

$DKIM_domain : string

DKIM signing domain name.

Type

string

$DKIM_copyHeaderFields

$DKIM_copyHeaderFields : bool

DKIM Copy header field values for diagnostic use.

Type

bool

$DKIM_extraHeaders

$DKIM_extraHeaders : array

DKIM Extra signing headers.

Type

array

$DKIM_private

$DKIM_private : string

DKIM private key file path.

Type

string

$DKIM_private_string

$DKIM_private_string : string

DKIM private key string.

If set, takes precedence over $DKIM_private.

Type

string

$action_function

$action_function : string

Callback Action function name.

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

Type

string

$XMailer

$XMailer : string|null

What to put in the X-Mailer header.

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

Type

string|null

$validator

$validator : string|callable

Which validator to use by default when validating email addresses.

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.

Type

string|callable

$IcalMethods

$IcalMethods : string[]

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

Type

string[]

$MIMEBody

$MIMEBody : string

The complete compiled MIME message body.

Type

string

$MIMEHeader

$MIMEHeader : string

The complete compiled MIME message headers.

Type

string

$mailHeader

$mailHeader : string

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

Type

string

$oauth

$oauth : \PHPMailer\PHPMailer\OAuthTokenProvider

An implementation of the PHPMailer OAuthTokenProvider interface.

Type

OAuthTokenProvider

$SingleToArray

$SingleToArray : array

Storage for addresses when SingleTo is enabled.

Type

array

$smtp

$smtp : \PHPMailer\PHPMailer\SMTP

An instance of the SMTP sender class.

Type

SMTP

$to

$to : array

The array of 'to' names and addresses.

Type

array

$cc

$cc : array

The array of 'cc' names and addresses.

Type

array

$bcc

$bcc : array

The array of 'bcc' names and addresses.

Type

array

$ReplyTo

$ReplyTo : array

The array of reply-to names and addresses.

Type

array

$all_recipients

$all_recipients : array

An array of all kinds of addresses.

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

Type

array

$RecipientsQueue

$RecipientsQueue : array

An array of names and addresses queued for validation.

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.

Type

array

$ReplyToQueue

$ReplyToQueue : array

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

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

Type

array

$attachment

$attachment : array

The array of attachments.

Type

array

$CustomHeader

$CustomHeader : array

The array of custom headers.

Type

array

$lastMessageID

$lastMessageID : string

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

Type

string

$message_type

$message_type : string

The message's MIME type.

Type

string

$boundary

$boundary : array

The array of MIME boundary strings.

Type

array

$language

$language : array

The array of available text strings for the current language.

Type

array

$error_count

$error_count : int

The number of errors encountered.

Type

int

$sign_cert_file

$sign_cert_file : string

The S/MIME certificate file path.

Type

string

$sign_key_file

$sign_key_file : string

The S/MIME key file path.

Type

string

$sign_extracerts_file

$sign_extracerts_file : string

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

Type

string

$sign_key_pass

$sign_key_pass : string

The S/MIME password for the key.

Used only if the key is encrypted.

Type

string

$exceptions

$exceptions : bool

Whether to throw exceptions for errors.

Type

bool

$uniqueid

$uniqueid : string

Unique ID used for message ID and boundaries.

Type

string

$LE

$LE : string

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

Type

string

Methods

__construct()

__construct(bool  $exceptions = null) : mixed

Constructor.

Parameters

bool $exceptions

Should we throw external exceptions?

Returns

mixed —

__destruct()

__destruct() : mixed

Destructor.

Returns

mixed —

isHTML()

isHTML(bool  $isHtml = true) : mixed

Sets message type to HTML or plain.

Parameters

bool $isHtml

True for HTML mode

Returns

mixed —

isSMTP()

isSMTP() : mixed

Send messages using SMTP.

Returns

mixed —

isMail()

isMail() : mixed

Send messages using PHP's mail() function.

Returns

mixed —

isSendmail()

isSendmail() : mixed

Send messages using $Sendmail.

Returns

mixed —

isQmail()

isQmail() : mixed

Send messages using qmail.

Returns

mixed —

addAddress()

addAddress(string  $address, string  $name = '') : bool

Add a "To" address.

Parameters

string $address

The email address to send to

string $name

Throws

\PHPMailer\PHPMailer\Exception

Returns

bool —

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

addCC()

addCC(string  $address, string  $name = '') : bool

Add a "CC" address.

Parameters

string $address

The email address to send to

string $name

Throws

\PHPMailer\PHPMailer\Exception

Returns

bool —

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

addBCC()

addBCC(string  $address, string  $name = '') : bool

Add a "BCC" address.

Parameters

string $address

The email address to send to

string $name

Throws

\PHPMailer\PHPMailer\Exception

Returns

bool —

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

addReplyTo()

addReplyTo(string  $address, string  $name = '') : bool

Add a "Reply-To" address.

Parameters

string $address

The email address to reply to

string $name

Throws

\PHPMailer\PHPMailer\Exception

Returns

bool —

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

parseAddresses()

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

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.

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

Parameters

string $addrstr

The address list string

bool $useimap

Whether to use the IMAP extension to parse the list

string $charset

The charset to use when decoding the address list string.

Returns

array —

setFrom()

setFrom(string  $address, string  $name = '', bool  $auto = true) : bool

Set the From and FromName properties.

Parameters

string $address
string $name
bool $auto

Whether to also set the Sender address, defaults to true

Throws

\PHPMailer\PHPMailer\Exception

Returns

bool —

getLastMessageID()

getLastMessageID() : string

Return the Message-ID header of the last email.

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.

Returns

string —

validateAddress()

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

Check that a string looks like an email address.

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.

Parameters

string $address

The email address to check

string|callable $patternselect

Which pattern to use

Returns

bool —

idnSupported()

idnSupported() : bool

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

Returns

bool —

true if required functions for IDN support are present

punyencodeAddress()

punyencodeAddress(string  $address) : string

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

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).

Parameters

string $address

The email address to convert

Returns

string —

The encoded address in ASCII form

send()

send() : bool

Create a message and send it.

Uses the sending method specified by $Mailer.

Throws

\PHPMailer\PHPMailer\Exception

Returns

bool —

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

preSend()

preSend() : bool

Prepare a message for sending.

Throws

\PHPMailer\PHPMailer\Exception

Returns

bool —

postSend()

postSend() : bool

Actually send a message via the selected mechanism.

Throws

\PHPMailer\PHPMailer\Exception

Returns

bool —

getSMTPInstance()

getSMTPInstance() : \PHPMailer\PHPMailer\SMTP

Get an instance to use for SMTP operations.

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

Returns

\PHPMailer\PHPMailer\SMTP —

setSMTPInstance()

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

Provide an instance to use for SMTP operations.

Parameters

\PHPMailer\PHPMailer\SMTP $smtp

Returns

\PHPMailer\PHPMailer\SMTP —

smtpConnect()

smtpConnect(array  $options = null) : bool

Initiate a connection to an SMTP server.

Returns false if the operation failed.

Parameters

array $options

An array of options compatible with stream_context_create()

Throws

\PHPMailer\PHPMailer\Exception

Returns

bool —

smtpClose()

smtpClose() : mixed

Close the active SMTP session if one exists.

Returns

mixed —

setLanguage()

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

Set the language for error messages.

The default language is English.

Parameters

string $langcode

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.

string $lang_path

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

Returns

bool —

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

getTranslations()

getTranslations() : array

Get the array of strings for the current language.

Returns

array —

addrAppend()

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

Create recipient headers.

Parameters

string $type
array $addr

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']]

Returns

string —

addrFormat()

addrFormat(array  $addr) : string

Format an address for use in a message header.

Parameters

array $addr

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

Returns

string —

wrapText()

wrapText(string  $message, int  $length, bool  $qp_mode = false) : string

Word-wrap message.

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

Parameters

string $message

The message to wrap

int $length

The line length to wrap to

bool $qp_mode

Whether to run in Quoted-Printable mode

Returns

string —

utf8CharBoundary()

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

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

Original written by Colin Brown.

Parameters

string $encodedText

utf-8 QP text

int $maxLength

Find the last character boundary prior to this length

Returns

int —

setWordWrap()

setWordWrap() : mixed

Apply word wrapping to the message body.

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.

Returns

mixed —

createHeader()

createHeader() : string

Assemble message headers.

Returns

string —

The assembled headers

getMailMIME()

getMailMIME() : string

Get the message MIME type headers.

Returns

string —

getSentMIMEMessage()

getSentMIMEMessage() : string

Returns the whole MIME message.

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

Returns

string —

createBody()

createBody() : string

Assemble the message body.

Returns an empty string on failure.

Throws

\PHPMailer\PHPMailer\Exception

Returns

string —

The assembled message body

headerLine()

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

Format a header line.

Parameters

string $name
string|int $value

Returns

string —

textLine()

textLine(string  $value) : string

Return a formatted mail line.

Parameters

string $value

Returns

string —

addAttachment()

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

Add an attachment from a path on the filesystem.

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.

Parameters

string $path

Path to the attachment

string $name

Overrides the attachment name

string $encoding

File encoding (see $Encoding)

string $type

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

string $disposition

Disposition to use

Throws

\PHPMailer\PHPMailer\Exception

Returns

bool —

getAttachments()

getAttachments() : array

Return the array of attachments.

Returns

array —

encodeString()

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

Encode a string in requested format.

Returns an empty string on failure.

Parameters

string $str

The text to encode

string $encoding

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

Throws

\PHPMailer\PHPMailer\Exception

Returns

string —

encodeHeader()

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

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

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

Parameters

string $str

The header value to encode

string $position

What context the string will be used in

Returns

string —

hasMultiBytes()

hasMultiBytes(string  $str) : bool

Check if a string contains multi-byte characters.

Parameters

string $str

multi-byte text to wrap encode

Returns

bool —

has8bitChars()

has8bitChars(string  $text) : bool

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

Parameters

string $text

Returns

bool —

base64EncodeWrapMB()

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

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

Adapted from a function by paravoid.

Parameters

string $str

multi-byte text to wrap encode

string $linebreak

string to use as linefeed/end-of-line

Returns

string —

encodeQP()

encodeQP(string  $string) : string

Encode a string in quoted-printable format.

According to RFC2045 section 6.7.

Parameters

string $string

The text to encode

Returns

string —

encodeQ()

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

Encode a string using Q encoding.

Parameters

string $str

the text to encode

string $position

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

Returns

string —

addStringAttachment()

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

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

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

Parameters

string $string

String attachment data

string $filename

Name of the attachment

string $encoding

File encoding (see $Encoding)

string $type

File extension (MIME) type

string $disposition

Disposition to use

Throws

\PHPMailer\PHPMailer\Exception

Returns

bool —

True on successfully adding an attachment

addEmbeddedImage()

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

Add an embedded (inline) attachment from a file.

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!

Parameters

string $path

Path to the attachment

string $cid

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

string $name

Overrides the attachment filename

string $encoding

File encoding (see $Encoding) defaults to base64

string $type

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

string $disposition

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

Throws

\PHPMailer\PHPMailer\Exception

Returns

bool —

True on successfully adding an attachment

addStringEmbeddedImage()

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

Add an embedded stringified attachment.

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.

Parameters

string $string

The attachment binary data

string $cid

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

string $name

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.

string $encoding

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

string $type

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

string $disposition

Disposition to use

Throws

\PHPMailer\PHPMailer\Exception

Returns

bool —

True on successfully adding an attachment

inlineImageExists()

inlineImageExists() : bool

Check if an inline attachment is present.

Returns

bool —

attachmentExists()

attachmentExists() : bool

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

Returns

bool —

alternativeExists()

alternativeExists() : bool

Check if this message has an alternative body set.

Returns

bool —

clearQueuedAddresses()

clearQueuedAddresses(string  $kind) : mixed

Clear queued addresses of given kind.

Parameters

string $kind

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

Returns

mixed —

clearAddresses()

clearAddresses() : mixed

Clear all To recipients.

Returns

mixed —

clearCCs()

clearCCs() : mixed

Clear all CC recipients.

Returns

mixed —

clearBCCs()

clearBCCs() : mixed

Clear all BCC recipients.

Returns

mixed —

clearReplyTos()

clearReplyTos() : mixed

Clear all ReplyTo recipients.

Returns

mixed —

clearAllRecipients()

clearAllRecipients() : mixed

Clear all recipient types.

Returns

mixed —

clearAttachments()

clearAttachments() : mixed

Clear all filesystem, string, and binary attachments.

Returns

mixed —

clearCustomHeaders()

clearCustomHeaders() : mixed

Clear all custom headers.

Returns

mixed —

rfcDate()

rfcDate() : string

Return an RFC 822 formatted date.

Returns

string —

isValidHost()

isValidHost(string  $host) : bool

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

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

Parameters

string $host

The host name or IP address to check

Returns

bool —

isError()

isError() : bool

Check if an error occurred.

Returns

bool —

True if an error did occur

addCustomHeader()

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

Add a custom header.

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

Parameters

string $name

Custom header name

string|null $value

Header value

Throws

\PHPMailer\PHPMailer\Exception

Returns

mixed —

getCustomHeaders()

getCustomHeaders() : array

Returns all custom headers.

Returns

array —

msgHTML()

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

Create a message body from an HTML 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.

Parameters

string $message

HTML message string

string $basedir

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

bool|callable $advanced

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

Throws

\PHPMailer\PHPMailer\Exception

Returns

string —

The transformed message body

html2text()

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

Convert an HTML string into plain text.

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();
});

Parameters

string $html

The HTML text to convert

bool|callable $advanced

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

Returns

string —

_mime_types()

_mime_types(string  $ext = '') : string

Get the MIME type for a file extension.

Parameters

string $ext

File extension

Returns

string —

MIME type of file

filenameToType()

filenameToType(string  $filename) : string

Map a file name to a MIME type.

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

Parameters

string $filename

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

Returns

string —

mb_pathinfo()

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

Multi-byte-safe pathinfo replacement.

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

Parameters

string $path

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

int|string $options

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

Returns

string|array —

set()

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

Set or reset instance properties.

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;.

Parameters

string $name

The property name to set

mixed $value

The value to set the property to

Returns

bool —

secureHeader()

secureHeader(string  $str) : string

Strip newlines to prevent header injection.

Parameters

string $str

Returns

string —

normalizeBreaks()

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

Normalize line breaks in a string.

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.

Parameters

string $text
string $breaktype

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

Returns

string —

stripTrailingWSP()

stripTrailingWSP(string  $text) : string

Remove trailing breaks from a string.

Parameters

string $text

Returns

string —

The text to remove breaks from

getLE()

getLE() : string

Return the current line break format string.

Returns

string —

sign()

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

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

Parameters

string $cert_filename
string $key_filename
string $key_pass

Password for private key

string $extracerts_filename

Optional path to chain certificate

Returns

mixed —

DKIM_QP()

DKIM_QP(string  $txt) : string

Quoted-Printable-encode a DKIM header.

Parameters

string $txt

Returns

string —

DKIM_Sign()

DKIM_Sign(string  $signHeader) : string

Generate a DKIM signature.

Parameters

string $signHeader

Throws

\PHPMailer\PHPMailer\Exception

Returns

string —

The DKIM signature value

DKIM_HeaderC()

DKIM_HeaderC(string  $signHeader) : string

Generate a DKIM canonicalization header.

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

Parameters

string $signHeader

Header

Returns

string —

DKIM_BodyC()

DKIM_BodyC(string  $body) : string

Generate a DKIM canonicalization body.

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

Parameters

string $body

Message Body

Returns

string —

DKIM_Add()

DKIM_Add(string  $headers_line, string  $subject, string  $body) : string

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

Parameters

string $headers_line

Header lines

string $subject

Subject

string $body

Body

Throws

\PHPMailer\PHPMailer\Exception

Returns

string —

hasLineLongerThanMax()

hasLineLongerThanMax(string  $str) : bool

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

Parameters

string $str

Returns

bool —

quotedString()

quotedString(string  $str) : string

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

Parameters

string $str

Returns

string —

getToAddresses()

getToAddresses() : array

Allows for public read access to 'to' property.

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

Returns

array —

getCcAddresses()

getCcAddresses() : array

Allows for public read access to 'cc' property.

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

Returns

array —

getBccAddresses()

getBccAddresses() : array

Allows for public read access to 'bcc' property.

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

Returns

array —

getReplyToAddresses()

getReplyToAddresses() : array

Allows for public read access to 'ReplyTo' property.

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

Returns

array —

getAllRecipientAddresses()

getAllRecipientAddresses() : array

Allows for public read access to 'all_recipients' property.

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

Returns

array —

getOAuth()

getOAuth() : \PHPMailer\PHPMailer\OAuthTokenProvider

Get the OAuthTokenProvider instance.

Returns

\PHPMailer\PHPMailer\OAuthTokenProvider —

setOAuth()

setOAuth(\PHPMailer\PHPMailer\OAuthTokenProvider  $oauth) : mixed

Set an OAuthTokenProvider instance.

Parameters

\PHPMailer\PHPMailer\OAuthTokenProvider $oauth

Returns

mixed —

edebug()

edebug(string  $str) : mixed

Output debugging info via a user-defined method.

Only generates output if debug output is enabled.

Parameters

string $str

Returns

mixed —

addOrEnqueueAnAddress()

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

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().

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

Parameters

string $kind

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

string $address

The email address

string $name

An optional username associated with the address

Throws

\PHPMailer\PHPMailer\Exception

Returns

bool —

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

addAnAddress()

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

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

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

Parameters

string $kind

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

string $address

The email address to send, resp. to reply to

string $name

Throws

\PHPMailer\PHPMailer\Exception

Returns

bool —

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

sendmailSend()

sendmailSend(string  $header, string  $body) : bool

Send mail using the $Sendmail program.

Parameters

string $header

The message headers

string $body

The message body

Throws

\PHPMailer\PHPMailer\Exception

Returns

bool —

isShellSafe()

isShellSafe(string  $string) : bool

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

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

Parameters

string $string

The string to be validated

Returns

bool —

isPermittedPath()

isPermittedPath(string  $path) : bool

Check whether a file path is of a permitted type.

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

Parameters

string $path

A relative or absolute path to a file

Returns

bool —

fileIsAccessible()

fileIsAccessible(string  $path) : bool

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

Parameters

string $path

A relative or absolute path to a file

Returns

bool —

mailSend()

mailSend(string  $header, string  $body) : bool

Send mail using the PHP mail() function.

Parameters

string $header

The message headers

string $body

The message body

Throws

\PHPMailer\PHPMailer\Exception

Returns

bool —

smtpSend()

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

Send mail via SMTP.

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

Parameters

string $header

The message headers

string $body

The message body

Throws

\PHPMailer\PHPMailer\Exception

Returns

bool —

generateId()

generateId() : string

Create a unique ID to use for boundaries.

Returns

string —

getBoundary()

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

Return the start of a message boundary.

Parameters

string $boundary
string $charSet
string $contentType
string $encoding

Returns

string —

endBoundary()

endBoundary(string  $boundary) : string

Return the end of a message boundary.

Parameters

string $boundary

Returns

string —

setMessageType()

setMessageType() : mixed

Set the message type.

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

Returns

mixed —

attachAll()

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

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

Returns an empty string on failure.

Parameters

string $disposition_type
string $boundary

Throws

\PHPMailer\PHPMailer\Exception

Returns

string —

encodeFile()

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

Encode a file attachment in requested format.

Returns an empty string on failure.

Parameters

string $path

The full path to the file

string $encoding

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

Returns

string —

validateEncoding()

validateEncoding(string  $encoding) : bool

Validate encodings.

Parameters

string $encoding

Returns

bool —

cidExists()

cidExists(string  $cid) : bool

Check if an embedded attachment is present with this cid.

Parameters

string $cid

Returns

bool —

setError()

setError(string  $msg) : mixed

Add an error message to the error container.

Parameters

string $msg

Returns

mixed —

serverHostname()

serverHostname() : string

Get the server hostname.

Returns 'localhost.localdomain' if unknown.

Returns

string —

lang()

lang(string  $key) : string

Get an error message in the current language.

Parameters

string $key

Returns

string —

setLE()

setLE(string  $le) : mixed

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

Parameters

string $le

Returns

mixed —

doCallback()

doCallback(bool  $isSent, array  $to, array  $cc, array  $bcc, string  $subject, string  $body, string  $from, array  $extra) : mixed

Perform a callback.

Parameters

bool $isSent
array $to
array $cc
array $bcc
string $subject
string $body
string $from
array $extra

Returns

mixed —

mailPassthru()

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

Call mail() in a safe_mode-aware fashion.

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).

Parameters

string $to

To

string $subject

Subject

string $body

Message Body

string $header

Additional Header(s)

string|null $params

Params

Returns

bool —

getSmtpErrorMessage()

getSmtpErrorMessage(string  $base_key) : string

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

Parameters

string $base_key

Returns

string —