отправить письмо с приложением с помощью php - PullRequest
5 голосов
/ 08 декабря 2011

Я использовал этот код для отправки электронного письма с вложением с использованием php, но во вложении есть ошибка, так как я получаю электронное письмо и в содержимом появляется вложение. прежде чем я использую тот же код, и он работал успешно. почему ???

<?php
// sending email with attachments

    function sendEmail($to,$from,$file,$ext){

      $to = "admin@fuwant.com";
     $from = "noor@fuwant.com";
      $subject = "Translation Request";

  $random_hash = md5(date('r', time()));

  $headers = "From: sahar@fuwant.com\r\nReply-To: admin@fuwant.com";

  $headers .= "\r\nContent-Type: multipart/mixed; boundary=\"PHP-mixed-".$random_hash."\"";

  $attachment = chunk_split(base64_encode(file_get_contents("Test.doc")));

  $output = "
        --PHP-mixed-$random_hash;
        Content-Type: multipart/alternative; boundary='PHP-alt-$random_hash'
        --PHP-alt-$random_hash
        Content-Type: text/plain; charset='iso-8859-1'
        Content-Transfer-Encoding: 7bit

        Hello World!
        This is the simple text version of the email message.

        --PHP-alt-$random_hash
        Content-Type: text/html; charset='iso-8859-1'
        Content-Transfer-Encoding: 7bit

        <h2>Hello World!</h2>
        <p>This is the <b>HTML</b> version of the email message.</p>

        --PHP-alt-$random_hash--

        --PHP-mixed-$random_hash
        Content-Type: application/doc; name=Test.doc
        Content-Transfer-Encoding: base64
        Content-Disposition: attachment

        $attachment
        --PHP-mixed-$random_hash--";
      $send =  @mail($to, $subject, $output, $headers);
  return $send;
  }
?>

пожалуйста, помогите.

Ответы [ 5 ]

6 голосов
/ 08 декабря 2011

по какой причине не используется phpmailer ?пример для вложения:

function mandaMail ($nombredest, $maildest, $asunto, $cuerpo) {
require_once("mailer/class.phpmailer.php");
$mail = new PHPMailer(true);
$mail->IsSMTP();

try {
    $mail->Host = "xxxx"; $mail->Port = 25; // smtp server
    $mail->SMTPAuth = true;
    $mail->Username = "xxxx"; // smtp username
    $mail->Password = "xxxx"; // smtp pass
    $mail->AddReplyTo("xxxx", "xxxx"); // email & name
    $mail->SetFrom("xxxx", "xxxx"); // similar to up value

    $mail->AddAddress($maildest, $nombredest);
    $mail->Subject = $asunto;
    $mail->MsgHTML(file_get_contents($cuerpo));

    $mail->AddAttachment("xxxx", "xxxx"); // attachments directory, attachment name (ie: dir/blah.jpg, blah.jpg)
    $mail->Send();

} catch (phpmailerException $e) { echo $e->errorMessage();
} catch (Exception $e) { echo $e->getMessage(); }
2 голосов
/ 08 декабря 2011

Вы можете сделать это так, как описано в этом учебнике , или использовать один из модулей PEAR , чтобы отправить электронное письмо с вложением способом этого * 1006.* учебник описывает.

Использование PEAR, вероятно, является лучшим вариантом, так как это проще сделать.Единственное предостережение в том, что PEAR доступен не на всех хостах.

0 голосов
/ 01 сентября 2017

Я использую это и (без использования PHPMailer ), надеюсь, это полезно для вас.

<code><form enctype="multipart/form-data" method="POST" action="">
    <label>Your Name <input type="text" name="sender_name" /> </label> <br>
    <label>Your Email <input type="email" name="sender_email" /> </label> <br>
    <label>Subject <input type="text" name="subject" /> </label> <br>
    <label>Message <textarea name="message"></textarea> </label> <br>
    <label>Attachment <input type="file" name="my_file" /></label><br>
    <label><input type="submit" name="button" value="Submit" /></label>
</form>

<?php 
echo "<pre>";print_r($_REQUEST);echo "
"; // прокомментируйте эту строку echo"
";print_r($_FILES);echo "
"; //закомментируйте эту строку, если ($ _ POST && isset ($ _ FILES ['my_file'])) {$ from_email = 'noreply@your_domain.com'; // из почты, это обязательно для некоторых хостов $ receient_email = 'your-emailid @gmail.com '; // электронная почта получателя (в большинстве случаев это ваша личная электронная почта) // Захват данных POST из формы HTML и их очистка, $ sender_name = filter_var ($ _ POST ["sender_name"], FILTER_SANITIZE_STRING); // имя отправителя$ reply_to_email = filter_var ($ _ POST ["sender_email"], FILTER_SANITIZE_STRING); // электронная почта отправителя, используемая в заголовке "reply-to" $ subject = filter_var ($ _ POST ["subject"], FILTER_SANITIZE_STRING); // получить тему из HTMLform // $ message = filter_var ($ _ POST ["message"], FILTER_SANITIZE_STRING); // message $ message = "Имя:". $ sender_name. "\ nMessage:". $ _ POST ["message"]; // сообщение// Получить данные загруженного файла $ file_tmp_name = $ _FILES ['my_file'] ['tmp_name']; $ file_name = $ _FILES [ 'my_file'] [ 'имя'];$ file_size = $ _FILES ['my_file'] ['size'];$ file_type = $ _FILES ['my_file'] ['type'];$ file_error = $ _FILES ['my_file'] ['error'];if ($ file_error> 0) {die ('Ошибка загрузки или файлы не загружены');} // чтение из загруженного файла и содержимого base64_encode для почты $ handle = fopen ($ file_tmp_name, "r");$ content = fread ($ handle, $ file_size);fclose ($ ручка);$ encoded_content = chunk_split (base64_encode ($ content));$ border = md5 ("sanwebe");// headers $ headers = "MIME-Version: 1.0 \ r \ n";$ headers. = "From:". $ from_email. "\ r \ n";$ headers. = "Reply-To:". $ reply_to_email. ""."\ Г \ п";$ headers. = "Content-Type: multipart / mixed; border = $ border \ r \ n \ r \ n";// текст body $ body = "- $ border \ r \ n";$ body. = "Content-Type: text / plain; charset = ISO-8859-1 \ r \ n";$ body. = "Content-Transfer-Encoding: base64 \ r \ n \ r \ n";$ body. = chunk_split (base64_encode ($ message));// файл вложения $ body. = "- $ border \ r \ n";$ body. = "Content-Type: $ file_type; name =". $ file_name. "\ r \ n";$ body. = "Content-Disposition: attachment; filename =". $ file_name. "\ r \ n";$ body. = "Content-Transfer-Encoding: base64 \ r \ n";$ body. = "X-Attachment-Id:" .rand (1000,99999). "\ r \ n \ r \ n";$ body. = $ encoded_content;$ sentMail = @mail ($ receient_email, $ subject, $ body, $ headers);if ($ sentMail) // выводить сообщения об успехах или неудачах {die ('Спасибо за ваше письмо');} else {die («Не удалось отправить почту!»);}}?>
0 голосов
/ 02 января 2013

Ваш код не будет работать, потому что электронная почта не поддерживает пробелы .

  $output = "
       --PHP-mixed-$random_hash;
       Content-Type: multipart/alternative; boundary='PHP-alt-$random_hash'
       --PHP-alt-$random_hash
       Content-Type: text/plain; charset='iso-8859-1'
       Content-Transfer-Encoding: 7bit

Вы должны использовать без пробелов

 $output = "
 --PHP-mixed-$random_hash;
 Content-Type: multipart/alternative; boundary='PHP-alt-$random_hash'
 --PHP-alt-$random_hash
 Content-Type: text/plain; charset='iso-8859-1'
 Content-Transfer-Encoding: 7bit
0 голосов
/ 08 декабря 2011

Я использую это:

function attachfile($file, $type = "application/octetstream")  {
    if(!($fd = fopen($file, "r"))) {
      $this->errstr = "Error opening $file for reading.";
      return 0;
    }
    $_buf = fread($fd, filesize($file));
    fclose($fd);

    $fname = $file;
    for($x = strlen($file); $x > 0; $x--)
      if($file[$x] == "/")
        $fname = substr($file, $x, strlen($file) - $x);

    // Convert to base64 becuase mail attachments are not binary safe.
    $_buf = chunk_split(base64_encode($_buf));

    $this->attachments[$file] = "\n--" . $this->boundary . "\n";
    $this->attachments[$file] .= "Content-Type: $type; name=\"$fname\"\n";
    $this->attachments[$file] .= "Content-Transfer-Encoding: base64\n";
    $this->attachments[$file] .= "Content-Disposition: attachment; " .
                                     "filename=\"$fname\"\n\n";
    $this->attachments[$file] .= $_buf;

    return 1;
  }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...