How to Send Email with PDF Attachment Using PHP

php send e-mail with PDF attachment

You can use PHPMailer with FPDF . It works properly without any hassle. You need to change parameter for $pdf->Output . Download and copy class.phpmailer.php and PHPMailerAutoload.php to your work folder. Attach class.phpmailer.php below or above require('html2pdf.php'); . I have done this before so this will work. According to your code this should work.

function send_pdf_to_user(){
if($_REQUEST['action'] == 'pdf_invoice' ){
require('html2pdf.php');
require_once('class.phpmailer.php');
$pdf=new PDF_HTML();
$pdf->SetFont('Arial','',11);
$pdf->AddPage();

$text = get_html_message($_REQUEST['eventid'], $_REQUEST['userid']);
if(ini_get('magic_quotes_gpc')=='1')
$text=stripslashes($text);
$pdf->WriteHTML($text);

$mail = new PHPMailer(); // defaults to using php "mail()"
$body = "This is test mail by monirul";

$mail->AddReplyTo("webmaster@test.ch","Test Lernt");
$mail->SetFrom('webmaster@test.ch', 'Test Lernt');

$address = "monirulmask@gmail.com";
$mail->AddAddress($address, "Abdul Kuddos");
$mail->Subject = "Test Invoice";
$mail->AltBody = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test

$mail->MsgHTML($body);
//documentation for Output method here: http://www.fpdf.org/en/doc/output.htm
$pdf->Output("Test Invoice.pdf","F");
$path = "Walter Lernt Invoice.pdf";

$mail->AddAttachment($path, '', $encoding = 'base64', $type = 'application/pdf');
global $message;
if(!$mail->Send()) {
$message = "Invoice could not be send. Mailer Error: " . $mail->ErrorInfo;
} else {
$message = "Invoice sent!";
}

}
}

How to attach PDF to email using PHP mail function

You should consider using a PHP mail library such as PHPMailer which would make the procedure to send mail much simpler and better.

Here's an example of how to use PHPMailer, it's really simple!

<?php

require_once('../class.phpmailer.php');

$mail = new PHPMailer(); // defaults to using php "mail()"

$body = file_get_contents('contents.html');
$body = eregi_replace("[\]",'',$body);

$mail->AddReplyTo("name@yourdomain.com","First Last");

$mail->SetFrom('name@yourdomain.com', 'First Last');

$mail->AddReplyTo("name@yourdomain.com","First Last");

$address = "whoto@otherdomain.com";
$mail->AddAddress($address, "John Doe");

$mail->Subject = "PHPMailer Test Subject via mail(), basic";

$mail->AltBody = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test

$mail->MsgHTML($body);

$mail->AddAttachment("images/phpmailer.gif"); // attachment
$mail->AddAttachment("images/phpmailer_mini.gif"); // attachment

if(!$mail->Send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "Message sent!";
}

?>

An alternative to PHPMailer is http://swiftmailer.org/

How to send email with pdf attachment using php?

Start using Swiftmailer, your life will be easier.

Use example :

require_once('swift/lib/swift_required.php');

$transport = Swift_MailTransport::newInstance();
$mailer = Swift_Mailer::newInstance($transport);
$message = Swift_Message::newInstance()
->setFrom(array($from))
->setTo(array($to))
->setEncoder(Swift_Encoding::get7BitEncoding())
->setSubject($subject)
->setBody($body, 'text/html')
->addPart(strip_tags($body), 'text/plain')
->attach(Swift_Attachment::fromPath($filename))
;
$mailer->send($message);

Send attachments with PHP Mail()?

I agree with @MihaiIorga in the comments – use the PHPMailer script. You sound like you're rejecting it because you want the easier option. Trust me, PHPMailer is the easier option by a very large margin compared to trying to do it yourself with PHP's built-in mail() function. PHP's mail() function really isn't very good.

To use PHPMailer:

  • Download the PHPMailer script from here: http://github.com/PHPMailer/PHPMailer
  • Extract the archive and copy the script's folder to a convenient place in your project.
  • Include the main script file -- require_once('path/to/file/class.phpmailer.php');

Now, sending emails with attachments goes from being insanely difficult to incredibly easy:

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

$email = new PHPMailer();
$email->SetFrom('you@example.com', 'Your Name'); //Name is optional
$email->Subject = 'Message Subject';
$email->Body = $bodytext;
$email->AddAddress( 'destinationaddress@example.com' );

$file_to_attach = 'PATH_OF_YOUR_FILE_HERE';

$email->AddAttachment( $file_to_attach , 'NameOfFile.pdf' );

return $email->Send();

It's just that one line $email->AddAttachment(); -- you couldn't ask for any easier.

If you do it with PHP's mail() function, you'll be writing stacks of code, and you'll probably have lots of really difficult to find bugs.

Email PDF Attachment with PHP Using FPDF

This ended up working for me:

<?php
require('lib/fpdf/fpdf.php');

$pdf = new FPDF('P', 'pt', array(500,233));
$pdf->AddFont('Georgiai','','georgiai.php');
$pdf->AddPage();
$pdf->Image('lib/fpdf/image.jpg',0,0,500);
$pdf->SetFont('georgiai','',16);
$pdf->Cell(40,10,'Hello World!');

// email stuff (change data below)
$to = "myemail@example.com";
$from = "me@example.com";
$subject = "send email with pdf attachment";
$message = "<p>Please see the attachment.</p>";

// a random hash will be necessary to send mixed content
$separator = md5(time());

// carriage return type (we use a PHP end of line constant)
$eol = PHP_EOL;

// attachment name
$filename = "test.pdf";

// encode data (puts attachment in proper format)
$pdfdoc = $pdf->Output("", "S");
$attachment = chunk_split(base64_encode($pdfdoc));

// main header
$headers = "From: ".$from.$eol;
$headers .= "MIME-Version: 1.0".$eol;
$headers .= "Content-Type: multipart/mixed; boundary=\"".$separator."\"";

// no more headers after this, we start the body! //

$body = "--".$separator.$eol;
$body .= "Content-Transfer-Encoding: 7bit".$eol.$eol;
$body .= "This is a MIME encoded message.".$eol;

// message
$body .= "--".$separator.$eol;
$body .= "Content-Type: text/html; charset=\"iso-8859-1\"".$eol;
$body .= "Content-Transfer-Encoding: 8bit".$eol.$eol;
$body .= $message.$eol;

// attachment
$body .= "--".$separator.$eol;
$body .= "Content-Type: application/octet-stream; name=\"".$filename."\"".$eol;
$body .= "Content-Transfer-Encoding: base64".$eol;
$body .= "Content-Disposition: attachment".$eol.$eol;
$body .= $attachment.$eol;
$body .= "--".$separator."--";

// send message
mail($to, $subject, $body, $headers);

?>

How to send email with attachment (pdf) in laravel?

in my controller i uploaded the file and send it to mail class like this:

    if ($request->has('resume')) {
$file = $request->file('resume');
$file_name = Str::random(7) . '.'.$file->getClientOriginalExtension();
$destinationPath = "/followUp";
$file->move(public_path($destinationPath), $file_name);
$file = 'followUp/'.$file_name;
}
$subject = 'پیگیری رزومه - ایندید';

Mail::to('visanewcom@gmail.com')->send(new sendMail($username,$mobile,$subject,$file));

and then in send mail class:

 return $this->view('email.followUp')

->with('username',$this->username)
->with('mobile',$this->mobile)
->with('file',$this->file)
->subject($this->subject)
->attach(public_path($this->file), [
'as' => 'resume.pdf',
'mime' => 'application/pdf',
])
;

Sending an email with a PDF Files attachment using PHP

// once there are no errors, as soon as the customer hits the submit button, it needs to send an email to the staff with the customer information
$msg = "Name: " .$_POST['name'] . "\n"
."Email: " .$_POST['email'] . "\n"
."Phone: " .$_POST['telephone'] . "\n"
."Number Of Guests: " .$_POST['numberOfGuests'] . "\n"
."Date Of Reunion: " .$_POST['date'];
$staffEmail = "staffemail";

mail($staffEmail, "You have a new customer", $msg); // using the mail php function to send the email. mail(to, subject line, message)

//once the customer submits his/her information, he/she will receive a thank you message attach with a pdf file.
// creating a pdf file
$pdf_filename = tempnam(sys_get_temp_dir(), "pdf");
$pdf=new FPDF();
$pdf->AddPage();
$pdf->SetFont("Arial", "B", 16);
$pdf->Cell(40, 10, "Title");
$pdf->Ln();
$pdf->SetFont("Arial", "", 12);
$pdf->Cell(15, 10, "Name:");
$pdf->SetFont("Arial", "I", 12);
$pdf->Cell(15, 10, $_POST['name']);
$pdf->Ln();
$pdf->SetFont("Arial", "", 12);
$pdf->Cell(15, 10, "Email:");
$pdf->SetFont("Arial", "I", 12);
$pdf->Cell(15, 10, $_POST['email']);
$pdf->Ln();
$pdf->SetFont("Arial", "", 12);
$pdf->Cell(15, 10, "Phone:");
$pdf->SetFont("Arial", "I", 12);
$pdf->Cell(15, 10, $_POST['telephone']);
$pdf->Ln();
$pdf->SetFont("Arial", "", 12);
$pdf->Cell(40, 10, "Number of Guests:");
$pdf->SetFont("Arial", "I", 12);
$pdf->Cell(40, 10, $_POST['numberOfGuests']);
$pdf->Ln();
$pdf->SetFont("Arial", "", 12);
$pdf->Cell(40, 10, "Date Of Reunion:");
$pdf->SetFont("Arial", "I", 12);
$pdf->Cell(40, 10, $_POST['date']);
// if file doesn't exists or if it is writable, create and save the file to a specific place
if(!file_exists($pdf_filename) || is_writable($pdf_filename)){
$pdf->Output($pdf_filename, "F");
} else {
exit("Path Not Writable");
}

// using the phpmailer class
// create a new instance called $mail and use its properties and methods.
$mail = new PHPMailer();
$staffEmail = "staffemail";
$mail->From = $staffEmail;
$mail->FromName = "name";
$mail->AddAddress($_POST['email']);
$mail->AddReplyTo($staffEmail, "name");

$mail->AddAttachment($pdf_filename);
$mail->Subject = "PDF file attachment";

$mail->Body = "message!";

// if mail cannot be sent, diplay error message
//if(!$mail->Send()){
//echo "<div id=\"mailerrors\">Message could not be sent</div>";
//echo "<div id=\"mailerrors\">Mailer Error: " . $mail->ErrorInfo . "</div>";
//} else { // else...if mail is sent, diplay sent message
//echo "<div id=\"mailerrors\">Message sent</div>";
//}

// delete the temp file
unlink($pdf_filename);
}
}


Related Topics



Leave a reply



Submit