powered by simpleCommunicator - 2.0.61     © 2026 Programmizd 02
Целевая тема:
Создать новую тему:
Автор:
Закрыть
Цитировать
Форумы / PHP, Perl, Python [игнор отключен] [закрыт для гостей] / Как добавить заголовки from в письмо с аттачем?
8 сообщений из 8, страница 1 из 1
Как добавить заголовки from в письмо с аттачем?
    #37792996
Фотография Stasonix
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
masterdelphi

Код: php
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
// Вспомогательная функция для отправки почтового сообщения с вложением 
  function send_mail($to, $thm, $html, $path) 
  { 
  
 $fp = fopen($path,"r"); 
    if (!$fp)
 {
 print "Файл $path не может быть прочитан"; 
        exit(); 
    } 

    $file = fread($fp, filesize($path)); 
    fclose($fp); 



    $boundary = "--".md5(uniqid(time())); // генерируем разделитель 

 $headers  = "MIME-Version: 1.0\n"; 
    $headers .="Content-Type: multipart/mixed; boundary=\"$boundary\"\n";

    
 $multipart = "--$boundary\n"; 

    //$kod = 'koi8-r'; // или $kod = 'windows-1251'; 
 $kod = 'utf8';
 $multipart .= "Content-Type: text/html; charset=$kod\n"; 
 $multipart .= "Content-Transfer-Encoding: Quot-Printed\n\n"; 
    $multipart .= "$html\n\n"; 


    $message_part = "--$boundary\n"; 
 $message_part .= "Content-Type: application/octet-stream\n"; 
    $message_part .= "Content-Transfer-Encoding: base64\n"; 
    $message_part .= "Content-Disposition: attachment; filename = \"".basename($path)."\"\n\n"; 
    $message_part .= chunk_split(base64_encode($file))."\n"; 

    $multipart .= $message_part."--$boundary--\n"; 

    if(!mail($to, $thm, $multipart, $headers)) 
    {
 echo "К сожалению, письмо не отправлено"; 
 exit(); 
    }


 }



Нужно добавить From $user_email и Return-path: $user_email, но ни в какую у меня не выходит. Как это правильно сделать?
...
Рейтинг: 0 / 0
Как добавить заголовки from в письмо с аттачем?
    #37793224
vkle
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Stasonixу меня не выходит.Покажите, как пытались сделать
...
Рейтинг: 0 / 0
Как добавить заголовки from в письмо с аттачем?
    #37793542
Няша ррр
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Мой старый класс работает, но я бы его переписал

Код: php
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
65.
66.
67.
68.
69.
70.
71.
72.
73.
74.
75.
76.
77.
78.
79.
80.
81.
82.
83.
84.
85.
86.
87.
88.
89.
90.
91.
92.
93.
94.
95.
96.
97.
98.
99.
100.
101.
102.
103.
104.
105.
106.
107.
108.
109.
110.
111.
112.
113.
114.
115.
116.
117.
118.
119.
120.
121.
122.
123.
124.
125.
126.
127.
128.
129.
130.
131.
132.
133.
134.
135.
136.
137.
138.
139.
140.
141.
142.
143.
144.
145.
146.
147.
148.
149.
150.
151.
152.
153.
154.
155.
156.
157.
158.
159.
160.
161.
162.
163.
164.
165.
166.
167.
168.
<?php

/**
 * Класс для отправки почты. Для работы должна быть разрешена функция mail.
 * 
 * Примеры:
 * 
 * // письмо с аттачем
 * $mail = new Mail;
 * $mail->charset("windows-1251"); // по умолчанию utf-8
 * $mail->to("recipient@example.com", "Имя получателя"); // имя можно опустить
 * $mail->subject("Заголовок");
 * $mail->body("Сообщение");
 * $filename = "path/to/file.rar"; 
 * $mail->attach(file_get_contents($filename), basename($filename), "application/x-rar-compressed");
 * $mail->attach("пусто", "Текстовый документ.txt", "text/plain"); // с распознанием русских символов в имени приложения проблем не возникнет
 * $mail->send();
 * 
 * // несколько адресатов
 * $mail = new Mail;
 * $mail->to(array("recipient1@example.com" => "Имя первого получателя", "recipient2@example.com" => "Имя второго получателя"));
 * $mail->subject("Заголовок");
 * $mail->body("Сообщение");
 * $mail->send();
 * 
 * // рассылаем копии письма
 * $mail = new Mail;
 * $mail->subject("Заголовок");
 * $mail->body("Сообщение");
 * $emails = array("recipient1@example.com", "recipient2@example.com");
 * foreach ($emails as $email) {
 *     $copy = copy $mail;
 *     $copy->to($email, "Лично");
 *     $copy->send();
 * }
 * 
 * Поля From, Reply-To, Cc и Bcc можно задать с помощью одноименных методов 
 * (в случае с Reply-To - reply) аналогичных по синтаксису методу to, существует
 * возможность добавления произвольного заголовков с помощью метода add.
 * 
 */
class Mail {
    private $to,
            $subject, 
            $body,
            $charset = "utf-8",
            $headers  = "MIME-Version: 1.0\r\n",
            $attachments = array(),
            $type = "plain";
    
    public function charset($charset) {
        $this->charset = $charset;
    }
    
    private function encode($string) {
        return chunk_split(base64_encode($string));
    }
    
    public function b($string) {
        return "=?{$this->charset}?B?" . base64_encode($string) . "?=";
    }
    
    private function recipient($email, $name) {
        return $name ? $this->b($name) . " <{$email}>" : $email;
    }
    
    private function recipients($emails) {
        $temp = array();
        foreach ($emails as $key => $val) {
            if (!is_int($key)) {
                $email = $key;
                $name  = $val;
            }  
            else {
                $email = $val;
                $name  = false;
            }
            $temp[] = $this->recipient($email, $name);
        }
        return implode(", ", $temp);
    }
    
    private function addr($params) {
        if (is_array($params[0])) {
            return $this->recipients($params[0]);
        }
        else {
            $params[1] = @$params[1];
            return $this->recipient($params[0], $params[1]);
        }
    }
    
    /**
     * Mail()->to($email, $name = false);
     * Mail()->to($emails);
     *
     **/
    public function to() {
        $this->to = $this->addr(func_get_args());   
    }
    
    public function add($key, $value) {
        $this->headers .= "{$key}: {$value}\r\n";
    }
    
    public function cc() {
        $this->add("Cc", $this->addr(func_get_args()));
    }
    
    public function bcc() {
        $this->add("Bcc", $this->addr(func_get_args()));
    } 

    public function from() {
        $this->add("From", $this->addr(func_get_args()));
    }
    
    public function reply() {
        $this->add("Reply-To", $this->addr(func_get_args()));
    }
    
    public function subject($subject) {
        $this->subject = $this->b($subject);
    }
    
    public function body($body) {
        $this->body = $this->encode($body);
    } 
    
    public function attach($data, $name, $type = "application/octet-stream") {
        $this->attachments[] = array(           
            "data" => $this->encode($data),
            "name" => $this->b($name),
            "type" => $type
        );
    }
    
    public function html() {
        $this->type = "html";
    }
    
    public function plain() {
        $this->type = "plain";
    }
    
    public function send() {
        if (!empty($this->attachments)) {
            $boundary = uniqid();
            $this->headers .= "Content-Type: multipart/mixed; boundary=\"{$boundary}\"";
            $this->body = "--{$boundary}\r\n" .
                          "Content-Type: text/{$this->type}; charset=\"{$this->charset}\"\r\n" .   
                          "Content-Transfer-Encoding: base64\r\n\r\n{$this->body}";             
            foreach ($this->attachments as $attachment) {
                $this->body .= "\r\n--{$boundary}\r\nContent-Type: {$attachment["type"]}; name=\"{$attachment["name"]}\"\r\n" . 
                               "Content-Transfer-Encoding: base64\r\n" .
                               "Content-disposition: attachment; file=\"{$attachment["name"]}\"\r\n\r\n{$attachment["data"]}";
            }
            $this->body .= "--{$boundary}--";
        }   
        else {
            $this->headers .= "Content-Type: text/{$this->type}; charset=\"{$this->charset}\"\r\n" .   
                              "Content-Transfer-Encoding: base64";
        }
        return mail($this->to, $this->subject, $this->body, $this->headers);
    }
}

?>
...
Рейтинг: 0 / 0
Как добавить заголовки from в письмо с аттачем?
    #37793553
Няша ррр
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Я его токо на жымыле и маиле проверял формат письма правильный прочитать можно
...
Рейтинг: 0 / 0
Как добавить заголовки from в письмо с аттачем?
    #37793610
SharuPoNemnogu
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Код: php
1.
mail("кому", "тема", "сообщение", "From: email@host.ru\nContent-Type: text/plain; charset=windows-1251\nContent-Transfer-Encoding: 8bit", "-femail@host.ru");



-femail@host.ru это и будет Return-path
...
Рейтинг: 0 / 0
Как добавить заголовки from в письмо с аттачем?
    #37793611
SharuPoNemnogu
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
SharuPoNemnogu, т.е. пишешь -f и мыло, а то там непонятно)
...
Рейтинг: 0 / 0
Как добавить заголовки from в письмо с аттачем?
    #38048345
vpupkin97
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
SharuPoNemnogu
Код: php
1.
mail("кому", "тема", "сообщение", "From: email@host.ru\nContent-Type: text/plain; charset=windows-1251\nContent-Transfer-Encoding: 8bit", "-femail@host.ru");



-femail@host.ru это и будет Return-path

Тема и сообщение не будут корректно отображаться. Для не-латиницы надо использовать вот такую конструкцию:
=?<Кодировка>?B?<текст в base64>?=
...
Рейтинг: 0 / 0
Как добавить заголовки from в письмо с аттачем?
    #38048686
Фотография ScareCrow
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
возьмите наконец swiftmailer
...
Рейтинг: 0 / 0
8 сообщений из 8, страница 1 из 1
Форумы / PHP, Perl, Python [игнор отключен] [закрыт для гостей] / Как добавить заголовки from в письмо с аттачем?
Найденые пользователи ...
Разблокировать пользователей ...
Читали форум (0):
Пользователи онлайн (0):
x
x
Закрыть


Просмотр
0 / 0
Close
Debug Console [Select Text]