phpmailer не встраивает изображения

#image #phpmailer #embed

Вопрос:

У меня есть следующий html-файл:

 <!DOCTYPE html>
<html>
    <head>
        <title></title>
        <link href="https://fonts.googleapis.com/css?family=Montserrat|Ubuntu" rel="stylesheet">
    </head>
    <body>
        <div id = 'container' style="height:500vh;width:88vw;margin:0 auto;color:#365f91;font-family:'Montserrat', sans-serif;font-size:1.75vw">

            <div style="display:flex;justify-content:space-between;margin-top:6vh;margin-bottom:1.5vh;">
                <div style='display:flex;flex-direction:column;justify-content:space-between;'>
                    <p style="margin:0;color:#38761d;font-weight:bold;font-size:2.75vw;">SWAG Newsletter Fall 2021</p>
                    <span style="display:block;margin-bottom:1.5%;color:#9bbb59;font-weight:bold;font-size:2.5vw">LATEST NEWS</span>
                </div>
                <img style = "right;width:25%" src="cid:pic1" >

            </div>
            <span style="display:block;color:#23456c;font-weight:bold;">Weston Power Choice: Awaiting DPU Approval</span>
            <p style="margin:0">
               <img style="float:left;width:25%;margin-right:2%;margin-top:1vh;" src="cid:pic2">
               Weston Power Choice is still alive! The Town  submitted its aggregation plan for
               <a href="https://masspowerchoice.com/weston">Weston Power Choice</a> to the Department of Public Utilities(DPU) on October 29, 2020.
               While we certainly wish we could accelerate this process, it is still sitting in the
               DPU review pipeline. Once the plan is approved, the Town will select an electricity
               supplier and, in close cooperation with SWAG, inform the community on next steps.
           </p><br>

           <span style="display:block;color:#23456c;font-weight:bold;">Pay-As-You-Throw: Implemented and Moving Forward</span>
           <p style="margin:0%">
              <img style="float:left;width:21%;margin-right:2%;margin-top:1%;" src="cid:pic3">
              SWAG helped the Town's Pay-As-You-Throw (PAYT) implementation by staffing an information
              table at the Weston transfer station on September 25th and October 2nd. During the preceding
              months, SWAG shared a steady stream of resources on reducing waste through composting,
              reusing and recycling. Aftersome initial challenges, the PAYT program is now running smoothly.
              While it's too early to determine the program's impact on the town's waste volumes, the transfer
              station has seen a noticeable increase in food waste going into the compost bins.
          </p>
          <br>

          <span style="display:block;color:#23456c;font-weight:bold;">Weston Ahead: Continues to Make Headway</span>
          <p style="margin:0%">
             <img style="float:left;width:20%;margin-right:2%;margin-top:1%;" src="cid:pic4">
             The Town is working hard to make progress on the goals set in the <a href="https://www.westonma.gov/1486/Weston-Ahead">
             Climate Action amp; Resilience Plan</a>. Efforts completed/underway include: launching Pay-As-You-Throw at the transfer
             station, replacing all street lights with LED's, conducting a Tree Survey with residents about interest in tree protections,
             pursuing a zero-energy bylaw, evaluating the feasibility of moving Town Hall from oil to electric heat, upgrading HVAC
             systems at the schools for health and energy effiency, and much more.
         </p>
         <br>

         <span style="display:block;color:#23456c;font-weight:bold;">Weston Plant Pollinator Alliance (WPPA): Display Garden Installed,
         2nd on the Way</span>
         <p style="margin:0%;margin-bottom:2vh;">
            <img style="float:left;width:15%;margin-right:2%;margin-top:1%;" src="cid:pic5">
            Are you interested in learning more about native plants, wild pollinators, and actions you can take
            at home to support at-risk species? The Weston Plant Pollinator Alliance(WPPA) <a href="https://www.wppama.org/">
            website</a> is a comprehensive resource highlighting local native pollinator conservation efforts. The first
            WPPA public <a href="https://www.wppama.org/our-projects">pollination preservation display garden</a>, installed last
            May at the Concord Rd. entrance to the Weston segment of the MassCentral Rail Trail, contains examples of beneficial
            native plants anyone can add to their yards to support at-risk pollinators. The WPPA continues to interface with local
            groups and organizations to increase pollinator resources and habitat in existing gardens throughout Weston, including
            a second public display garden planned for Spring 2022 installation.
        </p>
         <br>
        <span style="display:block;margin-bottom:0%;color:#9bbb59;font-weight:bold;font-size:2vw">UPCOMING EVENTS amp; ACTIONS</span>
        <ul style="padding:2vw;margin-top:0">
            <li style='margin-bottom:.5%;'><span style= "color:#23456c;font-weight:bold;">Interested in driving Impact in your Community?</span>
                SWAG is always looking for passionate volunteers. Join our monthly meetings on the second Thursday of each month and
                find out which topic(s) excite you. Meeting information can be found on the
                <a href="https://sustainablewestonma.org/.swag2/public/php/homeCtrl.php?place=gi-attend">SWAG website.</a>
            </li>
            <li style='margin-bottom:.5%;'><span style= "color:#23456c;font-weight:bold;">Annual Weston School-Wide Clean Up Day: November
                11th from 9-11 am.</span> Bring your family and help
                <a href="https://www.westonschools.org/high/blog/2021/10/25/annual-wps-clean-up-day-november-11th/">pick up trash around the school grounds!</a>
            </li>
            <li style='margin-bottom:.5%;'><span style= "color:#23456c;font-weight:bold;">National Recycling Day: November 15th.</span>
                Check out the <a href="https://www.sustainablewestonma.org/.swag2/public/php/homeCtrl.php?place=Calendar">SWAG calendar</a>
                for presentations on recycling and reducing waste during November!
            </li>
            <li style='margin-bottom:.5%;'><span style= "color:#23456c;font-weight:bold;">Creating a More Energy-Efficient House:
                November 16th.</span> Hear three local residents describe how they cut their use of fossil fuels and saved money. Find
                out more <a href="https://www.metrowestclimatesolutions.org/events/creating-a-more-energy-efficient-home-personal-stories">here.</a>
            </li>
            <li style='margin-bottom:.5%;'><span style= "color:#23456c;font-weight:bold;">Land's Sake Farm Environmental Education:
                Sign-up for Winter Programs!</span> After-school programs have started this week but there are still a few spots
                left in the Tue K-grade 2 and Thu grade 3-6 programs. <a href="https://landssake.org/education/after-school-programs/">Sign-up</a> quickly to secure your spot!
            </li>
        </ul>

        <p style="float:right;font-size:1vw">SWAG Quarterly Newsletter <br>Update No.10 11/07/21</p>
        <br>

        <p style='height:2vh;width:100%;background-color:darkgrey;'></p>

        <br>
        <span style="display:block;margin:3vh 0;color:#9bbb59;font-weight:bold;font-size:2vw">SUSTAINABILITY SPOTLIGHT</span>
        <br>

        <p style="margin-top:10vh;">Did you know food waste accounts for approximately 25% of the average household's trash? By removing
        food from the waste stream, Weston residents can significantly reduce their total waste and carbon footprint, and create
        nutrient-rich compost to aid healthy plant growth.</p>


        <p>Earlier this year, SWAG launched a campaign to help residents reduce their food (and other) waste streams. And it resonated!
        Here are two residents who creatively incorporated composting into their daily life.</p>


        <div>
            <img style="float:left;width:30%;margin-right:2%;margin-top:1%;" src="cid:pic6">
        <p style= "color:#23456c;font-weight:bold;font-size:2vw;">Jeff Barz-Snell</p>
        <span style= "display:block;color:#23456c;font-weight:bold;">Tell us about yourself</span>
        <p style="margin-top:0">I moved to Weston from Salem in 2018 with my wife and three children.  We live in the
            parsonage next to the First Parish Church, where I currently serve as the Minister.</p>

        <span style= "display:block;color:#23456c;font-weight:bold;">What are you showing in the picture?</span>
        <p style="margin-top:0">Clementine and I are next to a Green Cone Food Digester, which we installed in our yard last April.</p>

        <span style= "display:block;color:#23456c;font-weight:bold;">How is a Green Cone Food Digester different from a backyard composter?</span>
        <p style="margin-top:0">It's an aerobic digester designed to break down all food. You don't put leaves and grass in it,
            but you can compost vegetables, fruit, meat, fish, eggs, coffee and even bones. No mixing or turning of material is needed.
            The only requirement is a sunny location with good drainage.</p>

        <span style= "display:block;color:#23456c;font-weight:bold;">What spurred you to take this action?</span>
        <p style="margin-top:0">I've been involved in environmental work for many years. During a presentation last spring on
            Trash and Recycling given by the MetroWest Climate Solutions group, the presenter mentioned she used a Green Cone. I was curious.</p>
        </div>

        <span style= "display:block;color:#23456c;font-weight:bold;">Are the results what you expected?</span>
        <p style="margin-top:0">Yes, it works very well and has little or no smell, since most of the unit is buried in the ground.
            It did not attract vermin or other animals this summer, which is an important consideration around here.</p>

        <span style= "display:block;color:#23456c;font-weight:bold;">Do you see a noticeable reduction in your trash?</span>
        <p style="margin-top:0">Definitely. We dump 3-4 lbs of food waste into the digester every 3 days or so. It can
            accommodate up to 2.3 lbsper day. Since we don't have a garbage disposal it has made a big difference in the
            amount of trash and associated odors we bring to the transfer station. Your trash pick-up service will thank you as well!</p>

        <div>
            <img style="float:left;width:30%;margin-right:2%;margin-top:1%;" src="cid:pic7">
            <p style= "color:#23456c;font-weight:bold;font-size:2vw;">Marc van Zadelhoff</p>
            <span style= "display:block;color:#23456c;font-weight:bold;">Tell us a about yourself</span>
            <p style="margin-top:0">I live on 44 Silver Hill Road with my wife and three daughters ages 14, 12 and 10.
                I run a SaaS software company and when not working, I enjoy spending time with my family, woodworking and doing outdoor sports.</p>

            <span style= "display:block;color:#23456c;font-weight:bold;">What are you showing in the picture?</span>
            <p style="margin-top:0">It's a compost bin  I made from repurposed wood. The wood was originally used for a wheelchair ramp,
                which was built for my father before he passed away 2 years ago. I repurposed it to make a compost bin for our yard.
                My mother was super happy to see it go to great use.</p>

            <span style= "display:block;color:#23456c;font-weight:bold;">What spurred you to take this action?</span>
            <p style="margin-top:0">I was inspired by my wife who works in corporate sustainability and by the fact that we were
                throwing away a significant amount of compostable food materials. The great thing about composting is once you do it,
                you have much less smelly trash and amazing, reusable materials for planting.</p>
        </div>
            <span style= "display:block;color:#23456c;font-weight:bold;">Are the results what you expected?</span>
            <p style="margin-top:0">The compost bin turned out as I expected. It's actually the second one I've built so
                I was able to use my first experience to improve on this model. Particularly satisfying was that one of my
                neighbors saw it and asked me to build one for her! I love woodworking so I'm now building one for her family.</p>

            <span style= "display:block;color:#23456c;font-weight:bold;">Do you have any recommendations for others who want to
                emulate your action?</span>
            <p style="margin-top:0">Keep it simple and keep in mind that doing something is better than doing nothing.
                These bins are pretty easy to construct yourself or you can ask a handy neighbor to  do it for you.</p>

        <p style="float:right;font-size:1vw">SWAG Quarterly Newsletter <br>Update No.10 11/07/21</p>


        </div>
    </body>
</html>
 

программа управления php:

 <?php

require ("../../includes/functions.php");
require ("../../includes/newConstants.php");


$body = file_get_contents('https://sustainablewestonma.org/.swag2/vhtml/newsletter-fall2021.html');
//echo $body;


$mailerInputs['body'] = $body;
$mailerInputs['addAddress'] = "abc123@gmail.com";
mailerExpressBlueHostSWAGpdf($mailerInputs);

?>
 

и это моя функция почтовой рассылки (mailerExpressBlueHostSWAGpdf())

 function mailerExpressBlueHostSWAGpdf(array $mailInputs){
   
   chdir('../'); 
   
   require_once '../includes/phpmailer/PHPMailerAutoload.php';

   $mail = new PHPMailer();
   $mail->IsMail();   
   $mail->SetFrom('swag@sustainablewestonma.org');
   $mail->addAddress($mailInputs['addAddress']);   

   $body = $mailInputs['body'] ;     
   
   
   $mail->addEmbeddedImage("https://sustainablewestonma.org/.swag2/public/images/newsletters/fall2021/Picture1.png", "pic1");
   $mail->addEmbeddedImage("https://sustainablewestonma.org/.swag2/public/images/newsletters/fall2021/Picture2.png", "pic2");
   $mail->addEmbeddedImage("https://sustainablewestonma.org/.swag2/public/images/newsletters/fall2021/Picture3.png", "pic3");
   $mail->addEmbeddedImage("https://sustainablewestonma.org/.swag2/public/images/newsletters/fall2021/Picture4.png", "pic4");
   $mail->addEmbeddedImage("https://sustainablewestonma.org/.swag2/public/images/newsletters/fall2021/Picture5.png", "pic5");
   $mail->addEmbeddedImage("https://sustainablewestonma.org/.swag2/public/images/newsletters/fall2021/Picture6.png", "pic6");
   $mail->addEmbeddedImage("https://sustainablewestonma.org/.swag2/public/images/newsletters/fall2021/Picture7.png", "pic7");
   
   
   $mail->Subject = "SWAG Fall Newsletter" ;
   $mail->Body    = $body;
   $mail->IsHTML(true);
   $mail->ContentType="text/HTML";
   
   if(1==1){
      
      if(!$mail->send()) {
        // echo 'mail not sent <br>' ;
         $mail->ClearAddresses();
         return 'Message could not be sent.' . 'Mailer Error: ' . $mail->ErrorInfo;
      }else{
        // echo 'mail sent 2<br>';
         //echo $body;
         $mail->ClearAddresses();
         return 'Message has been sent';
      }
   }   
}
 

Все изображения есть. Кто-нибудь может понять, почему изображения не внедряются?

Ответ №1:

Вашей первой остановкой для такого вопроса всегда должна быть документация.

Вы делаете три основные вещи неправильно:

  1. Предоставление URL — адреса для удаленного файла. Это не поддерживается PHPMailer; это не HTTP-клиент. Это упоминается в документах по соответствующему addAttachment методу, и то же самое относится и здесь.
  2. Если вы хотите вставить данные изображения напрямую, а не через локальный файл, вам необходимо использовать addStringEmbeddedImage .
  3. Указав неверный параметр, вы не проверяете возвращаемое значение метода, поэтому вы не знаете, что он не работает.

Извлечение удаленных ресурсов-это ваша работа, а не PHPMailer. Чтобы сделать это самостоятельно, вы могли бы попробовать:

 $image = file_get_contents('https://sustainablewestonma.org/.swag2/public/images/newsletters/fall2021/Picture1.png');
if ($image) {
    if (!$mail->addStringEmbeddedImage($image, 'pic1', 'pic1.png')) {
        echo 'Could not attach image';
    }
} else {
    echo 'Fetching image failed';
}
 

Ты делаешь и некоторые другие вещи неправильно:

Вы используете очень старую версию PHPMailer, которая больше не поддерживается и, вероятно, содержит уязвимости. Получите последнюю версию и управляйте зависимостью с помощью composer.

Ты звонишь isMail() . Это транспорт отправки по умолчанию, поэтому это ничего не меняет.

Ты звонишь clearAddresses() после отправки. Это очищает добавленные вами адреса, но ваш экземпляр PHPMailer выходит за рамки области действия в следующей строке, поэтому это ничего не дает.

Это, вероятно, нарушит форматирование для получателей:

 $mail->ContentType="text/HTML";
 

Типы MIME, как правило , все строчные, и это значение уже правильно задано предыдущим вызовом isHTML() , поэтому вы можете удалить эту строку.

Вы не проверяете возвращаемое значение addAddress , и, учитывая, что это значение предоставляется извне этой функции, вы не узнаете, произойдет ли сбой, пока позже при попытке отправки.

 chdir('../'); 
 

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