Send email with PDF attachment using PHP

Facebook
Reddit
Twitter
Whatsapp
Cover image

Sometimes we may need to send email from our website to the client with some attachment. In this tutorial we will query the MySQL database to get the updated data from our table and email the data to the desired email as PDF attachment.

Live Demo

For this we will use

  • AngularJS [For front end]
  • PHP [To query the database and send email]
  • MySQL [The database]
  • fPDF library [This will generate the PDF for us]
  • SendGrid [This helps us sending the email in a better way]

code

index.html

<?php
class Database {
private $host = "localhost";
private $user = "root";
private $password = "root";
private $database = "crud";
function runQuery($sql) {
$conn = new mysqli($this->host,$this->user,$this->password,$this->database);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$resultset[] = $row;
}
}
$conn->close();
if(!empty($resultset))
return $resultset;
}
}
?>

books.sql

--
-- Table structure for table `books`
--
CREATE TABLE IF NOT EXISTS `books` (
`name` varchar(255) DEFAULT NULL,
`author` varchar(255) DEFAULT NULL
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8;
--
-- Dumping data for table `books`
--
INSERT INTO `books` (`name`,`author`) VALUES
('What young India wants', 'Chetan Bhagat'),
('Two States', 'Chetan Bhagat'),
('The hunger games', 'Suzanne Collions'),
('The 3 mistakes of my life', ' Chetan Bhagat'),
('Serious Men', ' Manu Joseph'),
('Revolution 2020', ' Chetan Bhagat'),
('God"s Little Soldier', 'Kiran Nagarkar');

app.js

'use strict';
angular.module('sendmailApp', [])
.controller('MailController', function ($scope,$http) {
$scope.loading = false;
$scope.mail = {to: 'support@codenx.com'};
$scope.send = function (mail){
$scope.loading = true;
$http.post('api/index.php', { to: mail.to }).then(res=>{
$scope.loading = false;
if(res.status===200)
$scope.serverMessage = 'Email sent with attachment';
else
$scope.serverMessage = 'Error sending email';
});
}
})

config.php

<?php
define('DATABASE_HOST', "localhost");
define('DATABASE_NAME', "demos");
define('DATABASE_USERNAME', "root");
define('DATABASE_PASSWORD', "root");
define('ATTACHED_FILENAME', "books.pdf");
define('SENDGRID_USERNAME', "YOUR_SENDGRID_USERNAME");
define('SENDGRID_PASSWORD', "YOUR_SENDGRID_PASSWORD");
define('FROM', "demo@angularcode.com");
define('TO', "support@codenx.com");
define('SUBJECT', "ShopNx - The Single Page eCommerce Website");
define('CONTENT', "
<h1>Experience faster shopping with ShopNx</h1>
<ul>
<li>Responsive Design</li>
<li>Higher Scalability</li>
<li>Ergonomically Designed</li>
</ul>");
?>

database.php

<?php
class Database {
private $host = "localhost";
private $user = "root";
private $password = "root";
private $database = "crud";
function runQuery($sql) {
$conn = new mysqli($this->host,$this->user,$this->password,$this->database);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$resultset[] = $row;
}
}
$conn->close();
if(!empty($resultset))
return $resultset;
}
}
?>

index.php

<?php
include('config.php');
include('database.php');
$email = TO;
if(isset($_POST['email'])) $email = $_POST['email'];
$database = new Database();
$result = $database->runQuery("SELECT name,author FROM books");
$header = $database->runQuery("SELECT UCASE(`COLUMN_NAME`)
FROM `INFORMATION_SCHEMA`.`COLUMNS`
WHERE `TABLE_SCHEMA`='demos'
AND `TABLE_NAME`='books'
and `COLUMN_NAME` in ('name','author')");
require('fpdf/fpdf.php');
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
foreach($header as $heading) {
foreach($heading as $column_heading)
$pdf->Cell(95,12,$column_heading,1);
}
foreach($result as $row) {
$pdf->Ln();
foreach($row as $column)
$pdf->Cell(95,12,$column,1);
}
$pdf->Output(ATTACHED_FILENAME,'F');
require('sendgrid.php');
$result = sendmail($email);
echo $result;
?>

sendgrid.php

<?php
include('config.php');
function sendmail($email){
$url = 'https://api.sendgrid.com/';
$filePath = dirname(__FILE__);
$params = array(
'api_user' => SENDGRID_USERNAME,
'api_key' => SENDGRID_PASSWORD,
'from' => FROM,
'to' => $email,
'subject' => SUBJECT,
'html' => CONTENT,
'files['.ATTACHED_FILENAME.']' => '@'.$filePath.'/'.ATTACHED_FILENAME
);
$request = $url.'api/mail.send.json';
// Generate curl request
$session = curl_init($request);
// Tell curl to use HTTP POST
curl_setopt ($session, CURLOPT_POST, true);
// Tell curl that this is the body of the POST
curl_setopt ($session, CURLOPT_POSTFIELDS, $params);
// Tell curl not to return headers, but do return the response
curl_setopt($session, CURLOPT_HEADER, false);
// Tell PHP not to use SSLv3 (instead opting for TLS)
curl_setopt($session, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1_2);
curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
// obtain response
$response = curl_exec($session);
curl_close($session);
// return the executation state
return $response;
}
?>
Subscribe my updates via Email