php在附件中发送带有html表的电子邮件

时间:2014-05-28 07:36:40

标签: javascript php

我尝试将带有php的表格html发送到我的电子邮件,但我需要将其作为附件发送而不是作为电子邮件正文。我尝试这个解决方案,但没有工作。 有人能帮助我吗?

这是我的功能

<script>
function sendMail(){

    //this is the table I want to send not as email body but as attachmment so I send this string in post with ajax call
    var datatosend = '<table border="1"><tr><th>Month</th><th>Savings</th></tr><tr><td>January</td><td>$100</td></<tr><td>February</td><td>$100</td></tr><tr><td colspan="2">Sum: $180</td></tr></table>'

    //I read the mail insered into the input to send the mail to the right mail
    var mailtosend = $('#sendpage #inputMailToSend').val();


    //I link the php script that recive the data from ajax call post
    var url = 'SendMailAtt.php';


    var ogg = 'Paolo_Carlo_Giovanni_Marco_Luca';

    $.ajax({
      type: "POST",
      url: url,
      data: "corpo=" + datatosend + "&dest=" + mailtosend + "&ogg=" + ogg,
      dataType: "html",
      success: function(msg){

        alert('ok');
      },
      error: function(){

        alert("ko");
      }
    });

这是PHP脚本

<?php   
$fp = fopen('log.txt', 'w');

$destinatario = $_POST['dest'];
$mittente = "miamail@gmail.com";
$oggetto = $_POST['ogg'];
$messaggio = $_POST['corpo'];
$allegato_name = date("d-m-Y").".html";

$headers = "From: " . $mittente . "\r\n";
$headers .= "Reply-To: " . $mittente . "\r\n";
$msg = "";
fwrite($fp, "log1\n");


  $data = $messaggio;
  //base64_encode
  $data = chunk_split(base64_encode($data));

  $semi_rand = md5(time());
  $mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
  fwrite($fp, "log2\n");

  // Aggiungo le intestazioni necessarie per l'allegato

  $headers .= "\nMIME-Version: 1.0\n";
  $headers .= "Content-Type: multipart/mixed;\n";
  $headers .= " boundary=\"{$mime_boundary}\"";

  $msg .= "--{$mime_boundary}\n";

  //text message
  $msg .= "Content-Type: multipart/mixed; charset=\"iso-8859-1\"\n";
  $msg .= "Content-Transfer-Encoding: 7bit\n\n";
  $msg .= $messaggio . "\n\n";

  $msg .= "--{$mime_boundary}\n";

  // add the attachment

  $msg .= "Content-Disposition: attachment;\n";
  $msg .= " filename=\"{$allegato_name}\"\n";
  $msg .= "Content-Transfer-Encoding: base64\n\n";
  $msg .= $data . "\n\n";

  $msg .= "--{$mime_boundary}--\n";


fwrite($fp, "log3\n"); 
$errorMail = "";

// Invio la mail

if ($errorMail = mail($destinatario, $oggetto, $msg, $headers)){
    fwrite($fp, "log IF\n");
    }else{
        fwrite($fp, "log ELSE\n");
        fwrite($fp, "HEADERS: ".$headers."\n");
        fwrite($fp, "MSG: ".$msg."\n");
        fwrite($fp, "OGGETTO: ".$oggetto."\n");
        fwrite($fp, "DESTINATARIO: ".$destinatario."\n");
        fwrite($fp, "ERROR: ".$errorMail ."\n");
}

fwrite($fp, "log4\n");

fclose($fp);
?>

1 个答案:

答案 0 :(得分:0)

注意最终输出,你可能在边界之间没有足够的\ n。