Skip to content

Instantly share code, notes, and snippets.

@marcosnakamine
Last active November 18, 2023 06:57
Show Gist options
  • Save marcosnakamine/9443303c340ef30ee3bac0f6d8eac95b to your computer and use it in GitHub Desktop.
Save marcosnakamine/9443303c340ef30ee3bac0f6d8eac95b to your computer and use it in GitHub Desktop.
WordPress - Send mail wp_mail with attachment
<?php
class YS_Mail {
public function YS_Mail() {}
public function enviar( $e ) {
$headers = "From: ".$e['from_name']." <".$e['to_mail']."> \n";
$headers .= "Reply-To:".$e['from_name']." <".$e['from_mail']."> \n";
$headers .= "MIME-Version: 1.0 \n";
$headers .= "Content-type: text/html; charset=utf8 \n";
$headers .= "Return-Path:".$e['to_mail']." \n";
$headers .= "To:".$e['to_mail']." \n";
if ( isset( $e['to_cc'] ) ) {
$headers .= "Cc:".$e['to_cc']." \n";
}
if (isset($e['attachment'])) {
$allowed = array('gif','png' ,'jpg', 'doc', 'docx', 'odt', 'pdf', 'zip', 'rar', '7zip');
$ext = pathinfo($e['attachment']['name'], PATHINFO_EXTENSION);
if(in_array($ext,$allowed) ) {
move_uploaded_file( $e['attachment']['tmp_name'], WP_CONTENT_DIR.'/uploads/'.basename( $e['attachment']['name'] ) );
$anexo = WP_CONTENT_DIR.'/uploads/'.basename( $e['attachment']['name'] );
$return = wp_mail( $e['to_mail'], $e['subject'], $e['message'], $headers, $anexo );
unlink($anexo);
} else {
$return = false;
}
} else {
$return = wp_mail( $e['to_mail'], $e['subject'], $e['message'], $headers );
}
return $return;
}
}
<?php
if (isset($_POST['envia']) && $_POST['envia'] == 'ok') {
require('../../../../wp-blog-header.php');
require('class.ys_mail.php');
$ysmail = new YS_Mail();
$mensagem = array(
'from_name' => 'Name',
'from_mail' => 'client@email.com.br',
'to_name' => 'Name',
'to_mail' => 'email@email.com.br',
'subject' => 'Subject',
'message' => 'Message'
'attachment' => $_FILES['file']
);
$ysmail->enviar($mensagem);
}
?>
<form method="post" enctype="multipart/form-data">
<input type="file" name="arquivo">
<input type="hidden" name="envia" value="ok">
<button>OK</button>
</form>
<?php
if (isset($_POST['envia']) && $_POST['envia'] == 'ok') {
require('../../../../wp-blog-header.php');
require('class.ys_mail.php');
$ysmail = new YS_Mail();
$mensagem = array(
'from_name' => 'Name',
'from_mail' => 'client@email.com.br',
'to_name' => 'Name',
'to_mail' => 'email@email.com.br',
'subject' => 'Subject',
'message' => 'Message'
);
$ysmail->enviar($mensagem);
}
?>
<form method="post" enctype="multipart/form-data">
<input type="hidden" name="envia" value="ok">
<button>OK</button>
</form>
@brainfleck
Copy link

Thank you. This code is working for me.

@Intervik
Copy link

Intervik commented Dec 2, 2021

Thank you, Clean and understandable code works well and correct with routines, unlink uploaded file and so on.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment