1 / 79

Emailing with PHP: Sending an Email, Storing Images, Getting Confirmation

Learn how to send emails using PHP, including sending multipart messages, storing images, and getting confirmation. Also covers session tracking, graphics, input validators, and cookies.

souders
Download Presentation

Emailing with PHP: Sending an Email, Storing Images, Getting Confirmation

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Unit – III emailing with PHP Sending an email – multipart message – storing images – getting confirmation. Session tracking using PHP – Graphics and Input Validators – cookies.– Open Source Programming

  2. Emailing with PHP • If you are in a *NIX environment, you will most likely have sendmail installed on your server. If you are using a hosting service, check with your service provider to make sure sendmail or some equivalent is being used. Once you have your mail server squared away, you’ll need to modify your php.ini • SMTP - Set this to the ip address or DNS name of your SMTP server. default value : localhost • sendmail_from -The From address used by default by the PHP mail() command • smtp_port- Set this to the port PHP uses to connect to the SMTP server. default value 25 Open Source Programming

  3. Email – mail() It is a function in PHP used to send an email. It returns true on success of sending an email, otherwise false. mail(to,sub,message, headers, other_parameters) (In this, the first three parameters are must. ) Where to- the receiver(s) email address(es). “,” used as delimiter to separate the addresses. Sub – subject of the mail Message – text which has to delivered to the receiver(s). Each line should be separated with a CRLF (\r\n). Lines should not be larger than 70 characters. Headers – additional parameter used 1. to include BCC & CC email address(es), 2. send the mail as multipart, and 3. contains the attachment file Other_parameters – used to display some additional information to the receiver(s). Open Source Programming

  4. Simple Mail program <? php $to=“user123@example.com”; $sub=“Test mail”; $message1 = “This is a sample test mail"; $mailsent = mail($to,$sub,$message1); If ($mailsent) echo “the mail was sent to $to successfully”; Else echo “the mail couldn’t send. Pl verify your mail settings / connection”; ?> Output: The mail was sent to user123@example.com successfully. Open Source Programming

  5. Collecting Data & Sending Email Can collect the data through HTML forms and can send an email. Should create one HTML program to collect information like to-address, subject, message from user; and one PHP program to send mail using these information. Open Source Programming

  6. Collecting Data and Sending Mail we are going to create two Web pages, mailform.html and email.php The file mailform.html will collect the data you are going to send. The file email.php will actually send the message, using the data you enter. Save the first page as mailform.html. Note that mailform.html doesn’t actually have any PHP code in it. It simply collects the required data in an HTML form. Save the second page as email.php. This second page will take the values entered into the first page, and send them in an e-mail.

  7. Email – program Email.html <html> <form action="email.php" method=“POST"> EmailId: <input type="text" name="email" size=40> <br>Subject: <input type="text" name="subject" size=40> <br>Message:<br> <textarea cols=40 rows=10 name="message"></textarea> <input type="submit" value="Send"> </form> </html> Open Source Programming

  8. email.php <?php ini_set("sendmail_from", "pradeep@vit.ac.in"); ini_set("SMTP","mail.vit.ac.in"); echo "<h1>Welcome to emailing with PHP</h1>"; echo "<br>"; $to= $_REQUEST["to"]; $subject= $_REQUEST["subject"]; $message= $_REQUEST["MESSAGE"]; $from = "pradeep@vit.ac.in"; $headers = "From:" . $from; $send=mail($to,$subject,$message,$headers); if($send) echo "congrats! The following Mail has been Sent<br><br>"; echo "<b>To:</b> $to<br>"; echo "<b>From:</b> $from<br>"; echo "<b>Subject:</b> $subject<br>"; echo "<b>Message:</b><br>"; echo $message; else echo "error in sending mail...."; ?>

  9. Running the script Load up the first page, Email.html, in your browser, and enter some data. Make sure you use valid e-mail addresses so that you can verify their receipt. Click the Send button. A second page appears, similar to the one shown below. Open your e-mail client and check your e-mail

  10. Email Program – Input earthpeople@ultimatespin.com grebnok@ultimatespin.com Hello World…. …. We will be there soon! Open Source Programming

  11. Email Program – Result Open Source Programming

  12. Receiver’s Inbox Open Source Programming

  13. Email to more addresses <? php $to=“user123@example.com, user345@example.com, aa@aa.com”; $sub=“Test mail”; $message1 = “This is a sample test mail"; $mailsent = mail($to,$sub,$message1); If ($mailsent) echo “the mail was sent to $to successfully”; Else echo “the mail couldn’t send. Pl verify your mail settings / connection”; ?> Output: The mail was sent to user123@example.com, user345@example.com, aa@aa.com successfully. Open Source Programming

  14. Email with CC & BCC The cc & bcc addresses to be included in header parameter as follows: $header=“cc: user1@example.com,user2@aa.com” Or $header=“bcc: user1@example.com,user2@aa.com” If u want to add both together, then $header =“cc: user1@example.com,user2@aa.com\r\n” $header.=“bcc: user1@example.com,user2@aa.com” Here \r\n – is the boundary between cc & bcc. It is must to use \r\n to the header, if you want to add more parameters. Open Source Programming

  15. Email – with cc <? php $to=“user123@example.com”; $sub=“Test mail”; $message1 = “This is a sample test mail"; $header = “cc:aa@aa.com, ab@aa.com”; $mailsent = mail($to,$sub,$message1,$header); If ($mailsent) echo “the mail was sent to $to and $headersuccessfully”; Else echo “the mail couldn’t send. Pl verify your mail settings / connection”; ?> Output: The mail was sent to user123@example.com cc:aa@aa.com, ab@aa.com successfully. Open Source Programming

  16. Email – with cc & Bcc <? php $to=“user123@example.com”; $sub=“Test mail”; $message1 = “This is a sample test mail"; $header = “cc:aa@aa.com, ab@aa.com\r\n”; $header .=“bcc: ac@aa.com”; $mailsent = mail($to,$sub,$message1,$header); If ($mailsent) echo “the mail was sent to $to and $headersuccessfully”; Else echo “the mail couldn’t send. Pl verify your mail settings / connection”; ?> Output: The mail was sent to user123@example.com cc:aa@aa.com, ab@aa.com bcc: ac@aa.com successfully. Open Source Programming

  17. Email – HTML messages In order to send messages as a plain text and an HTML, will use headers with additional information as follows: $headers = “MIME Version 1.0 \r\n”; $headers .= "Content-type: text/html; charset=iso-8859-1\r\n"; $headers .= "Content-Transfer-Encoding: 7bit\r\n"; Tell the e-mail client that data is coming in multiple parts—in this instance, plain text and HTML. This tells the e-mail client to look for additional “Content-type” information in the message, which includes boundary information. The boundary is what separates the multiple parts of the message. Open Source Programming

  18. Email as HTML COntent <? php $to=“user123@example.com”; $sub=“Test mail”; $message1 = “<h1>MIME mail</h1>This<br> is <br>a <br>sample <br>test <br>mail"; $headers = "MIME-Version: 1.0\r\n"; $headers .= "Content-type: text/html; charset=iso-8859-1\r\n"; $headers .= "Content-Transfer-Encoding: 7bit\r\n"; $mailsent = mail($to,$sub,$message1,$header); If ($mailsent) echo “the mail was sent to $to successfully”; Else echo “mail was not sent”; ?> Open Source Programming

  19. Email as HTML It is on receiver side Open Source Programming

  20. Multipart Messages

  21. How it Works This tells the e-mail client to look for additional “Content-type” information in the message, which includes boundary information. The boundary is what separates the multiple parts of the message. It begins with two dashes (--), and goes at the beginning of the message, between each part, and at the end. The HTML portion of our e-mail follows. Note the double dashes (--) in front of the boundary. Also note the use of two new lines (\n\n) on the Content-Transfer-Encoding line. Do not neglect those— the code will not work correctly without them. $message .= “--$boundary\n”; $message .= “Content-type: text/html; charset=iso-8859-1\n”; $message .= “Content-Transfer-Encoding: 7bit\n\n”; $message .= $messagebody . “\n”; $headers .= “Content-type: multipart/alternative; boundary=\”$boundary\”\r\n”;

  22. How it works Next is the text portion of our e-mail. Note the similarity to the HTML portion. You do not need to include the same $messagebody here. In fact, you would usually include an alternate message in text format. $message .= “--$boundary\n”; $message .= “Content-Type: text/plain; charset=\”iso-8859-1\”\n”; $message .= “Content-Transfer-Encoding: 7bit\n\n”; $message .= $messagebody . “\n”; This is the final boundary. Note the double dashes (--) at the end. This signifies that it’s the end of the e-mail. $message .= “--$boundary--”; This is used to set the boundary in our example $boundary = “==MP_Bound_xyccr948x==”;

  23. Email with an attachment • To send a email with an attachment, should do the following steps: • Step 1: Open the attach file and transfer its content to a php variable. • Step 2: Assign that file content to the message parameter of the mail function with some attributes and boundary which are needed for attachment. • Step 3: Now add the message which has to be delivered to the receiver with attributes to specify it is a message. • Note: Here, every information has to be separated with a boundary value. Open Source Programming

  24. Rb Mode • Windows offers a text-mode translation flag ('t') which will transparently translate \n to \r\n when working with the file. In contrast, you can also use 'b' to force binary mode, which will not translate your data. To use these flags, specify either 'b'or 't' as the last character of the mode parameter. • The default translation mode depends on the SAPI and version of PHP that you are using, so you are encouraged to always specify the appropriate flag for portability reasons. You should use the 't' mode if you are working with plain-text files and you use \n to delimit your line endings in your script, but expect your files to be readable with applications such as notepad. You should use the 'b' in all other cases. • If you do not specify the 'b' flag when working with binary files, you may experience strange problems with your data, including broken image files and strange problems with \r\n characters.

  25. Email – with an attachment The above steps will explain in detail with program codes 1. Open the file which has to be attached with the mail in rb mode and transfer the content into a php variable. $fileatt = "mysql-php.pdf"; // Path to the file $file = fopen($fileatt,'rb'); $data = fread($file,filesize($fileatt)); fclose($file); Set the attributes for attachment 2.1 Now add the content-type to the message as the type of attached file. $email_message = "--{$mime_boundary}\n" . "Content-Type: {$fileatt_type};\n“; Open Source Programming

  26. Email – with an attachment 2.2 Then can rename the attach file as follows: $email_message .= " name=\"{$fileatt_name}\"\n“; (here same name used, you can change the name here, if you want. ) 2.3 Add “content-disposition: attachment” – which indicates the mail is coming with an attachment. $email_message .= "Content-Disposition: attachment;\n“; 2.4 Add the transfer encoding type. $email_message .= "Content-Transfer-Encoding: base64\n\n“; 2.5 Now it is a time to add the content of the attachment file. $email_message .= $data . "\n\n“; 2.6 Add the boundary with the message as a ended one. $email_message .= "--{$mime_boundary}--\n"; Open Source Programming

  27. Email – with an attachment 3.1 Now can add message which has to send as a plain or HTML: $email_message .= “your file has been sent as an <h1>attachment </h1>to the <font color = red> user specified by you</font>”. 3.2. Now add attributes for message. $email_message .= "This is a multi-part message in MIME format.\n\n" ."--{$mime_boundary}\n" . "Content-Type:text/html; charset=\"iso-8859-1\"\n" . "Content-Transfer-Encoding: 7bit\n\n" . After all the above is done use mail() as follows: $headers = "\nMIME-Version: 1.0\n" ."Content-Type: multipart/mixed;\n" ." boundary=\"{$mime_boundary}\""; $sent=mail($to, $sub, $email_message,$headers); Open Source Programming

  28. Email with an attachment • Detail explanation about previous steps: • Collect the message and store it in a variable. • Add the boundary at the end of that message. • Enclose the content type of that message and its transfer encoding method. • Now add boundary to mark it as end of message. • Open the file which has to be attached with the mail in r+ mode and transfer the content into a php variable. • Now add the content-type to the message as the type of attached file. Open Source Programming

  29. Email with an attachment • Then set the name as the file name which has to be sent an attachment. • Add “content-disposition: attachment” – which indicates the mail is coming with an attachment. • Can add the rename option of the attached file. • Add the transfer encoding type. • Now it is a time to add the content of the attachment file. • Add the boundary with the message as a ended one. Open Source Programming

  30. Chunk_split • The chunk_split() function splits a string into a series of smaller parts. • Syntax • chunk_split(string,length,end) ParameterDescription • string Required. Specifies the string to split • Length Optional. A number that defines the length of the chunks. Default is 76 • endOptional. A string that defines what to place at the end of each chunk. Default is \r\n Note: This function does not alter the original string.

  31. Sample program The following slides show the sample email program with an attachment <?php /* IMAGE ATTACHMENT $fileatt = "test1.jpg"; // Path to the file $fileatt_type = "image/jpg"; // File Type $fileatt_name = "test1.jpg"; // Filename that will be used for the file as the attachment */ //TEXT ATTACHMENT $fileatt = "MYSQL-PHP.pdf"; // Path to the file $fileatt_type = "application/pdf"; // File Type $fileatt_name = "PHPebook.pdf"; // Filename that will be used for the file as the attachment Open Source Programming

  32. Sample program (cont) // READ THE FILE $file = fopen($fileatt,'r+'); $data = fread($file,filesize($fileatt)); fclose($file); // ENCODE THE FILE WHICH HAS TO ATTACH $data = chunk_split(base64_encode($data)); // ASSIGNING ADDRESSES, SUBJECT & MESSAGE $email_from = “xxxxxx@vit.ac.in"; // Who the email is from //$email_subject = "image file attached"; // The Subject of the email $email_subject= "PHP book attached as a pdf file"; $email_message = "Thanks for visiting mysite.com! Here is your free file.<br>"; $email_message .= "Thanks for visiting.<br>"; // Message that the email has in it $email_to = “xxxxxxx@vit.ac.in"; // Who the email is to Open Source Programming

  33. Sample program (cont) //CREATE HEADER FOR MULTIPART MESSAGE $headers = "From: ".$email_from; $semi_rand = md5(time()); $mime_boundary = "==Multipart_Boundary_x{$semi_rand}x"; $headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"{$mime_boundary}\""; // DEFINING MESSAGE TYPE $email_message .= "This is a multi-part message in MIME format.\n\n" . "--{$mime_boundary}\n" . "Content-Type:text/html; charset=\"iso-8859-1\"\n" . "Content-Transfer-Encoding: 7bit\n\n" . $email_message .= "\n\n"; Open Source Programming

  34. Sample program (cont) //ATTACHING THE FILE $email_message .= "--{$mime_boundary}\n" . "Content-Type: {$fileatt_type};\n" . " name=\"{$fileatt_name}\"\n" . "Content-Disposition: attachment;\n" . " filename=\"{$fileatt_name}\"\n" . "Content-Transfer-Encoding: base64\n\n" . $data .= "\n\n" . "--{$mime_boundary}--\n"; //SEND MAIL $ok = @mail($email_to, $email_subject, $email_message, $headers); Open Source Programming

  35. Sample program (cont) // check the mail was sent or not if($ok) { echo "Your file has been sent<br> to the email address you specified.<br> Make sure to check your junk mail!<br> } Else { die("Sorry but the email could not be sent. Please go back and try again!"); } ?> Open Source Programming

  36. Output at Client Side Open Source Programming

  37. Receivers Inbox Open Source Programming

  38. Storing Images Create a database named as postcard and create a table, images consisting of three fields, imageid, imageurl, imagedes. That table stores the image details. For this, all the images should be stored in a folder called postcards. The following programs explain it. DBcreation.php <?php //Connect to the server using the correct username and password. $conn = mysql_connect(“yourserver”, “joeuser”, “yourpass”); /*Create the database. Call it “postcard.” If it is successful, print “Database created” to the screen and move on. */ $sql = “CREATE DATABASE postcard”; $success = mysql_query($sql, $conn) or die(mysql_error()); Echo “Database created. . .”; ?> Open Source Programming

  39. Storing Images (cont) Create a program to connect with database DBconnect.php <?php $conn = mysql_connect(“yourserver”, “joeuser”, “yourpass”); mysql_select_db(“postcard”, $conn); ?> Create the images table in the database, containing three columns. Createtable.php <?php require(“dbconnect.php”); //imports the db connection prg. $sql = “CREATE TABLE images (id int NOT NULL primary key auto_increment, img_url VARCHAR (255) NOT NULL, img_desc text )”; $success = mysql_query($sql, $conn) or die(mysql_error()); echo “‘images table created. . .” ?> Open Source Programming

  40. Storing Images (cont) Create two arrays, to store image url and image description. Then insert those values into the images table storeimages.php <?php require(“dbconnect.php”); //Now create two arrays of values to place in the images table. $imgURL = array(‘/postcards/punyearth.gif’, ‘/postcards/grebnok.gif’, ‘/postcards/sympathy.gif’, ‘/postcards/congrats.gif’); $imgDESC = array(‘Wish you were here!’, ‘See you soon!’, ‘Our Sympathies’, ‘Congratulations!’); //Loop through the arrays, pulling the location and description text and inserting them into the images table. for ($i=0; $i<4; $i++) { $sql = “INSERT INTO images ( images.img_url , images.img_desc ) VALUES ( ‘$imgURL[$i]’, $imgDESC[$i]’)”; $success = mysql_query($sql, $conn) or die(mysql_error()); } Echo “Data entered. . .”; ?> Open Source Programming

  41. Getting Confirmation • It is quite easy for the user to use any e-mail address in the “From” field. This is a bad thing because nasty e-mails can be sent on someone else’s behalf. • In order to prevent such maliciousness, you must first send a confirmation e-mail to the “From” address. • Once you get the confirmation, you know the user entered a good e-mail address, and you can go ahead and send the e-mail. This will explain with the following screen shots. Open Source Programming

  42. Getting Confirmation Create a PHP program to collect the following information Open Source Programming

  43. Getting Confirmation Send the selected card & message to from address to get confirmation. Open Source Programming

  44. Getting Confirmation Click here to confirm Now the user gives confirmation by using the link given below. Can send the mail to address in ‘to’ field, if receives confirmation. Open Source Programming

  45. Cookies • A cookie is a small piece of information that a Web server can store through your Web browser on to your hard disk when you visit the corresponding site. The Web server can also retrieve this information later when you visit the same site next time. • When you visit a cookie-enabled Web site, you might need to log in to the site or register using a password and other relevant information. This information is stored into a small text file whose maximum size is 4 KB. • This file is referred to as a cookie and contains the relevant user-related information, such as User ID, password, list of pages that the user visited, and the date the user last visited a page. Open Source Programming

  46. Why Cookie Internet is based on Hypertext Transfer Protocol (HTTP), which is a stateless protocol. This implies that once a transaction between the client machine and the Web server is finished, the Web server loses all the memory regarding the transaction. Maintaining the state between your subsequent visits to a Web page prevent loss of sensitive data Open Source Programming

  47. Use of Cookies • To determine how many users visit the given Web site and how often • For storing details of the users who visit the site or register on the Web site. • Allowing users to customize the interface (such as layout and colors) as per their liking. • To prevent repetitive logins, thus making the login process faster. In addition, since the cookie is stored at the client end, the Web server need not be burdened each time a user needs to log in to the site. The server only needs to authenticate the first-time users. • For tracking a user's path and activities on a given Web site. This feature allows the Web administrators to track miscreants. • For generating individual user profiles. For example, some sites display personalized messages to their users when they log in to the site. • For storing the items selected by the site users in their respective shopping carts. Open Source Programming

  48. How does a Cookie work? No Yes ->Updates cookie value No -> Creates new cookie Open Source Programming

  49. How does a Cookie work? • When you type the URL of the destination Web site in the Address bar of your browser, the address is located and if found successfully, a request is sent to the Web server that hosts the site. If the Web server accepts the request, the Web browser at the client end checks for an existing cookie from the given site. • If the cookie is found, the browser sends all the name-value pairs in the cookie to the server as the HTTP header. In addition, the expiration date of the cookie, if any, and a path is also sent to the server along with the name-value pairs. • If the corresponding cookie is not found on the local hard disk, the server is notified about the absence of a cookie. In this case, the server generates a new ID for the client who requested a connection and sends the cookie containing the name-value pair(s) to the requester's Web browser. The browser then stores this cookie on the hard disk of your machine. Open Source Programming

More Related