Mangcoding

icon chat
Mulida Asti - Thursday, 6 March 2025 - 4 months ago

How to Send Emails with Attachments Using PHPMailer in WordPress

single image
Photo by Simona Sergi on Unsplash

We received a question from one of our website visitors regarding how to send emails with attachments using PHPMailer in WordPress.

Hopefully, this article shared by Mangcoding can help you save time! Feel free to leave a comment below or ask questions via Mangcoding’s social media.

PHP Mailer Mangoding

Link Mangcoding

What is PHPMailer in WordPress?

PHPMailer is a PHP class that allows you to send emails. This step is quite simple in our opinion. And here, Mangcoding will explain how to add attachments and provide some examples.

So first — if you want to attach something to an email, use the following pattern:

$phpmailer->AddAttachment('path to file', 'file name with extension');

Full Code Example:

global $phpmailer; // define the global variable
if ( !is_object( $phpmailer ) || !is_a( $phpmailer, 'PHPMailer' ) ) { // check if $phpmailer object of class PHPMailer exists
    // if not - include the necessary files
    require_once ABSPATH . WPINC . '/class-phpmailer.php';
    require_once ABSPATH . WPINC . '/class-smtp.php';
    $phpmailer = new PHPMailer( true );
}
$phpmailer->ClearAttachments(); // clear all previous attachments if exist
$phpmailer->ClearCustomHeaders(); // the same about mail headers
$phpmailer->ClearReplyTos();
$phpmailer->From = '[email protected]';
$phpmailer->FromName = 'Misha Rudrastyh';
$phpmailer->Subject = 'Plugin: ' . $plugin_display_name; // subject
$phpmailer->SingleTo = true;
$phpmailer->ContentType = 'text/html'; // Content Type
$phpmailer->IsHTML( true );
$phpmailer->CharSet = 'utf-8';
$phpmailer->ClearAllRecipients();
$phpmailer->AddAddress( $_POST['email'] ); // the recipient's address
$phpmailer->Body = 'Thanks for buying my plugin (the plugin archive is attached to this email).If you have any questions, contact me.';
$phpmailer->AddAttachment(getcwd() . '/plugins/' . $plugin_name . '.zip', $plugin_name . '.zip'); // add the attachment
$phpmailer->Send(); // the last thing - send the email

Please try practicing what Mangcoding has explained in the article above. Hopefully, this article can be useful and help you solve your issue, especially in sending Email with attachments using PHPMailer in WordPress.

That’s the article Mangcoding wanted to share. Hopefully, it’s helpful and provides you with new insights. If you have constructive feedback or suggestions, feel free to leave a comment or reach out via email and Mangcoding’s social media.

Source: Rudrastyh.com

Link Copied to Clipboard