I’m in the exact same situation. I have a form where a user can request a discount coupon, so I need to create a coupon (pdf file) on the fly with a unique serial number in it, attach the coupon and send it to the user via email.
I’ve found a working solution, so here it is:
1) I’ve created a form in the backend and setted all required field in MAIL section.
2) In the file attachement field on MAIL I’ve inserted
[coupon]
N.B: it’s not necessary to really add this field to the form, just in the attchment field.
3) I Hooked in cf7 via ‘wpcf7_before_send_mail‘ action
add_action( 'wpcf7_before_send_mail', 'create_unique_coupon_and_send_it' );
function create_unique_coupon_and_send_it( $cf7 ) {
//check if this is the right form
if ($cf7->id==741){
$uploads = wp_upload_dir();
//define some constants
define ('COUPON_UPLOAD_PATH',$uploads['path'].'/coupons');
// ...
// ...
if ($cf7->mail['use_html']==true)
$nl="<br/>";
else
$nl="\n";
//I omitted all the stuff used to create
//the pdf file, you have just to know that
//$pdf_filename contains the filename to attach
//Let'go to the file attachment!
$cf7->uploaded_files = array ( 'coupon' => COUPON_UPLOAD_PATH.'/'.$pdf_filename );
//append some text to the outgoing email
$message=$nl.$nl.'Blah blah blah.....'.$nl;
$message.='So Long, and Thanks for All the Fish!'.$nl;
$cf7->mail_2['body'].=$message;
}
}
Note that:
1) you have to change the form id as needed (or avoid the check if you have only one form on your site)
2) CF7 unlink (delete) the attached file after mail is sent for security reasons, so make a copy of it if you have to send the same file over and over.
3) make sure the key of the item in this associative array
array ( ‘coupon’ => COUPON_UPLOAD_PATH.’/’.$pdf_filename );
matches the name inserted in the form settings, in the attachment file field (see point 2) above the code)
4) If you are using (like me) the “to-db-extension” plugin, remember to add the action with a priority level lower than 10:
add_action( ‘wpcf7_before_send_mail’, ‘create_unique_coupon_and_send_it’, 5 );
to execute your code before the DB plugin gets form data and save them in the db. In the code example above, I can add a field to every record in the db, just altering the $cf7->posted_data array:
//Add coupon file name in the database
$cf7->posted_data['coupon_file']=$pdf_filename;
Hope it can be useful.