It is possible to add an attachment using the standard ‘wp_mail’ function, however you would need to hook into the phpmailer_init
action to do so.
Because this will require calling another function where you don’t have any context, you may need to register the action function anonymously with the use ( $attachments )
statement, store the attachment content as a global variable or property, or place the attachment generation code into the new function.
I can see that OP’s code seems to be in the context of a class method, so I’ll try to create an example which should be compatible / consistent.
// Previous Code...
// Use this action to generate and/or attach files.
add_filter( 'phpmailer_init', array( $this, 'add_attachments' ) );
// And/or store the attachments as a property.
$this->set_attachments( $attachments );
$sent = wp_mail( $to, $subject, $message, $this->get_headers() );
// Log errors etc...
if ( ! $sent ) {
//...
$this->log_error( $error_message );
}
}
/**
* Add attachments to the email.
*
* This method must be public in order to work as an action.
* @param PHPMailer\PHPMailer\PHPMailer $phpmailer
*/
public function add_attachments( $phpmailer ) {
// Remove filter to prevent attaching the files to subsequent emails.
remove_action( 'phpmailer_init', array( $this, 'add_attachments' ) );
// Get or generate the attachments somehow.
foreach ( $this->get_attachments() as $filename, $file_contents ) {
try {
$phpmailer->addStringAttachment( $file_contents, $filename );
} catch( \Exception $ex ) {
// An exception may thrown which would prevent the remaining files from being attached, so we'll catch these and log the errors.
// This email may be sent without attachments. Do not try/catch if you don't want the email to be sent without all the attachments.
$this->log_error( $ex->getMessage() );
}
}
}
/**
* Abstraction for the logging code to make it reusable.
* @param string $log_message
*/
protected function log_error( $log_message ) {
if ( ! $this->log_errors ) {
return;
}
// Log errors here.
}