PHPMailer Methods Reference

0

A reference for the PHPMailer 6.x methods you will actually call, grouped by what they do, with signatures and the behaviour worth knowing. The complete API is in the source at github.com/PHPMailer/PHPMailer; this page covers what comes up in practice.

Constructor

public function __construct(?bool $exceptions = null)

Pass true to make failures throw PHPMailer\PHPMailer\Exception instead of returning false. Do this. The default leaves you to check every return value by hand, and the day you forget is the day email stops working silently.

$mail = new PHPMailer(true);

Choosing the transport

Method Effect
isSMTP(): void Send over SMTP. Requires Host, and usually SMTPAuth, Username, Password, SMTPSecure, Port.
isMail(): void Use PHP’s mail(). The default, so calling it is only needed to switch back.
isSendmail(): void Pipe to the sendmail binary named in $Sendmail.
isQmail(): void Use qmail’s sendmail wrapper.

Addresses

setFrom(string $address, string $name = '', bool $auto = true): bool
addAddress(string $address, string $name = ''): bool
addCC(string $address, string $name = ''): bool
addBCC(string $address, string $name = ''): bool
addReplyTo(string $address, string $name = ''): bool

All return true on success, or false if the address is invalid or already present — so a duplicate addAddress() is harmless rather than producing two copies.

The third argument to setFrom() controls whether Reply-To is set automatically to the same address. Pass false when you have already called addReplyTo() and want to keep it.

Clearing addresses

Method Clears
clearAddresses(): void To recipients
clearCCs(): void Cc
clearBCCs(): void Bcc
clearReplyTos(): void Reply-To
clearAllRecipients(): void To, Cc and Bcc together

These matter whenever you reuse an instance in a loop. clearAddresses() in a finally block is the difference between ten personal emails and one email to ten people who now have each other’s addresses.

Reading back what is set

getToAddresses(): array
getCcAddresses(): array
getBccAddresses(): array
getReplyToAddresses(): array
getAllRecipientAddresses(): array

Each returns arrays of [address, name] pairs. Useful in tests and for logging what a message actually went to.

Content

isHTML(bool $isHtml = true): void

Switches ContentType between text/html and text/plain. It does not populate AltBody — you set that yourself, and you should.

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

The useful shortcut. Given an HTML string it sets Body, generates AltBody by converting the HTML to text, and — if $basedir is given — finds local images referenced in src attributes and embeds them automatically:

$mail->msgHTML(file_get_contents('templates/receipt.html'), __DIR__ . '/templates');

Pass true as the third argument to use a better HTML-to-text converter, which requires html2text to be installed.

html2text(string $html, $advanced = false): string

The conversion on its own, if you want to inspect or post-process the result before assigning it.

Attachments and inline images

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

Attaches a file from disk. $name overrides the filename the recipient sees. Leave $type empty and PHPMailer derives the MIME type from the extension. Returns false — or throws, with exceptions on — if the file is unreadable.

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

Same thing from a variable, for content generated at runtime. No temporary file needed:

$mail->addStringAttachment($pdfBytes, 'invoice.pdf', PHPMailer::ENCODING_BASE64, 'application/pdf');
addEmbeddedImage(string $path, string $cid, string $name = '', ...): bool
addStringEmbeddedImage(string $string, string $cid, string $name = '', ...): bool

$cid is the content ID you then reference from the HTML body:

$mail->addEmbeddedImage('/path/logo.png', 'logo');
$mail->Body = '<img src="cid:logo" alt="Logo">';
Method Returns
clearAttachments(): void
getAttachments(): array The attachment list
attachmentExists(): bool Whether any attachment is set
inlineImageExists(): bool Whether any embedded image is set

Sending

send(): bool

Builds and sends the message. Returns true, or throws with exceptions enabled. Internally it is preSend() followed by postSend().

preSend(): bool
postSend(): bool
getSentMIMEMessage(): string

Splitting the two is how you inspect a message without delivering it — invaluable in tests:

$mail->preSend();
$raw = $mail->getSentMIMEMessage(); // full MIME source, nothing sent

Connection control

smtpConnect(?array $options = null): bool
smtpClose(): void
getSMTPInstance(): SMTP
setSMTPInstance(SMTP $smtp): SMTP

With SMTPKeepAlive = true, call smtpClose() when the batch is finished — otherwise the connection stays open until the script ends. setSMTPInstance() lets you inject a mock in tests.

Custom headers

addCustomHeader(string $name, ?string $value = null): bool
getCustomHeaders(): array
clearCustomHeaders(): void
$mail->addCustomHeader('X-Message-Type', 'order-confirmation');
$mail->addCustomHeader('List-Unsubscribe', '<https://example.com/unsub?t=abc>');

List-Unsubscribe is worth adding to anything resembling a newsletter — the major providers now expect it, and its absence counts against you.

Validation and utilities

public static function validateAddress(string $address, $patternselect = null, ...): bool

Static, so callable without an instance. Syntax only — it cannot tell you whether the mailbox exists:

if (!PHPMailer::validateAddress($email)) { /* reject */ }
public static function parseAddresses(string $addrstr, bool $useimap = true, ...): array
public static function normalizeBreaks(string $text, ?string $breaktype = null): string
public static function filenameToType(string $filename): string
public static function mimeTypes(string $ext = ''): string
public static function rfcDate(): string

parseAddresses() turns "Name <a@b.com>, c@d.com" into a structured array, which is what you want when importing a list from a form field.

DKIM signing

DKIM_Add(string $headers_line, string $subject, string $body): string
DKIM_Sign(string $signHeader): string
DKIM_BodyC(string $body): string
DKIM_HeaderC(string $signHeader): string
DKIM_QP(string $txt): string

You rarely call these directly. Set the DKIM_domain, DKIM_selector and DKIM_private properties and send() signs automatically. They are public mainly so subclasses can override the canonicalisation.

Localisation

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

Translates PHPMailer’s own error messages. It has no effect on your message content:

$mail->setLanguage('fr');

Errors and OAuth

isError(): bool
setOAuth(OAuthTokenProvider $oauth): void
getOAuth(): OAuthTokenProvider

isError() is the check you need when exceptions are off. The details are in the $ErrorInfo property, which carries the server’s own response — always more informative than the exception message. setOAuth() supplies an XOAUTH2 token provider for Gmail or Microsoft 365; see the XOAUTH2 example.

See also

sunshyne works on technical SEO and email deliverability for French-speaking markets, and runs the digital consultancy at sunshyne.ch. Most of that work sits where the two overlap. On the SEO side: redirect mapping, crawl and indexation diagnostics, server log analysis, and recovering domains whose history has damaged them. On the email side: the authentication layer — SPF, DKIM and DMARC — sender reputation, and the reasons a technically valid message still gets filtered. These PHPMailer pages exist because the second half of that work keeps returning to the same questions: which transport to use, why an SMTP connection fails, and why a correctly formed message is rejected anyway. The examples here are the ones worth keeping after answering those questions more than once.

Comments are closed.