Отправка письма с вложением

    Проблемы с кодировкой при отправке email писем посредством php мы уже разобрали в предыдущей части нашей статьи. Давайте разберёмся с оставшимися вопросами.

    Итак, на повестке дня: использование вложений и вставка изображения в тело письма.

    Наверняка многим на почту приходили красивые письма с вёрсткой и картинками. А отправляя письма собственноручно, приходит некрасивый текст. В данной статье мы научимся отправлять письма с красивой версткой и картинками, что часто бывает необходимо при отправке рассылок.

    Если вы когда-нибудь сталкивались с отправкой таких писем, то, скорее всего у вас часто возникали следующие проблемы:

    • вложенный файл не открывается или открывается неправильно
    • не показывается текст
    • картинку можно скачать, но она не вставляется в тело письма.

    Давайте, попробуем со всем этим разобраться.

    Для отправки писем с вложениями используется специальный формат, который называется multipart. В заголовках (headers) он указывается как Content-type: multipart/mixed; boundary=... При этом тело письма состоит из кусочков (каждый кусочек — это часть письма, текст или вложение), которые разделяются значением boundary. Каждый кусочек имеет свои заголовки (конечно же Content-type, ну и другие).

    Если кусочку ещё и задать Content-ID, то его можно вставлять в HTML (ссылка при этом будет выглядеть как «CID:<значение Content-ID>»).

    Написаный ранее класс для работы с почтой я модифицировал под отправку multipart сообщений:

    1. class TEmail{
    2.   public $from_email;
    3.   public $from_name;
    4.   public $to_email;
    5.   public $to_name;
    6.   public $subject;
    7.   public $data_charset='UTF-8';
    8.   public $send_charset='windows-1251';
    9.   //Части сообщения - текст и т.п.
    10.   private $EOL;
    11.   private $parts=array();
    12.   //Конструктор
    13.   function __construct(){
    14.     $this->EOL=CHR(13).CHR(10);
    15.     }
    16.   //Функция, прикрепляющая файл
    17.   function attachment($content_type,$name,$fn,$content_id=''){
    18.     //Read data from the file...
    19.     $fp=fopen($fn,'rb');
    20.     if(!$fp)return false;
    21.     $str=fread($fp,filesize($fn));
    22.     fclose($fp);
    23.     $msg['attachment']=true;
    24.     $msg['content_type']=$content_type;
    25.     $msg['content_id']=$content_id; //Для вставки в тело письма
    26.     $msg['data']=$str;
    27.     $msg['name']=$name;
    28.     $msg['send_charset']='';
    29.     $msg['transfer_encoding']='base64';
    30.     array_push($this->parts,$msg);
    31.     }
    32.   //Функция, добавляющая тело сообщения
    33.   function body($content_type,$str){
    34.     $msg['attachment']=false;
    35.     $msg['content_type']=$content_type;
    36.     $msg['content_id']='';
    37.     $msg['data']=$str;
    38.     $msg['name']='';
    39.     $msg['send_charset']=$this->send_charset;
    40.     $msg['transfer_encoding']='8bit';//'quoted-printable';
    41.     array_push($this->parts,$msg);
    42.     }
    43.   //Функция для отправки multipart сообщения (с вложениями)
    44.   function send_multipart(){
    45.     $dc=$this->data_charset;
    46.     $sc=$this->send_charset;
    47.     $EOL=$this->EOL;
    48.     $boundary='a'.sha1(uniqid(time()));//любая строка, которой не будет в потоке данных.
    49.     //Encode some fields
    50.     $enc_to=mime_header_encode($this->to_name,$dc,$sc).' <'.$this->to_email.'>';
    51.     $enc_subject=mime_header_encode($this->subject,$dc,$sc);
    52.     if(!empty($this->from_email))
    53.        $enc_from=mime_header_encode($this->from_name, $dc, $sc).' <'.$this->from_email.'>';else
    54.        $enc_from='';
    55.     //Process data...
    56.     $multipart='';
    57.     for($i=0;$i<count($this->parts);$i++){
    58.       $ctype=$this->parts[$i]['content_type'];
    59.       $cname=$this->parts[$i]['name'];
    60.       $ccharset=$this->parts[$i]['send_charset'];
    61.       $ctenc=$this->parts[$i]['transfer_encoding'];
    62.       $cid=$this->parts[$i]['content_id'];
    63.       //Put file into multipart
    64.       $multipart.='--'.$boundary.$EOL;
    65.       $multipart.='Content-Type: '.$ctype.
    66.         (empty($ccharset)?'':'; charset='.$ccharset).
    67.         (empty($cname)?'':'; name='.$cname).$EOL;
    68.       if(!empty($cid))
    69.         $multipart.='Content-ID: <'.$cid.'>'.$EOL;
    70.       $multipart.='Content-Transfer-Encoding: '.$ctenc.$EOL;
    71.       //Different encodings
    72.       if($ctenc=='8bit'){//quoted-printable
    73.         $enc_body=$dc==$ccharset?
    74.           $this->parts[$i]['data']:
    75.           iconv($dc,$ccharset.'//IGNORE',$this->parts[$i]['data']);
    76.         $multipart.=$EOL.$enc_body.$EOL;
    77.         }else
    78.       if($ctenc=='base64'){
    79.         $multipart.=$EOL.chunk_split(base64_encode($this->parts[$i]['data']),76,$EOL).$EOL;
    80.         };
    81.       }
    82.     $multipart.='--'.$boundary.'--'.$EOL;
    83.     //
    84.     $headers='';
    85.     $headers.='Mime-Version: 1.0'.$EOL;
    86.     $headers.='Content-type: multipart/mixed; boundary='.$boundary.$EOL;
    87.     if(!empty($enc_from))
    88.        $headers.='From: '.$enc_from.$EOL;
    89.     //Send email
    90.     return mail($enc_to,$enc_subject,$multipart,$headers);
    91.     }
    92.   //Функция для отправки обычного сообщения
    93.   function send_single(){
    94.     //Get some global variables...
    95.     $dc=$this->data_charset;
    96.     $sc=$this->send_charset;
    97.     $EOL=$this->EOL;
    98.     $body=$this->parts[0]['data'];
    99.     $ctype=$this->parts[0]['content_type'];
    100.     $ccharset=$this->parts[0]['send_charset'];
    101.     //Encode some fields
    102.     $enc_to=mime_header_encode($this->to_name,$dc,$sc).' <'.$this->to_email.'>';
    103.     $enc_subject=mime_header_encode($this->subject,$dc,$sc);
    104.     if(!empty($this->from_email))
    105.        $enc_from=mime_header_encode($this->from_name, $dc, $sc).' <'.$this->from_email.'>';else
    106.        $enc_from='';
    107.     //Encode Body
    108.     $enc_body=$dc==$ccharset?$body:iconv($dc,$ccharset.'//IGNORE',$body);
    109.     //Form headers
    110.     $headers='';
    111.     $headers.='Mime-Version: 1.0'.$EOL;
    112.     $headers.='Content-type: '.$ctype.'; charset='.$ccharset.$EOL;
    113.     if(!empty($enc_from))
    114.        $headers.='From: '.$enc_from.$EOL;
    115.     //Send email
    116.     return mail($enc_to,$enc_subject,$enc_body,$headers);
    117.     }
    118.   function send(){
    119.     if(count($this->parts)==1) return $this->send_single(); else
    120.     if(count($this->parts)>1) return $this->send_multipart(); else
    121.       return false;
    122.     }
    123.   }

    Тут функция send() проверяет количество «кусочков». Если «кусочек» один, то отправляет его как текст. Ведь multipart нам не нужен, если мы отправляем только текст.

    Функции attachment() и body() прикрепляют текст или вложение. Принцип их работы, я думаю, понятен.

    Отправка писем с вложениями не представляет сложности. Тут я прикрепляю картинку и zip-архив:

    1.   require_once(dirname(__FILE__).'/email_api.php');
    2.   echo('Trying to send emails...<br>');
    3.   //HTML email
    4.   echo('Email with attachment - sending...<br>');
    5.   $email=new TEmail;
    6.   $email->from_email='noreply@konservs.com';
    7.   $email->from_name='От "Записок Консерваторов"';
    8.   $email->to_email='*********';
    9.   $email->subject='Тема (ІЇҐЭЄ іїґэє)';
    10.   $email->body('text/html','Письмо в HTML с вложениями.<br>'.
    11.     'Картинка:'.
    12.     '<img src="cid:cid1">'.
    13.     '<h1>Header 1 (Заголовок 1)</h1>'.
    14.     '<h2>Header 2 (Заголовок 2)</h2>'.
    15.     '<h3>Header 3 (Заголовок 3)</h3>'.
    16.     '<h4>Header 4 (Заголовок 4)</h4>'.
    17.     '<h5>Header 5 (Заголовок 5)</h5>'.
    18.     'Тест: ІЇҐЭЄ іїґэє');
    19.   $DS=DIRECTORY_SEPARATOR;
    20.   $email->attachment('image/jpeg','logo.jpg',dirname(__FILE__).$DS.'files'.$DS.'test.jpg','cid1');
    21.   $email->attachment('application/octet-stream','test.zip',dirname(__FILE__).$DS.'files'.$DS.'test.zip');
    22.   if($email->send())
    23.     echo('Email with attachment - OK.<br>'); else
    24.     echo('Email with attachment - Error!<br>');

    Пример письма, которое пришло мне.

    Письмо с вложением и картинкой

    Поздравляем! Вы научились отправлять письма с вложениями.

    Комментарии

    09.12.2014 05:37:54
    Avatar of МиколаМикола
    Постійно користуюся цим класом!
    Спасибі!
    26.12.2016 06:52:44
    Avatar of МиколаМикола
    ти не повіриш, але все ще користуюся)
    27.08.2019 03:50:19
    Avatar of ВадимВадим
    Как с вами связаться?
    12.06.2021 11:34:40
    Avatar of Ashlay HazaltonAshlay Hazalton
    Hi, this is Chris.
    Who win all online casinos by using FREE BONUS.

    Witch mean, I don’t really spend money in online casinos.

    But I win every time, and actually, everybody can win by following my directions.

    even you can win!

    So, if you’re the person, who can listen to someone really smart, you should just try!!

    The best online casino, that I really recommend is, Vera&John.
    Established in 2010 and became best online casino in the world.

    They give you free bonus when you charge more than $50.
    If you charge $50, your bonus is going to be $50.

    If you charge $500, you get $500 Free bonus.
    You can bet up to $1000.

    Just try roulette, poker, black jack…any games with dealers.
    Because dealers always have to make some to win and, only thing you need to do is to be chosen.

    Don’t ever spend your bonus at slot machines.
    YOU’RE GONNA LOSE YOUR MONEY!!

    Next time, I will let you know how to win in online casino against dealers!!

    Don’t forget to open your VERA&JOHN account, otherwise you’re gonna miss even more chances!!



    Open Vera&John account (free)
    https://bit.ly/3wZkpco
    26.06.2021 03:00:45
    Avatar of James LambertJames Lambert
    Good day

    I`m seeking a reputable company/individual to partner with in a manner that would benefit both parties. The project is worth $24 Million so if interested, kindly contact me through this email jameslambert@lambert-james.com for clarification.

    I await your response.

    Thanks,

    James Lambert
    26.06.2021 12:11:16
    Avatar of Mike Carrington
Mike Carrington
    Greetings

    We will enhance your Local Ranks organically and safely, using only whitehat methods, while providing Google maps and website offsite work at the same time.

    Please check our plans here, we offer Local SEO at cheap rates.
    https://speed-seo.net/product/local-seo-package/

    NEW:
    https://www.speed-seo.net/product/zip-codes-gmaps-citations/

    regards
    Mike Carrington

    Speed SEO Digital Agency
    27.06.2021 05:33:45
    Avatar of JamesRahJamesRah
    Hello! konservs.com

    Do you know the best way to talk about your product or services? Sending messages exploitation feedback forms can allow you to easily enter the markets of any country (full geographical coverage for all countries of the world). The advantage of such a mailing is that the emails that will be sent through it'll end up within the mailbox that's meant for such messages. Sending messages using Feedback forms isn't blocked by mail systems, which suggests it is guaranteed to reach the client. You'll be able to send your offer to potential customers who were previously inaccessible because of email filters.
    We offer you to test our service for free of charge. We will send up to 50,000 message for you.
    The cost of sending one million messages is us $ 49.

    This letter is created automatically. Please use the contact details below to contact us.

    Contact us.
    Telegram - @FeedbackMessages
    Skype live:contactform_18
    WhatsApp - +375259112693
    We only use chat.
    30.06.2021 12:41:25
    Avatar of Mike Michaelson
Mike Michaelson
    Hello

    I have just checked konservs.com for its SEO Trend and saw that your website could use an upgrade.

    We will enhance your SEO metrics and ranks organically and safely, using only whitehat methods, while providing monthly reports and outstanding support.

    Please check our services below, we offer SEO at cheap rates.
    https://www.hilkom-digital.de/cheap-seo-packages/

    Start improving your sales and leads with us, today!

    regards
    Mike Michaelson

    Hilkom Digital Team
    support@hilkom-digital.de
    01.07.2021 04:56:40
    Avatar of Mark SandalsMark Sandals
    Hello Dear,

    I am working directly with a private family portfolio that can provide funding for credible clients with feasible projects. Currently, we have investment funds for viable projects.

    They are interested in the following: Institution, Library, Hospitals, Green energy,
    Power projects, Agriculture and Real Estate. They can also partner with your company on other projects of value. The interest rate and tenure are fantastic.

    Your response is most anticipated if this is of interest to you. Reach me on email: financial@eurocleargroups.email or markosandals5050@gmail.com.


    Kind regards,

    Mark Sandals
    Financial Consultant
    13.07.2021 10:36:08
    Avatar of SEO X Press Digital AgencySEO X Press Digital Agency
    Hi there


    I have just took a look on your SEO for konservs.com for the ranking keywords and saw that your website could use a boost.


    We will increase your Ranks organically and safely, using only whitehat methods,


    If interested, please email us

    support@digital-x-press.com


    regards
    Mike WifKinson

    SEO X Press Digital Agency
    https://www.digital-x-press.com
    18.07.2021 11:32:31
    Avatar of Mike Oldman
Mike Oldman
    Hi there

    Do you want a quick boost in ranks and sales for your %domain% website?
    Having a high DA score, always helps

    Get your %domain% to have an amazing DA score in Moz with us today and rip the benefits of such a great feat.

    See our offers here:
    https://www.monkeydigital.co/product/moz-da50-seo-plan/

    NEW:
    https://www.monkeydigital.co/product/ahrefs-dr60/


    thank you
    Mike Oldman

    support@monkeydigital.co
    24.07.2021 05:55:20
    Avatar of Mike Scott
Mike Scott
    Howdy

    We will improve your Local Ranks organically and safely, using only whitehat methods, while providing Google maps and website offsite work at the same time.

    Please check our pricelist here, we offer Local SEO at cheap rates.
    https://speed-seo.net/product/local-seo-package/

    NEW:
    https://www.speed-seo.net/product/zip-codes-gmaps-citations/

    regards
    Mike Scott

    Speed SEO Digital Agency
    29.07.2021 10:26:27
    Avatar of TiemiossyTiemiossy
    <a href=https://cialiswwshop.com/>buy cialis online</a>
    01.08.2021 02:14:32
    Avatar of Mike Francis
Mike Francis
    Greetings

    I have just checked konservs.com for the ranking keywords and saw that your website could use an upgrade.

    We will increase your SEO metrics and ranks organically and safely, using only whitehat methods, while providing monthly reports and outstanding support.

    Please check our pricelist here, we offer SEO at cheap rates.
    https://www.hilkom-digital.de/cheap-seo-packages/

    Start increasing your sales and leads with us, today!

    regards
    Mike Francis

    Hilkom Digital Team
    support@hilkom-digital.de
    10.08.2021 08:15:40
    Avatar of SEO X Press Digital AgencySEO X Press Digital Agency
    Hi there


    I have just took a look on your SEO for konservs.com for its SEO ranks and saw that your website could use an upgrade.


    We will increase your Ranks organically and safely, using only whitehat methods,


    If interested, please email us

    support@digital-x-press.com


    regards
    Mike Green

    SEO X Press Digital Agency
    https://www.digital-x-press.com
    13.08.2021 01:18:35
    Avatar of Mike Hodges
Mike Hodges
    Hi there

    Do you want a quick boost in ranks and sales for your konservs.com website?
    Having a high DA score, always helps

    Get your konservs.com to have a DA between 50 to 60 points in Moz with us today and rip the benefits of such a great feat.

    See our offers here:
    https://www.monkeydigital.co/product/moz-da50-seo-plan/

    NEW:
    https://www.monkeydigital.co/product/ahrefs-dr60/


    thank you
    Mike Hodges

    support@monkeydigital.co
    16.08.2021 12:10:27
    Avatar of WilliamemigeWilliamemige
    Продажа цыплят в розницу и оптом с доставкой по Украине. Заходите на сайт Цыпочка https://cipochka.com.ua
    26.08.2021 01:01:54
    Avatar of Mike Jerome
Mike Jerome
    Howdy

    I have just verified your SEO on konservs.com for the ranking keywords and saw that your website could use a boost.

    We will improve your SEO metrics and ranks organically and safely, using only whitehat methods, while providing monthly reports and outstanding support.

    Please check our pricelist here, we offer SEO at cheap rates.
    https://www.hilkom-digital.de/cheap-seo-packages/

    Start enhancing your sales and leads with us, today!

    regards
    Mike Jerome

    Hilkom Digital Team
    support@hilkom-digital.de
    07.09.2021 01:10:03
    Avatar of Mike Ferguson
Mike Ferguson
    Hello

    We all know the importance that dofollow link have on any website`s ranks.
    Having most of your linkbase filled with nofollow ones is of no good for your ranks and SEO metrics.

    Buy quality dofollow links from us, that will impact your ranks in a positive way
    https://www.digital-x-press.com/product/150-dofollow-backlinks/

    Best regards
    Mike Ferguson

    support@digital-x-press.com
    17.09.2021 02:27:22
    Avatar of Mike Philips
Mike Philips
    Hello

    We will enhance your Local Ranks organically and safely, using only whitehat methods, while providing Google maps and website offsite work at the same time.

    Please check our plans here, we offer Local SEO at cheap rates.
    https://speed-seo.net/product/local-seo-package/

    NEW:
    https://www.speed-seo.net/product/zip-codes-gmaps-citations/

    regards
    Mike Philips

    Speed SEO Digital Agency
    22.09.2021 02:18:17
    Avatar of JamesRahJamesRah
    Good day! konservs.com

    Do you know the easiest way to point out your product or services? Sending messages using feedback forms will allow you to easily enter the markets of any country (full geographical coverage for all countries of the world). The advantage of such a mailing is that the emails that will be sent through it'll find yourself within the mailbox that is meant for such messages. Causing messages using Feedback forms isn't blocked by mail systems, which implies it is bound to reach the client. You will be able to send your offer to potential customers who were antecedently unprocurable because of spam filters.
    We offer you to test our service for complimentary. We will send up to 50,000 message for you.
    The cost of sending one million messages is us $ 49.

    This offer is created automatically. Please use the contact details below to contact us.

    Contact us.
    Telegram - @FeedbackMessages
    Skype live:contactform_18
    WhatsApp - +375259112693
    We only use chat.
    26.09.2021 01:23:07
    Avatar of Mike Calhoun
Mike Calhoun
    Hi there

    I have just checked konservs.com for its SEO metrics and saw that your website could use a boost.

    We will increase your SEO metrics and ranks organically and safely, using only whitehat methods, while providing monthly reports and outstanding support.

    Please check our plans here, we offer SEO at cheap rates.
    https://www.hilkom-digital.de/cheap-seo-packages/

    Start increasing your sales and leads with us, today!

    regards
    Mike Calhoun

    Hilkom Digital Team
    support@hilkom-digital.de
    01.10.2021 06:07:19
    Avatar of Mike Freeman
Mike Freeman
    Hello

    We all know the importance that dofollow link have on any website`s ranks.
    Having most of your linkbase filled with nofollow ones is of no good for your ranks and SEO metrics.

    Buy quality dofollow links from us, that will impact your ranks in a positive way
    https://www.digital-x-press.com/product/150-dofollow-backlinks/

    Best regards
    Mike Freeman

    support@digital-x-press.com
    08.10.2021 07:00:27
    Avatar of Mike Longman
Mike Longman
    Hi there

    Do you want a quick boost in ranks and sales for your konservs.com website?
    Having a high DA score, always helps

    Get your konservs.com to have a DA between 50 to 60 points in Moz with us today and reap the benefits of such a great feat.

    See our offers here:
    https://www.monkeydigital.co/product/moz-da50-seo-plan/

    NEW:
    https://www.monkeydigital.co/product/ahrefs-dr60/


    thank you
    Mike Longman

    support@monkeydigital.co
    15.10.2021 01:53:21
    Avatar of Mike Owen
Mike Owen
    Good Day

    We will increase your Local Ranks organically and safely, using only whitehat methods, while providing Google maps and website offsite work at the same time.

    Please check our pricelist here, we offer Local SEO at cheap rates.
    https://speed-seo.net/product/local-seo-package/

    NEW:
    https://www.speed-seo.net/product/zip-codes-gmaps-citations/

    regards
    Mike Owen

    Speed SEO Digital Agency
    20.10.2021 02:19:03
    Avatar of Mike Ford
Mike Ford
    Hello

    I have just analyzed konservs.com for the ranking keywords and saw that your website could use a push.

    We will improve your SEO metrics and ranks organically and safely, using only whitehat methods, while providing monthly reports and outstanding support.

    Please check our pricelist here, we offer SEO at cheap rates.
    https://www.hilkom-digital.de/cheap-seo-packages/

    Start improving your sales and leads with us, today!

    regards
    Mike Ford

    Hilkom Digital Team
    support@hilkom-digital.de
    27.10.2021 02:21:25
    Avatar of skripkaskripka
    Привет. За последние два года коронавирус хладнокровно убивает бизнес. Все сидят на удалёнке, а кого то и вовсе сокращают. Людей стремящихся к улучшению своих профессиональных навыков или освоению новых, наверняка заинтересует моё предложение. Качайте самые свежие и популярные платные курсы, книги, тренинги и вебинары от известных авторов по самым разным направлениям. Повышайте свою квалификацию, укрепляйте ваш бизнес, познавайте себя и окружающий мир, заводите новые хобби и прокачивайте свои навыки. Цена вечной подписки символическая 500 руб.

    Вы получите возможность скачивать платные профессиональные курсы, стоимость которых многократно превышают сумму вечной подписки. Освойте новую профессию или просто изучайте интересные вам материалы.

    Упомянутый мною саит вы сможете найти по адресу https://vk.cc/c7fS7J либо написав любое сообщение в telegram пользователю @AliceSugar ( https://t.me/AliceSugar ).

    Вы так же можете отписаться от данной рассылки заполнив форму https://docs.google.com/forms/d/e/1FAIpQLSci7Qu_YAf-A_Ml8pL8fO7ClI1W1XEzMyfzp0NS0fZiPYtprA/viewform?usp=sf_link
    Captcha Обновить
    Go Top