How to Send Email with Attachments via PHPMailer in WP
Table of Contents
Email attachments
I have a lot of questions from my website visitors about functionality. One of these questions is about email attachments
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 = '[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