Viewed   260 times

I have a site where in a page I have developed an xls report. After its creation I want to send it in a mail with phpmailer. How can I attach this file to the email? This is my code:

    $objPHPExcel = new PHPExcel();

            // Set document properties
            $objPHPExcel->getProperties()->setCreator("Alessandro Minoccheri")
                                         ->setLastModifiedBy("Alessandro Minoccheri")
                                         ->setTitle("Office 2007 XLSX Test Document")
                                         ->setSubject("Office 2007 XLSX Test Document")
                                         ->setDescription("Generazione report inverter")
                                         ->setKeywords("office 2007 openxml php")
                                         ->setCategory("");

            $row=1;
            $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow('0', $row, 'Inverter');
            $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow('1', $row, 'Channel');
            $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow('2', $row, 'Picco');
            $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow('3', $row, 'Picco data');
            $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow('4', $row, 'Media');
            $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow('5', $row, 'Sommatoria');
$objPHPExcel->setActiveSheetIndex(0);

        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('report.xls');

               $yourName = 'Client';
        $yourEmail_2 = 'alessandro@xxx-it';

        ini_set("include_path", "../inc/phpmailer/");
        require("class.phpmailer.php");
        $mail = new PHPMailer();

        $mail->From     = 'xxx@xxx.com';
        $mail->FromName = 'Client';
        $mail->AddAddress($yourEmail_2); 
        //$mail->AddBCC($yourEmail_2); 

        /*if(!empty($_FILES['attachment']['tmp_name'])){
            $new_name = urlencode( rand(0,10000).rand(10000,20000).$_FILES['attachment']['name'] );
            if(move_uploaded_file($_FILES['attachment']['tmp_name'],'./uploads/'.$new_name)){
                $string_file = '<p>Curriculum allegato: '</p>';
            }
        }*/

        $mail->WordWrap = 50;                              // set word wrap
        $mail->IsHTML(true);                               // send as HTML

        $mail->Subject  =  'Riepilogo settimanale';

        $mail->Body     =  "Riepilogo settimanale dell'impianto: ".utf8_decode($inv['name']);

        $mail->AltBody  =  "Riepilogo settimanale dell'impianto: ".utf8_decode($inv['name']);

        if ( $mail->Send()){
            //ok
        }

 Answers

4

Have you tried...

$mail->AddAttachment($full_path_to_file, "report.xls");
Tuesday, September 6, 2022
 
3

Here is another possible way without re-creating the Class each time.

<?php

require 'phpmailer/PHPMailerAutoload.php';
$mail = new PHPMailer;
$mail->isSMTP();                                      // Set mailer to         use SMTP
$mail->Host = 'smtp.gmail.com';  // Specify main and backup SMTP servers
$mail->SMTPAuth = true;                               // Enable SMTP authentication
$mail->Username = 'yyy.com';                 // SMTP username
$mail->Password = 'yyy';                           // SMTP password
$mail->SMTPSecure = 'tls';                            // Enable TLS encryption, `ssl` also accepted
$mail->Port = 587;                                    // TCP port to connect to
$person = array(0 => 'xxx.com', 'xxx2.com');

$mail->setFrom('yyy.com');
$mail->isHTML(true);                                  // Set email format to HTML
$mail->Subject = 'Here is the subject';
$mail->Body    = "xxx";
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';

$errors = [];
for ($x = 0; $x < 2; $x++) {
    $mail->addAddress($person[$x]);
    if(!$mail->send()) {
        $errors[] = 'Message could not be sent. Mailer Error: ' . $mail->ErrorInfo;
    }
    $mail->clearAddresses();
}

if(empty($errors)) {
    // success
} else {
    // handle errors
}

Using $mail->clearAddresses(); within the loop.

Tuesday, November 8, 2022
 
1

Encoding is not a variable: $this->Encoding

Wednesday, August 10, 2022
1

It is pretty simple, leave the images on the server and send the PHP + CSS to them...

$to = 'bob@example.com';

$subject = 'Website Change Reqest';

$headers = "From: " . strip_tags($_POST['req-email']) . "rn";
$headers .= "Reply-To: ". strip_tags($_POST['req-email']) . "rn";
$headers .= "CC: susan@example.comrn";
$headers .= "MIME-Version: 1.0rn";
$headers .= "Content-Type: text/html; charset=UTF-8rn";

$message = '<p><strong>This is strong text</strong> while this is not.</p>';


mail($to, $subject, $message, $headers);

It is this line that tells the mailer and the recipient that the email contains (hopefully) well formed HTML that it will need to interpret:

$headers .= "Content-Type: text/html; charset=UTF-8rn";

Here is the link I got the info.. (link...)

You will need security though...

Sunday, October 9, 2022
 
4

Flow code:

The head tag:

<head runat="server">
    <title></title>
     <script type="text/javascript"
          src="https://www.google.com/jsapi?autoload={
            'modules':[{
              'name':'visualization',
              'version':'1',
              'packages':['corechart']
            }]
          }"></script>
    
<script type="text/javascript">
        google.setOnLoadCallback(drawChart);
        function drawChart() {
            var data = google.visualization.arrayToDataTable([
              ['Year', 'Sales', 'Expenses'],
              ['2004', 1000, 400],
              ['2005', 1170, 460],
              ['2006', 660, 1120],
              ['2007', 1030, 540]
            ]);

            var options = {
                title: 'Company Performance',
                curveType: 'function',
                legend: { position: 'bottom' }
            };

            var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));
            var txtBase64 = document.getElementById('txtBase64Image');
            google.visualization.events.addListener(chart, 'ready', function () {
                txtBase64.value = chart.getImageURI();
            });
            chart.draw(data, options);
        }
    </script>
</head>

Body tag:

<body>
    <form id="form1" runat="server">
        <div id="curve_chart" style="width: 900px; height: 500px"></div>
        <%--If you want, you can textbox visible false.--%>
        <asp:TextBox ID="txtBase64Image" runat="server" Width="600" TextMode="MultiLine"></asp:TextBox><br/>
        <asp:Button ID="Button1" runat="server" Text="Send Mail" OnClick="Button1_Click" />
    </form>
</body>

After c# code:

public Image Base64ToImage(string base64String)
{
    var imageBytes = Convert.FromBase64String(base64String);
    using (var ms = new MemoryStream(imageBytes, 0, imageBytes.Length))
    {
        var image = Image.FromStream(ms, true);
        return image;
    }
}

Button click: Send to mail chart. Look EmailSender https://github.com/serkomut/Serkomut.MailSender

protected void Button1_Click(object sender, EventArgs e)
{
    var split = txtBase64Image.Text.Split(',')[1];
    var image = Base64ToImage(split);
    var stream = new MemoryStream();
    image.Save(stream, ImageFormat.Jpeg);
    stream.Position = 0;

    var result = new EmailSender()
                    .FromHost("smtp.gmail.com")
                    .Credential("sendermail@gmail.com", "mailPassword")
                    .FromTo(new Message
                    {
                        From = "sendermail@gmail.com",
                        To = "tomail@gmail.com"
                    })
                    .Subject("Subject")
                    .Body("Content text...")
                    .Attachment(new Attachment(stream, "chart_image.jpg", "image/jpg"))
                    .Send();
}
Thursday, September 29, 2022
 
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :