Sunteți pe pagina 1din 8

Send email with PDF attachment using PHP

angularcode.com/send-pdf-attachment-email-using-php/

09/04/2016

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 DemoDownload

For this we will use

1. AngularJS [For front end]


2. PHP [To query the database and send email]
3. MySQL [The database]
4. fPDF library [This will generate the PDF for us]
5. SendGrid [This helps us sending the email in a better way]

Project Structure
api

cong.php

database.php

sendgrid.php

index.php

1/8
index.html
app.js

code

index.html

1 lang="en">
2 http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
3 name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0"/>
4 Send email using NodeJS
5
6
7 href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
8 href="https://cdnjs.cloudare.com/ajax/libs/materialize/0.97.5/css/materialize.min.css" type="text/css"
9 rel="stylesheet" media="screen,projection"/>
10 href="css/style.css" type="text/css" rel="stylesheet" media="screen,projection"/>
11 ng-app="sendmailApp" ng-controller="MailController">
12
13 class="light-blue lighten-1" role="navigation">
14 class="nav-wrapper container">id="logo-container" href="http://www.angularcode.com/" class="brand-
15 logo">AngularCode | Demo
16 class="right">
17 class="dropdown-button" href="http://www.angularcode.com/send-email-from-website-using-
18 angularjs-and-nodejs"
19 data-activates="dropdown1">Tutorialclass="material-icons left">airplay
20
21
22
23
24
25
26 class="section no-pad-bot valign-wrapper">
27 class="container">
28
29
30 class="center">class="material-icons center large">attachment
31 class="header green-text">Send me the le as attachment
32
33 class="center success">
34 class="preloader-wrapper small active" ng-if="loading">
35 class="spinner-layer spinner-green-only">
36 class="circle-clipper left">
37 class="circle">
38 class="gap-patch">
2/8
39 class="circle">
40 class="circle-clipper right">
41 class="circle">
42
43
44
45 ng-cloak ng-if="!loading && serverMessage">class="material-icons center">done{{serverMessage}}
46
47 class="row center">
48 class="input-eld col s12 z-depth-2" >
49 ng-model="mail.to" class="materialize-text" placeholder="support@codenx.com">
50
51
52 class="row center">
53 ng-click="send(mail)" class="btn-large waves-eect waves-light green" ng-
54 disabled="loading">class="material-icons left">send
55 class="circle">Send Mail
56
57
58
59
60
61
62
63 class="page-footer orange">
64 class="footer-copyright">
65 class="container center">
66 Crafted by class="orange-text text-lighten-3" href="http://angularcode.com">AngularCode
67
68
69
70
71
72 type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.2/angular.min.js">
73 type="text/javascript" src="app.js">
74
Status API Training Shop Blog About
2016 GitHub, Inc. Terms Privacy Security Contact Help

books.sql

3/8
1 --
2 -- Table structure for table `books`
3 --
4
5 CREATE TABLE IF NOT EXISTS `books` (
6 `name` varchar(255) DEFAULT NULL,
7 `author` varchar(255) DEFAULT NULL
8 ) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8;
9
10 --
11 -- Dumping data for table `books`
12 --
13
14 INSERT INTO `books` (`name`,`author`) VALUES
15 ('What young India wants', 'Chetan Bhagat'),
16 ('Two States', 'Chetan Bhagat'),
17 ('The hunger games', 'Suzanne Collions'),
18 ('The 3 mistakes of my life' , ' Chetan Bhagat'),
19 ('Serious Men', ' Manu Joseph'),
20 ('Revolution 2020', ' Chetan Bhagat'),
21 ('God"s Little Soldier', 'Kiran Nagarkar');

app.js

1 'use strict';
2
3 angular.module('sendmailApp', [])
4 .controller('MailController', function ($scope,$http) {
5 $scope.loading = false;
6 $scope.mail = {to: 'support@codenx.com'};
7 $scope.send = function (mail){
8 $scope.loading = true;
9 $http.post('api/index.php', { to: mail.to }).then(res=>{
10 $scope.loading = false;
11 if(res.status===200)
12 $scope.serverMessage = 'Email sent with attachment';
13 else
14 $scope.serverMessage = 'Error sending email';
15 });
16 }
17 })

4/8
cong.php

1 dene('DATABASE_HOST', "localhost");
2 dene('DATABASE_NAME', "demos");
3 dene('DATABASE_USERNAME', "root");
4 dene('DATABASE_PASSWORD', "root");
5 dene('ATTACHED_FILENAME', "books.pdf");
6 dene('SENDGRID_USERNAME', "YOUR_SENDGRID_USERNAME");
7 dene('SENDGRID_PASSWORD', "YOUR_SENDGRID_PASSWORD");
8 dene('FROM', "demo@angularcode.com");
9 dene('TO', "support@codenx.com");
10 dene('SUBJECT', "ShopNx - The Single Page eCommerce Website");
11 dene('CONTENT', "
12
13
14 Experience faster shopping with ShopNx
15
16
17
18
19 Responsive Design

Higher Scalability

Ergonomically Designed
");
?>

database.php

5/8
1 include('cong.php');
2 class Database {
3 function runQuery($sql) {
4 $conn = new
5 mysqli(DATABASE_HOST,DATABASE_USERNAME,DATABASE_PASSWORD,DATABASE_NAME);
6 if ($conn->connect_error) {
7 die("Connection failed: " . $conn->connect_error);
8 }
9 $result = $conn->query($sql);
10 if ($result->num_rows > 0) {
11 while($row = $result->fetch_assoc()) {
12 $resultset[] = $row;
13 }
14 }
15 $conn->close();
16 if(!empty($resultset))
17 return $resultset;
18 }
19 }
20 ?>

index.php

6/8
1 include('cong.php');
2 include('database.php');
3 $email = TO;
4 if(isset($_POST['email'])) $email = $_POST['email'];
5 $database = new Database();
6 $result = $database->runQuery("SELECT name,author FROM books");
7 $header = $database->runQuery("SELECT UCASE(`COLUMN_NAME`)
8 FROM `INFORMATION_SCHEMA`.`COLUMNS`
9 WHERE `TABLE_SCHEMA`='demos'
10 AND `TABLE_NAME`='books'
11 and `COLUMN_NAME` in ('name','author')");
12 require('fpdf/fpdf.php');
13 $pdf = new FPDF();
14 $pdf->AddPage();
15 $pdf->SetFont('Arial','B',16);
16 foreach($header as $heading) {
17 foreach($heading as $column_heading)
18 $pdf->Cell(95,12,$column_heading,1);
19 }
20 foreach($result as $row) {
21 $pdf->Ln();
22 foreach($row as $column)
23 $pdf->Cell(95,12,$column,1);
24 }
25 $pdf->Output(ATTACHED_FILENAME,'F');
26 require('sendgrid.php');
27 $result = sendmail($email);
28 echo $result;
29 ?>
30 Status API Training Shop Blog About
31 2016 GitHub, Inc. Terms Privacy Security Contact Help
32

sendgrid.php

7/8
1 include('cong.php');
2 function sendmail($email){
3 $url = 'https://api.sendgrid.com/';
4 $lePath = dirname(__FILE__);
5 $params = array(
6 'api_user' => SENDGRID_USERNAME,
7 'api_key' => SENDGRID_PASSWORD,
8 'from' => FROM,
9 'to' => $email,
10 'subject' => SUBJECT,
11 'html' => CONTENT,
12 'les['.ATTACHED_FILENAME.']' => '@'.$lePath.'/'.ATTACHED_FILENAME
13 );
14 $request = $url.'api/mail.send.json';
15 // Generate curl request
16 $session = curl_init($request);
17 // Tell curl to use HTTP POST
18 curl_setopt ($session, CURLOPT_POST, true);
19 // Tell curl that this is the body of the POST
20 curl_setopt ($session, CURLOPT_POSTFIELDS, $params);
21 // Tell curl not to return headers, but do return the response
22 curl_setopt($session, CURLOPT_HEADER, false);
23 // Tell PHP not to use SSLv3 (instead opting for TLS)
24 curl_setopt($session, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1_2);
25 curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
26 // obtain response
27 $response = curl_exec($session);
28 curl_close($session);
29 // return the executation state
30 return $response;
31 }
32 ?>
33

8/8

S-ar putea să vă placă și