Отправить e-mail с вложением отправлен input
у Меня есть сайт PHP с формой контакта, которая позволяет загружать файл. Этот файл должен быть отправлен, вложенный в сообщение электронной почты вместе с остальными данными. Ваш e-mail не будет получено, хотя пришло сообщение с подтверждением доставки. Также не в папку "спам". Уже испытал компании e-mail, GMail и Hotmail.
Есть файл PHP с HTML, который затем делает post (jQuery, AJAX), чтобы файл PHP сценарий. В этом файле сценария является то, что он сделал, отправка почты. Я знаю, что функция отправки выполняется, потому что я получаю сообщение от нее.
Код HTML:
<div id="inscreverOportunidade" class="hideform inscreverOportunidade" style="display:none;">
<div id="boxForm">
<div class="formProf">
<div style="width:100%;" class="big-new-close" onclick="javascript:showForm('');"><span>X</span></div>
<div class="to">
<div class="small-text"> NOME*</div>
<input type="text" required="true" class="input-text" value="" id="NomeO" name="NomeO" onfocus="this.value = '';" onblur="if (this.value == '') {
this.value = '';
}">
</div>
<div class="to email">
<div class="small-text"> EMAIL*</div>
<input type="email" required="true" class="text" value="" id="EmailO" name="EmailO" onfocus="this.value = '';" onblur="if (this.value == '') {
this.value = '';
}" >
</div>
<div class="to">
<div class="small-text"> CONTACTO*</div>
<input type="text" required="true" class="input-text" value="" id="ContactoO" name="ContactoO" onfocus="this.value = '';" onblur="if (this.value == '') {
this.value = '';
}">
</div>
<div class="to email">
<div class="small-text"> LOCALIDADE*</div>
<input type="text" required="true" class="text" value="" id="LocalidadeO" name="LocalidadeO" onfocus="this.value = '';" onblur="if (this.value == '') {
this.value = '';
}" >
</div>
<div class="to">
<div class="small-text"> PROFISSÃO*</div>
<input type="text" required="true" class="input-text" value="" id="ProfissaoO" name="ProfissaoO" onfocus="this.value = '';" onblur="if (this.value == '') {
this.value = '';
}">
</div>
<div class="to email">
<div class="small-text"> ANEXAR CURRÍCULO*</div>
<input type="file" required="true" name="CV" id="CV" class="text" accept=".docx, .doc, .pdf">
</div>
<div class="info">Os campos marcados com * são de preenchimento obrigatório</div>
<div class="submit-curriculo"><input type="submit" name="submit" id="submit" value="Inscrever" onclick="javascript:sendFormRegO();
return false;"></div>
</div> <!--end formProf-->
</div> <!--end boxForm-->
</div>
<script>
function sendFormRegO()
{
var proceed = true;
//simple validation at client's end
//loop through each field and we simply change border color to red for invalid fields
$("#inscreverOportunidade input[required=true]").each(function(){
$(this).css('border-color','');
if(!$.trim($(this).val())){ //if this field is empty
$(this).css('border-color','red'); //change border color to red
proceed = false; //set do not proceed flag
}
//check invalid email
var email_reg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
if($(this).attr("type")=="email" && !email_reg.test($.trim($(this).val()))){
$(this).css('border-color','red'); //change border color to red
proceed = false; //set do not proceed flag
}
});
if(proceed) //everything looks good! proceed...
{
//data to be sent to server
var m_data = new FormData();
m_data.append( 'nome', $('input[name=NomeO]').val());
m_data.append( 'email', $('input[name=EmailO]').val());
m_data.append( 'contacto', $('input[name=ContactoO]').val());
m_data.append( 'localidade', $('input[name=LocalidadeO]').val());
m_data.append( 'profissao', $('input[name=ProfissaoO]').val());
m_data.append( 'file', $('input[name=CV]')[0].files[0]);
//instead of $.post() we are using $.ajax()
//that's because $.ajax() has more options and flexibly.
$.ajax({
url: '<?php echo Yii::app()->createUrl('site/inscricaooportunidade'); ?>',
data: m_data,
processData: false,
contentType: false,
type: 'POST',
dataType:'json',
success: function(response){
alert(response.text);
//load json data from server and output message
if(response.type == 'error'){ //load json data from server and output message
output = '<div class="error">'+response.text+'</div>';
}else{
output = '<div class="success">'+response.text+'</div>';
}
}
});
}
}
</script>
PHP Код:
public function actionInscricaoOportunidade()
{
//if(Yii::app()->request->isAjaxRequest)
if($_POST)
{
//check if its an ajax request, exit if not
if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
$output = json_encode(array( //create JSON data
'type'=>'error',
'text' => 'Sorry Request must be Ajax POST'
));
die($output); //exit script outputting json data
}
//Sanitize input data using PHP filter_var().
$nome = filter_var($_POST['nome'], FILTER_SANITIZE_STRING);
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
$contacto = filter_var($_POST['contacto'], FILTER_SANITIZE_STRING);
$localidade = filter_var($_POST['localidade'], FILTER_SANITIZE_STRING);
$profissao = filter_var($_POST['profissao'], FILTER_SANITIZE_STRING);
//$message->addTo(Yii::app()->params['adminEmail']);
$to_email = "[email protected]";
$from_email = $email;
//email body
$message_body = "Foi efectuada uma nova inscrição na oportunidade XXX com os seguintes dados:<br /><br />";
$message_body .= "<strong>NOME:</strong> " . $nome . "<br />";
$message_body .= "<strong>EMAIL:</strong> " . $email . "<br />";
$message_body .= "<strong>CONTACTO:</strong> " . $contacto . "<br />";
$message_body .= "<strong>Localidade:</strong> " . $localidade . "<br />";
$message_body .= "<strong>Profissão:</strong> " . $profissao . "<br /><br />";
$message_body .= "<strong>O Curriculo do candidato encontra-se anexado a este email</strong>";
### Attachment Preparation ###
$file_attached = false;
if(isset($_FILES['file'])) //check uploaded file
{
//get file details we need
$file_tmp_name = $_FILES['file']['tmp_name'];
$file_name = $_FILES['file']['name'];
$file_size = $_FILES['file']['size'];
$file_type = $_FILES['file']['type'];
$file_error = $_FILES['file']['error'];
//exit script and output error if we encounter any
if($file_error>0)
{
$mymsg = array(
1=>"The uploaded file exceeds the upload_max_filesize directive in php.ini",
2=>"The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form",
3=>"The uploaded file was only partially uploaded",
4=>"No file was uploaded",
6=>"Missing a temporary folder" );
$output = json_encode(array('type'=>'error', 'text' => $mymsg[$file_error]));
die($output);
}
//read from the uploaded file & base64_encode content for the mail
$handle = fopen($file_tmp_name, "r");
$content = fread($handle, $file_size);
fclose($handle);
$encoded_content = chunk_split(base64_encode($content));
//now we know we have the file for attachment, set $file_attached to true
$file_attached = true;
}
if($file_attached) //continue if we have the file
{
# Mail headers should work with most clients
$headers = "MIME-Version: 1.0\r\n";
$headers = "X-Mailer: PHP/" . phpversion()."\r\n";
$headers .= "From: ".$from_email."\r\n";
$headers .= "Subject: Confirmação de Inscricao - Oportunidade\r\n";
$headers .= "Reply-To: " .$email. "\r\n";
$headers .= "Content-Type: multipart/mixed; boundary=".md5('boundary1')."\r\n\r\n";
$headers .= "--".md5('boundary1')."\r\n";
$headers .= "Content-Type: multipart/alternative; boundary=".md5('boundary2')."\r\n\r\n";
$headers .= "--".md5('boundary2')."\r\n";
$headers .= "Content-Type: text/plain; charset=utf-8\r\n\r\n";
$headers .= $message_body."\r\n\r\n";
$headers .= "--".md5('boundary2')."--\r\n";
$headers .= "--".md5('boundary1')."\r\n";
$headers .= "Content-Type: ".$file_type."; ";
$headers .= "name=\"".$file_name."\"\r\n";
$headers .= "Content-Transfer-Encoding:base64\r\n";
$headers .= "Content-Disposition:attachment; ";
$headers .= "filename=\"".$file_name."\"\r\n";
$headers .= "X-Attachment-Id:".rand(1000,9000)."\r\n\r\n";
$headers .= $encoded_content."\r\n";
$headers .= "--".md5('boundary1')."--";
}else{
//proceed with PHP email.
$headers = 'From: '.$nome.'' . "\r\n" .
'Reply-To: '.$email.'' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
}
$send_mail = mail($to_email, "Confirmação de Inscricao - Oportunidade", $message_body, $headers);
if(!$send_mail)
{
//If mail couldn't be sent output error. Check your PHP email configuration (if it ever happens)
$output = json_encode(array('type'=>'error', 'text' => 'Could not send mail! Please check your PHP mail configuration.'));
die($output);
}else{
$output = json_encode(array('type'=>'message', 'text' => 'Hi '.$nome .' Thank you for your email'));
die($output);
}
}
}
2 answers
... Здесь код, который я сделал во Франции... 14 лет притягивает (время...). Работать. У меня нет времени переводить, но и очень легко понять:
<?php
/*=============================================*/
/* ENVOI D'UN MAIL AVEC FICHIER JOINT EVENTUEL */
/* PL Lamballais - PARX 2000 */
/*=============================================*/
/* Fichier: php.inc/send_mail.php3 */
/* Version 1.00 du 18/02/2000 */
/* Version 1.01 du 04/03/2000 Ajout de charset et du */
/* type MIME de l'envoi sans fichier joint pour avoir les accents. */
/* $dbug => 0 = normal, 1 débug, donc on affiche les infos. */
/* $mail_dest => adresse email destination */
/* $mail_exp => adresse email expéditeur */
/* $mail_subject => sujet du message */
/* $mail_msg => corps du message */
/* $file_path => chemin complet du fichier à joindre (rien si pas de fichier) */
/* $file_name => nom du fichier devant apparaitre comme nom de pièce jointe */
/* $file_type => type MIME du fichier à joindre */
function send_mail($dbug, $mail_dest,$mail_exp,$mail_subject,$mail_msg,$file_path,$file_name,$file_type)
{
if ($dbug == 1)
{
echo "Routine send_mail(). Mode débuggage<br />\n";
echo "mail_dest = ".$mail_dest."<br />\n";
echo "mail_exp = ".$mail_exp."<br />\n";
echo "mail_subject = ".$mail_subject."<br />\n";
echo "mail_msg = ".$mail_msg."<br />\n";
echo "file_path = ".$file_path."<br />\n";
echo "file_name = ".$file_name."<br />\n";
echo "file_type = ".$file_type."<br />\n";
}
/* Définition des éléments d'en-tête du mail */
/* Ce sont les éléments par défaut donc sans fichier joint */
$boundary="-----------------kjbsdf9873987348735";
$MIME = "MIME-Version: 1.0\nContent-Type:text/plain;\n\tcharset=\"utf-8\"\nContent-Transfer-Encoding: 8bit\n\n";
$startMsg = "";
$ending = "";
/*= Préparation du début du message =*/
$hold_message = $mail_msg."\n\n";
/*= S'il y a un fichier, on l'encode =*/
if ($file_path != "")
{
/* Vérifions l'existence de ce fichier */
$tst = file_exists($file_path);
if ($tst == false)
{
if ($dbug == 1)
{
echo "== Erreur: le fichier ".$file_path." est introuvable.<br />\n";
}
}
else
{
$fp=fopen($file_path,"r"); /* Ouvre le fichier */
$in = fread( $fp, filesize( $file_path)); /* Lecture des données */
fclose( $fp ); /* Fermeture fichier */
$data_encode= chunk_split(base64_encode($in)); /* Encodage */
if ($dbug == 1)
{
$taille = strlen($data_encode);
echo "Taille des données Base64 : ".$taille."<br />\n";
}
/* Puisqu'il y a un fichier joint, on change le début et la fin du message */
$startMsg = "\n--$boundary\nContent-Type:text/plain;\n\tcharset=\"utf-8\"\nContent-Transfer-Encoding: 8bit\n\n";
$ending = "\n--$boundary--";
$MIME = "MIME-Version: 1.0\nContent-Type:multipart/mixed;\n\tboundary=\"$boundary\"\n\nThis is a multi-part message in MIME format.\n\n";
$hold_message = $hold_message."\n--$boundary\nContent-Type:".$file_type.";\n\tname=\"$file_name\"\nContent-Transfer-Encoding: base64\nContent-Disposition: inline;\n\tfilename=\"$file_name\"\n\n$data_encode";
}
}
/*= La préparation est terminée, nous envoyons le message =*/
$hold_from = "From: ".$mail_exp."\n".$MIME."\n";
$hold_message = $startMsg.$hold_message.$ending;
mail( $mail_dest, $mail_subject, $hold_message, $hold_from );
}
?>
Этот код и используется здесь: http://www.ansb-brasil.org/trab_conosco/trab_conosco.php
Вам нужно конвертировать файл в файл mime type SwiftMailer Swift_Mime_MimeEntity
type. CUploadedFile::getInstanceByName('fileupload')
returns CUploadedFile класса, что SwiftMailer не знает, как справиться. Подробнее Swift attachments here.
Я не проверял это, но вам нужно будет сделать что-то вроде этого:
$uploadedFile = CUploadedFile::getInstanceByName('fileupload'); // get the CUploadedFile
$uploadedFileName = $uploadedFile->tempName; // will be something like 'myfile.jpg'
$swiftAttachment = Swift_Attachment::fromPath($uploadedFileName); // create a Swift Attachment
$this->email->attach($swiftAttachment); // now attach the correct type
Удачи