Oke, this is a tricky one. (I think).
Do you know when you receive a message and the email has a image on top or on the bottom of the page.
I have been trying to make it but can't figure it out.
I hope you guy's can help me with this problem.
This is what I got so far;
<?php
$to = 'info#gmail.com';
if(isset($_POST['submit']))
{
$name = $_POST['name'];
$gast = $_POST['email'];
$tmpName = $_FILES['attachment']['tmp_name'];
$fileType = $_FILES['attachment']['type'];
$fileName = $_FILES['attachment']['name'];
if(empty($errors))
{
$to = $to;
$from = $gast;
$file = fopen($tmpName,'rb');
$data = fread($file,filesize($tmpName));
fclose($file);
$mimeBoundary = "==Multipart_Boundary_x{$randomVal}x";
$body = "E-mail".
"Name: $name\n".
"Email: $gast \n".
"Content-Type: {$fileType};\n".
"Content-Transfer-Encoding: base64\n\n".
$data;
$headers = "From: $from \r\n";
$headers .= "Email: $gast \r\n";
$headers .= "\nMIME-Version: 1.0\n";
$headers .= "Content-Type: multipart/alternative;\n";
$headers .= " boundary=\"{$mimeBoundary}\"";
$headers .= "img src='http://cache.estivant.nl/image/1399025430_12_banners-bestemmingen-single-1680x460-extra2-06-kos_1399025430.jpg' alt='image'";
$data = chunk_split(base64_encode($data));
mail($to, $body, $headers);
}
}
?>
<html>
<head></head>
<body>
<form method="post" action="">
<label for="name">name</label>
<input type="name" name="name" value="" />
<label for="email">email</label>
<input type="email" name="email" value="" />
<button id="submit" name="submit">send</button>
</form>
</body>
</html>
Simply write a html page with css styles and format your email accordingly and use the html as your email body. This will create an image in the mail
<img src="image.jpg" alt="image"></img>
Please be aware that most (if not all) email clients will block your image from being showed to your receiver as long as you are not in their trusted sender list or contact list.
Of course, your email has to be sent as html
Here is an example of a nicely formatted email with images.
Note image syntax: <img src="http://css-tricks.com/examples/WebsiteChangeRequestForm/images/wcrf-header.png" alt="Website Change Request" />'
$to = 'bob#example.com';
$subject = 'Website Change Request';
$headers = "From: " . strip_tags($_POST['req-email']) . "\r\n";
$headers .= "Reply-To: ". strip_tags($_POST['req-email']) . "\r\n";
$headers .= "CC: susan#example.com\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$message = '<html><body>';
$message .= '<img src="http://css-tricks.com/examples/WebsiteChangeRequestForm/images/wcrf-header.png" alt="Website Change Request" />';
$message .= '<table rules="all" style="border-color: #666;" cellpadding="10">';
$message .= "<tr style='background: #eee;'><td><strong>Name:</strong> </td><td>" . strip_tags($_POST['req-name']) . "</td></tr>";
$message .= "<tr><td><strong>Email:</strong> </td><td>" . strip_tags($_POST['req-email']) . "</td></tr>";
$message .= "<tr><td><strong>Type of Change:</strong> </td><td>" . strip_tags($_POST['typeOfChange']) . "</td></tr>";
$message .= "<tr><td><strong>Urgency:</strong> </td><td>" . strip_tags($_POST['urgency']) . "</td></tr>";
$message .= "<tr><td><strong>URL To Change (main):</strong> </td><td>" . $_POST['URL-main'] . "</td></tr>";
$addURLS = $_POST['addURLS'];
if (($addURLS) != '') {
$message .= "<tr><td><strong>URL To Change (additional):</strong> </td><td>" . strip_tags($addURLS) . "</td></tr>";
}
$curText = htmlentities($_POST['curText']);
if (($curText) != '') {
$message .= "<tr><td><strong>CURRENT Content:</strong> </td><td>" . $curText . "</td></tr>";
}
$message .= "<tr><td><strong>NEW Content:</strong> </td><td>" . htmlentities($_POST['newText']) . "</td></tr>";
$message .= "</table>";
$message .= "</body></html>";
mail($to,$subject,$message,$headers);
Code source and full explanation: http://css-tricks.com/sending-nice-html-email-with-php/
Related
I have made a contact form with the following fields: Name, Email, Message. It all worked fine - messages were sent to my email - until I added the attachments option to the form.
I've tried validating the attachment fields by searching up tutorials, but nothing seems to work. I guess I'm just not sure how to implement it to my already existing code.. Any help here?
Here is the form:
<?php include 'contact-form.php'; ?>
<form id="contact" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data">
<h3>Contact Us</h3>
<fieldset>
<input placeholder="Nimi" type="text" tabindex="1" name="thename" value="<?= $thename ?>" autofocus>
<div class="error"><span><?= $name_error ?></span></div>
</fieldset>
<fieldset>
<input placeholder="Email" type="text" tabindex="2" name="email" value="<?= $email ?>">
<div class="error"><span><?= $email_error ?></span></div>
</fieldset>
<fieldset>
<textarea placeholder="Sisesta sõnum siia.." type="text" tabindex="3" name="message"></textarea>
<div class="error"><span><?= $message_error ?></span></div>
</fieldset>
<fieldset>
<label for="attachment1">File:</label> <input type="file" id="attachment1" name="attachment[]" size="35">
<label for="attachment2">File:</label> <input type="file" id="attachment2" name="attachment[]" size="35">
<div class="error"><span><?= $attachment_error ?></span></div>
</fieldset>
<fieldset>
<button name="submit" type="submit" id="contact-submit" data-submit="...Saatmine">Saada</button>
</fieldset>
<div class="success"><?= $success; ?></div>
<div class="error"><?= $error; ?></div>
</form>
Here is PHP validation code contact-form.php:
<?php
$name_error = $email_error = $message_error = $attachment_error = "";
$thename = $email = $message = $success = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["thename"])) {
$name_error = "Palun sisesta nimi";
} else {
$thename = test_input($_POST["thename"]);
// check if name only contains letters, whitespace and hyphen
if (!preg_match("/^[a-zA-Z -]*$/",$thename)) {
$name_error = "Sisestada saab ainult tähti, tühikuid ja sidekriipse";
}
}
if (empty($_POST["email"])) {
$email_error = "Palun sisesta email";
} else {
$email = test_input($_POST["email"]);
// email validation
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$email_error = "Sisesta email korrektselt";
}
}
if (empty($_POST["message"])) {
$message_error = "Palun sisesta sõnum";
} else {
$message = test_input($_POST["message"]);
}
if (empty($_FILES["attachment"])) {
$attachment_error = "Palun sisesta enda eluloo fail";
}
if ($name_error == '' and $email_error == '' and $message_error == '' ){
$message_body = '';
unset($_POST['submit']);
foreach ($_POST as $key => $value){
$message_body .= "$key: $value\n";
}
$to = 'myemail#gmail.com';
$subject = 'Eesti Elulood';
$message = "Sulle saadeti kiri Rannu koguduse kodulehelt.\n\nSaatja nimi: $thename\n\nSaatja email: $email\n\nSõnum: $message";
// create email headers
$headers = 'From: '.$email."\r\n".
'Reply-To: '.$email."\r\n" .
'X-Mailer: PHP/' . phpversion();
if (isset($_FILES['attachment']['name'])) {
$semi_rand = md5(uniqid(time()));
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
$headers = "From: " . '=?UTF-8?B?' . base64_encode($thename) . '?=' . "
<$email>" . PHP_EOL;
$headers .= "Reply-To: " . '=?UTF-8?B?' . base64_encode($thename) . '?=' .
" <$email>" . PHP_EOL;
$headers .= "Return-Path: $email" . PHP_EOL;
$headers .= "MIME-Version: 1.0" . PHP_EOL;
$headers .= "Content-Type: multipart/mixed;" . PHP_EOL;
$headers .= " Boundary=\"{$mime_boundary}\"";
$datamsg = "This is a multi-part message in MIME format." . PHP_EOL .
PHP_EOL;
$datamsg .= "--{$mime_boundary}" . PHP_EOL;
$datamsg .= "Content-Type: text/plain; Charset=\"UTF-8\"" . PHP_EOL;
$datamsg .= "Content-Transfer-Encoding: 8bit" . PHP_EOL . PHP_EOL;
$datamsg .= $message . PHP_EOL . PHP_EOL;
for ($index = 0; $index < count($_FILES['attachment']['name']); $index++)
{
if ($_FILES['attachment']['name'][$index] != "") {
$file_name = $_FILES['attachment']['name'][$index];
$data_file =
chunk_split(base64_encode(file_get_contents($_FILES['attachment']
['tmp_name'][$index])));
$datamsg .= "--{$mime_boundary}" . PHP_EOL;
$datamsg .= "Content-Type: application/octet-stream; Name=\"
{$file_name}\"" . PHP_EOL;
$datamsg .= "Content-Disposition: attachment; Filename=\"{$file_name}\"" . PHP_EOL;
$datamsg .= "Content-Transfer-Encoding: base64" . PHP_EOL . PHP_EOL .
$data_file . PHP_EOL . PHP_EOL;
}
}
$datamsg .= "--{$mime_boundary}--";
}
if (#mail($to, '=?UTF-8?B?' . base64_encode($subject) . '?=',
$datamsg, $headers, "-f$email")){
$success = "Thankyou, message sent!.";
} else {
$error = "Sorry but the email could not be sent. Please try again!";
}
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
After hitting the submit button, It just takes me to the index.php page..
Any help is appreciated!
1) You have no mail attachments code into your php code except for the html markup, so you cannot send your mail attachments.
2) You have to encode the attachments using chunk_split(base64_encode()) and then you have to import them into your message part using the correct way.
3) You forgot to enter the correct headers, that's the other reason why you can't send your mails.
4) You have to consider that if you use GMail there may be a limit to the type of file you can send and so read this: https://support.google.com/mail/answer/6590?hl=en
5) I suggest you to use the long php tag instead the short tag:
Instead of writing <?= $_SERVER['PHP_SELF']; ?>, write <?php echo $_SERVER['PHP_SELF']; ?>
6) You have a serious error into your php and this is the reason why pressing submit you are in the home instead of your contact form:
<?= $SERVER['PHP_SELF']; ?> is wrong!
<?= $_SERVER['PHP_SELF']; ?> is correct!
See you point 5)
Here is an example of correct html markup for attachments:
<label for="attachment1">File:</label> <input type="file" id="attachment1" name="attachment[]" size="35">
<label for="attachment2">File:</label> <input type="file" id="attachment2" name="attachment[]" size="35">
<label for="attachment3">File:</label> <input type="file" id="attachment3" name="attachment[]" size="35">
Here is an example of correct php mail code for attachments:
if (isset($_FILES['attachment']['name'])) {
$semi_rand = md5(uniqid(time()));
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
$headers = "From: " . '=?UTF-8?B?' . base64_encode($sender_name) . '?=' . " <$from_email>" . PHP_EOL;
$headers .= "Reply-To: " . '=?UTF-8?B?' . base64_encode($sender_name) . '?=' . " <$from_email>" . PHP_EOL;
$headers .= "Return-Path: $from_email" . PHP_EOL;
$headers .= "MIME-Version: 1.0" . PHP_EOL;
$headers .= "Content-Type: multipart/mixed;" . PHP_EOL;
$headers .= " Boundary=\"{$mime_boundary}\"";
$datamsg = "This is a multi-part message in MIME format." . PHP_EOL . PHP_EOL;
$datamsg .= "--{$mime_boundary}" . PHP_EOL;
$datamsg .= "Content-Type: text/plain; Charset=\"UTF-8\"" . PHP_EOL;
$datamsg .= "Content-Transfer-Encoding: 8bit" . PHP_EOL . PHP_EOL;
$datamsg .= $message . PHP_EOL . PHP_EOL;
for ($index = 0; $index < count($_FILES['attachment']['name']); $index++) {
if ($_FILES['attachment']['name'][$index] != "") {
$file_name = $_FILES['attachment']['name'][$index];
$data_file = chunk_split(base64_encode(file_get_contents($_FILES['attachment']['tmp_name'][$index])));
$datamsg .= "--{$mime_boundary}" . PHP_EOL;
$datamsg .= "Content-Type: application/octet-stream; Name=\"{$file_name}\"" . PHP_EOL;
$datamsg .= "Content-Disposition: attachment; Filename=\"{$file_name}\"" . PHP_EOL;
$datamsg .= "Content-Transfer-Encoding: base64" . PHP_EOL . PHP_EOL . $data_file . PHP_EOL . PHP_EOL;
}
}
$datamsg .= "--{$mime_boundary}--";
}
if (#mail($recipient_email, '=?UTF-8?B?' . base64_encode($subject) . '?=', $datamsg, $headers, "-f$from_email")) {
exit("Files Sent Successfully");
} else {
exit("Sorry but the email could not be sent. Please go back and try again!");
}
Where $sender_name is the name of sender, $from_email is the email of sender, $recipient_email is the recipient of your email.
You can take an example from my code and integrate it into your project, I wrote only the essential parts concerning the sending of attachments.
I hope this helps.
while sending a mail using PHP mail() without attachment working fine.
But while sending with attachment sending Failed
please help me.
Whats wrong in my code?
Thanks in advance.
My HTML code is shown below
index.html
<html>
<head>
<title>Mail</title>
</head>
<body>
<form method="POST" action="mail.php" enctype="multipart/form-data">
<input type="text" name="fromName">
<input type="email" name="fromEmail">
<input type="file" name="fileAttach">
<input type="submit" name="submit">
</form>
</body>
</html>
The following is my Mail code
mail.php
<?php
if (isset($_POST['submit'])) {
/* $mailto = $_POST["mailTo"];*/
$mailto = "to#gmail.com";
$from_mail = $_POST["fromEmail"];
$replyto = $_POST["fromEmail"];
$from_name = $_POST["fromName"];
/*$message = $_POST["message"];*/
$message="This is message part";
/*$subject = $_POST["subject"];*/
$subject ="this is subject part";
$filename = $_FILES["fileAttach"]["name"];
$content = chunk_split(base64_encode(file_get_contents($_FILES["fileAttach"]["tmp_name"])));
$uid = md5(uniqid(time()));
$name = basename($file);
$header = "From: " . $from_name . " <" . $from_mail . ">\r\n";
$header .= "Reply-To: " . $replyto . "\r\n";
$header .= "MIME-Version: 1.0\r\n";
$header .= "Content-Type: multipart/mixed; boundary=\"" . $uid . "\"\r\n\r\n";
$header .= "This is a multi-part message in MIME format.\r\n";
$header .= "--" . $uid . "\r\n";
// You add html "Content-type: text/html; charset=utf-8\n" or for Text "Content-type:text/plain; charset=iso-8859-1\r\n" by I.khan
$header .= "Content-type:text/html; charset=utf-8\n";
$header .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
// User Message you can add HTML if You Selected HTML content
$header .= "<div style='color: red'>" . $message . "</div>\r\n\r\n";
$header .= "--" . $uid . "\r\n";
$header .= "Content-Type: application/octet-stream; name=\"" . $filename . "\"\r\n"; // use different content types here
$header .= "Content-Transfer-Encoding: base64\r\n";
$header .= "Content-Disposition: attachment; filename=\"" . $filename . "\"\r\n\r\n"; // For Attachment
$header .= $content . "\r\n\r\n";
$header .= "--" . $uid . "--";
if (mail($mailto, $subject, $message, $header)) {
echo "<script>alert('Success');</script>"; // or use booleans here
} else {
//echo mysqli_error();
echo "<script>alert('Failed');</script>";
}
}
Is there anything to add or change in the code?
<?php
//if there is post
if(isset($_POST) && !empty($_POST)){
//if there is attachment
if(!empty($_FILES['attachment']['name'])){
//store some variables
$file_name = $_FILES['attachment']['name'];
$temp_name = $_FILES['attachment']['tmp_name'];
$file_type = $_FILES['attachment']['type'];
//get the extension of the file
$base = basename($file_name);
$extension = substr($base, strlen($base)-4,strlen($base));
//only these file type will be allowed
$allow_extensions = array(".doc","docx",".pdf",".zip",".png");
//check if file is allowes
if(in_array($extension,$allow_extensions)){
//mail essentials
$from = $_POST['email'];
$to = "sampleemail#gmail.com";
$replyto = $to;
$subject = "email with attachment";
$message = "this is a random message";
//things you need
$file = $temp_name;
$content = chunk_split(base64_encode(file_get_contents($file)));
$uid = md5(uniqid(time()));
//standard mail headers
$header = "From " . $from . "\r\n";
$header .= "Reply-To: " . $replyto . "\r\n";
$header .= "MIME-Version: 1.0\r\n";
//declairing we hav e multiple parts of message like text
$header .= "Content-Type: multipart/mixed; boundary=\"".$uid."\"\r\n\r\n";
$header .= "This is a multi-part message in MIME format. \r\n";
//plain text part
$header .= "--".$uid."\r\n";
$header .= "Content-type:text/plain; charset=iso-8859-1\r\n";
$header .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
$header .= $message."\r\n\r\n";
//file attachment
$header .= "--".$uid."\r\n";
$header .= "Content-Type: ".$file_type."; name=\"".$file_name."\"\r\n";
$header .= "Content-Transfer-Encoding: base64\r\n";
$header .= "Content-Disposition: attachment; filename=\"".$file_name."\"\r\n\r\n";
$header .= $content. "\r\n\r\n";
//send mail
if(mail($to, $subject, "", $header)){
echo "Mail Sent";
}
else
{
echo "Failed";
}
}
else{
echo "file type not allowed";
}
}
else{
echo "no file posted";
}
}
?>
<html>
<head>
</head>
<body>
<form method="post" action="index.php" enctype="multipart/form-data">
<input type="text" name="email" value="from" />
<br>
<input type="file" name="attachment" />
<br>
<input type="submit" value="Send Mail" />
</form>
</body>
</html>
Can't find the bug to my code, I am not getting the link to my attachment.. T_T please help. I am not good in boundary.. T_T I tried using phpmailer but can't get it to work, is there any document to read on how to set it up? I really just wanted to make a simple form with attach button for applicant to sent their resumes..
Everything after $header .= "Content-Type: multipart/mixed; boundary=\"".$uid."\"\r\n\r\n"; should be in a $body, not a header.
I would get rid of this: $header .= "This is a multi-part message in MIME format. \r\n";
After $content you actually need to put another line with the mime separator.
$body .= $content . "\r\n" . '--' . $uid . '--';
And finally
if (mail($to, $subject, $body, $header)) {...
mailPlease help. My PHP mailer is not working that I host on Go Daddy. Any idea why the email won't send?
<?php
session_start();
$contact=$_POST['contact'];
$phone=$_POST['telephone'];
$email=$_POST['email'];
$msg=$_POST['message'];
$to="webform#xxx.com";
$subject="Contact Form";
$from=$email;
$message .= '<table border="1px" width="50%" style="border:1px black solid;margin:0px auto">';
$message .= '<tr><th colspan="2" style="text-align:center">Contacts Information</th></tr>';
$message .= '<tr><td>Name :- </td><td>'.$contact.'</td></tr>';
$message .='<tr> <td>Phone No. :- </td><td>'.$phone.'</td></tr>';
$message .= "<tr><td>Email :- </td><td>" . $email . "</td></tr>";
$message .= "<tr><td>Message :- </td><td>" . $msg. "</td></tr>";
$message .= "</table>";
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
$headers .= 'From: ' . $from . "\r\n";
mail($to, $subject, $message, $headers);
header("Location: sent.html");
Their is a typo error in your code.
$contact=$_POST['contact'];
$phone=$_POST['telephone'];
$email=$_POST['email'];
$msg=$_POST['message'];
$to="webform#xxx.com";
$subject="Contact Form";
$from=$enm; //this should be $from=$email
CAUTION: ur not validating user input. Pls do validate them server side to avoid errors and attack attempts.
If u have any other error pls state it clearly.
I’m fairly new and basically using examples and tutorials I’ve seen on the web. Any help would be appreciated.
I’ve got a simple web form to email with an HTML table.
It won’t send the body of the message and it won’t send the message at all unless I use $email_body rather than $message.
HTML Form:
<section class="left">
<form name="input" action="appointment.php" method="post">
<p>Name:</p> <input name="name" type="text"/><br><br>
<p>Email:</p> <input name="email" type="text"/><br><br>
<p>Issue:</p>
<textarea name="issue" rows="4" cols="50">Keep it brief..
</textarea>
</section>
<section class="right">
<p><u>Preferred Time(s):</u></p><br><br>
<p><input type="radio" name="checkmorning" value="Available">Morning (8:30-9:55)</p><br><br>
<p><input type="radio" name="checklunch" value="Available">Lunchtime</p><br><br>
<p><input type="radio" name="checkafter" value="Available">After School(3:10-3:45)</p><br><br>
<input type="submit" value="Submit">
</section>
</form>
PHP:
<?php
$name = $_POST['name'];
$visitor_email = $_POST['email'];
$issue = $_POST['issue'];
$checkmorning = $_POST['checkmorning'];
$checklunch = $_POST['checklunch'];
$checkafter = $_POST['checkafter'];
$email_from = '*****#gmail.com';//<== update the email address
$email_subject = "New Order submission";
$email_body = '<html><body>';
$message .= '<img src="*******" alt="New Appointment" />';
$message .= '<table rules="all" style="border-color: #666;" cellpadding="10">';
$message .= "<tr style='background: #eee;'><td><strong>Name:</strong> </td><td>" . strip_tags($_POST['name']) . "</td></tr>";
$message .= "<tr><td><strong>Email:</strong> </td><td>" . strip_tags($_POST['email']) . "</td></tr>";
$message .= "<tr><td><strong>Issue:</strong> </td><td>" . strip_tags($_POST['issue']) . "</td></tr>";
$message .= "<tr><td><strong>TIME: Morning:</strong> </td><td>" . $_POST['checkmorning'] . "</td></tr>";
$message .= "<tr><td><strong>TIME: Lunchtime:</strong> </td><td>" . $_POST['checklunch'] . "</td></tr>";
$message .= "<tr><td><strong>TIME: After School:</strong> </td><td>" . $_POST['checkafter'] . "</td></tr>";
$message .= "</table>";
$message .= "</body></html>";
$to = "***#gmail.com";//<== update the email address
$headers = "From: $email_from \r\n";
$headers .= "Reply-To: $visitor_email \r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
//Send the email!
mail($to,$email_subject,$email_body,$headers);
//done. redirect to thank-you page.
header( 'Location:/thank-you.html' );
if(!isset($_POST['submit']))
{
//This page should not be accessed directly. Need to submit the form.
echo "error; you need to submit the form!";
}
// Function to validate against any email injection attempts
function IsInjected($str)
{
$injections = array('(\n+)',
'(\r+)',
'(\t+)',
'(%0A+)',
'(%0D+)',
'(%08+)',
'(%09+)'
);
$inject = join('|', $injections);
$inject = "/$inject/i";
if(preg_match($inject,$str))
{
return true;
}
else
{
return false;
}
}
?>
change
$email_body = '<html><body>';
to
$message = '<html><body>';
and
mail($to,$email_subject,$email_body,$headers);
to
mail($to,$email_subject,$message,$headers);
just add this line before mail($to,$email_subject,$email_body,$headers);
$email_body .= $message;