代码之家  ›  专栏  ›  技术社区  ›  DCR

phpmailer未嵌入图像

  •  0
  • DCR  · 技术社区  · 3 年前

    我有以下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 & 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 & 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'] = "[email protected]";
    mailerExpressBlueHostSWAGpdf($mailerInputs);
    
    ?>
    

    这是我的mailer函数(mailerExpressBlueHostSWAGpdf())

    function mailerExpressBlueHostSWAGpdf(array $mailInputs){
       
       chdir('../'); 
       
       require_once '../includes/phpmailer/PHPMailerAutoload.php';
    
       $mail = new PHPMailer();
       $mail->IsMail();   
       $mail->SetFrom('[email protected]');
       $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';
          }
       }   
    }
    

    所有的图像都在那里。有人能理解为什么没有嵌入图像吗?

    0 回复  |  直到 3 年前
        1
  •  0
  •   Synchro    3 年前

    对于这样的问题,你的第一站应该总是 the documentation .

    你做错了三件事:

    1. 提供远程文件的URL。PHPMailer不支持这一点;它不是HTTP客户端。相关的文档中提到了这一点 addAttachment method ,同样适用于此处。
    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('../'); 
    

    这很奇怪,很可能会在应用程序的其他地方引发各种奇怪的问题。想象一下在循环中调用这个方法。你的工作目录会发生什么变化?