26 Feb 2018

How to Send Email with Attachments via PHPMailer in WordPress


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