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. What is PHPMailer It is the PHP class which allows you send emails. Very simple I think. Let me tell […]

  /  April 12

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 = '<p>Thanks for buying my plugin (the plugin archive is attached to this email).</p><p>If you have any questions, <a href="https://rudrastyh.com/contacts">contact me</a>.</p>';
$phpmailer->AddAttachment(getcwd() . '/plugins/' . $plugin_name . '.zip', $plugin_name . '.zip'); // add the attachment
$phpmailer->Send(); // the last thing - send the email

Only the best of WordPress

Subscribe to this weekly newsletter to receive the latest blog posts by email.I respect your privacy. Your email is safe with me.

Leave your question or feedback

phpjsHTMLCSSSQLCode
Please, enter a comment
Please, enter a name
Incorrect email