How to Send Email with Attachments via PHPMailer in WP

I have a lot of questions from my website visitors about «My Plugins» functionality. One of these questions is about email attachments — because when you buy my plugin, you will receive it via email.

plugin file will be attached to email

What is PHPMailer

It is the PHP class which allows you send emails. Very simple I think. Let me tell you about attachments and show some examples.

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

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

Full 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 = 'misha@rudrastyh.com';
$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
Misha Rudrastyh

Misha Rudrastyh

I develop websites since 2008, so it is total of 13 years of experience, oh my gosh. Most of all I love love love to create websites with WordPress and Gutenberg, some ideas and thoughts I share throughout my blog.

Need some developer help? Contact me