php mail attachments with message - php

I have seen this is a common question but through searching I haven't found the answer I need. I have used PHP code to create a mailer with attachments that are located on my server.
My site has a CRUD system and the read.php file displays various elements of an uploaded file. I also have a form on this page which allows the user to enter and email address and message to send on the said file.
My form code is:-
<form class="form-horizontal" action="mailer.php" method="post">
<div class="form-group">
<label class="col-sm-2">Email Address</label>
<div class="col-sm-4">
<input name="doc_email" type="text" placeholder="Enter Email Address to" class="form-control" >
</div>
</div>
<div class="form-group">
<label class="col-sm-2">Message</label>
<div class="col-sm-4">
<input name="doc_message" type="text" placeholder="Enter a message (not mandatory)" class="form-control" >
</div>
</div>
<div class="form-actions">
<button type="submit" class="btn btn-success">Send Email</button>
</div>
</form>
And my mailer.php code is currently;-
<?php
if (isset($_POST['submit']))
{
$file_name = $_POST['file_name'];
$doc_email = $_POST['doc_email'];
$doc_message = $_POST['doc_message'];
require_once('class.phpmailer.php');
$email = new PHPMailer();
$email->From = 'you#example.com';
$email->FromName = 'Your Name';
$email->Subject = 'Message Subject';
$email->Body = $doc_message;
$email->AddAddress = $doc_email;
$path_file_to_attach = '/documents/uploads/';
$file_to_attach = $file_name;
$email->AddAttachment( $path_file_to_attach , $file_to_attach );
return $email->Send();
//redirect user after success
header("Location: index.php");
}
?>
The class.phpmailer.php file is within the same directory (/documents) as the read.php/mailer.php, all I get is a blank screen with no email or errors.
The folder with the files is located in a sub folder called 'uploads'... documents/uploads/
Any help as always is greatly appreciated.

You have two things empty:
if (isset($_POST['submit'])) //this is false, your button must have a name="submit" attribute
$file_name = $_POST['file_name']; // you don't have any element with this name.
Just add to your html:
<input type="text" name="file_name">
And your button
<button type="submit" name="submit"></button>

Related

"Contact Me" Mail Form in PHP [duplicate]

This question already has answers here:
PHP mail function doesn't complete sending of e-mail
(31 answers)
Closed 1 year ago.
I have setup a "contact me" form on my website and it doesn't work. Here is the code :
Form Markup :
<form class="contactform" method="post" action="php/process-form.php">
<div class="row">
<!-- Name Field Starts -->
<div class="form-group col-xl-6"> <i class="fa fa-user prefix"></i>
<input id="name" name="name" type="text" class="form-control" placeholder="YOUR NAME" required>
</div>
<!-- Name Field Ends -->
<!-- Email Field Starts -->
<div class="form-group col-xl-6"> <i class="fa fa-envelope prefix"></i>
<input id="email" type="email" name="email" class="form-control" placeholder="YOUR EMAIL" required>
</div>
<!-- Email Field Ends -->
<!-- Comment Textarea Starts -->
<div class="form-group col-xl-12"> <i class="fa fa-comments prefix"></i>
<textarea id="comment" name="comment" class="form-control" placeholder="YOUR MESSAGE" required></textarea>
</div>
<!-- Comment Textarea Ends -->
</div>
<!-- Submit Form Button Starts -->
<div class="submit-form">
<button class="btn button-animated" type="submit" name="send"><span><i class="fa fa-send"></i> Send Message</span></button>
</div>
<!-- Submit Form Button Ends -->
<div class="form-message"> <span class="output_message text-center font-weight-600 uppercase"></span>
</div>
</form>
process-form.php :
<?php
if (isset($_REQUEST['name'],$_REQUEST['email'])) {
$name = $_REQUEST['name'];
$mail = $_REQUEST['email'];
$message = $_REQUEST['comment'];
$to = 'redacted#for.privacy';
$subject = 'Contact From My Website';
$headers = "From: ".$name." <".$mail."> \r\n";
$send_email = mail($to,$subject,$message,$headers);
echo ($send_email) ? 'success' : 'error';
}
?>
AJAX :
$(".contactform").on("submit", function() {
$(".output_message").text("Loading...");
var form = $(this);
$.ajax({
url: form.attr("action"),
method: form.attr("method"),
data: form.serialize(),
success: function(result) {
if (result == "success") {
$(".form-inputs").css("display", "none");
$(".box p").css("display", "none");
$(".contactform").find(".output_message").addClass("success");
$(".output_message").text("Message Sent!");
} else {
$(".tabs-container").css("height", "440px");
$(".contactform").find(".output_message").addClass("error");
$(".output_message").text("Error Sending!");
}
}
});
return false;
});
Error message from the ajax shows and I don't receive any mail. This code should be correct but I read that I needed an smtp configuration ? I can setup such a thing in my google business email but I don't know how and how to implement it on the website.
PHP's mail() function does need some configuration in php.ini file in some cases, like using Windows operating system. It is documented in php.net mail documentation page. Either configure the file, if your load will not be hundreds of mails, or use some of the public available libraries for SMTP connection. They provide much more flexibility and usually provide simple api.
On windows
You need to have set up the php.ini
[mail]
SMTP = "your-mail-server-address"
smtp_port = 25
This answer should provide you more than enough explanation and info.
on Ubuntu / Debian
You have to have configured your sendmail client so it can send emails in your network and specified as sendmail command in sendmail_path directive of php.ini file
While you are using mail() function, You should configure STMP in php.ini file.
But you can use PHPMailer especially when dealing with Google email service, Because Google doesn't allow less secure apps by default.
Look for this example below using PHPMailer:
$mail = new PHPMailer;
$mail->From = 'from#example.com';
$mail->FromName = 'Mailer';
$mail->addAddress($_REQUEST['email'], $_REQUEST['name']);
$mail->addCC('cc#example.com');
$mail->Subject = 'Contact From My Website';
$mail->Body = $_REQUEST['comment'];
echo $mail->send() ? "success" : "error";

how do i display a custom message after submitting a form?

I have a html form that sends email, using phpMailer, after its submission. Everything works fine but i want to display a message on the form when the email is sent.
With my code, a message is displayed on an empty white page.
My php code:
<?php
$name = $_POST['name'] ?? '';
$email = $_POST['email'] ?? '';
$msg = $_POST['msg'] ?? '';
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
require 'vendor/autoload.php';
$mail = new PHPMailer(true);
try {
$mail->Host='smtp.gmail.com';
$mail->SMTPDebug = 0;
$mail->isSMTP();
$mail->Port=587;
$mail->SMTPAuth=true;
$mail->SMTPSecure='tls';
$mail->Username='email#email.com';
$mail->Password='password';
$mail->setFrom($email, $name); // who send the email
$mail->addAddress('email#email.com'); // who recive the email
$mail->isHTML(true);
$mail->Subject = 'Portfolio response';
$mail->Body = $msg;
$mail->send();
echo 'Your message has been sent!';
} catch (Exception $e){
echo '';
}
?>
Your message has been sent! is obviously the message displayed.
Html form code:
<form action="mail-handler.php" method="POST" id="contact-form">
<span class="contacts-text" id="first-contacts-text">To get in touch with me, please compile this form.</span>
<span class="contacts-text">I will reply as soon as possible. Thank you!</span>
<ul class="form-content">
<li class="form-input">
<label for="name" class="label">Full name</label>
<input class="input" id="name" type="text" name="name" required>
</li>
<li class="form-input">
<label for="email" class="label">E-mail</label>
<input class="input" id="mail" type="text" name="email" required>
</li>
<li class="form-input">
<label for="msg" class="label">Insert text</label>
<textarea class="input" id="comment" type="text" name="msg" cols="30" rows="10" style="resize: none;" required></textarea>
</li>
<li class="form-input" id="last-input">
<input class="input" id="form-button" type="submit" value="submit" name="submit" onclick="sendEmail()">
</li>
</ul>
</form>
Thanks in advice!
First, change the name of your index.html to index.php, so it can be parsed by a PHP interpreter.
Next modiy your success statement body, i.e.:
try {
$mail->send();
header('Location: index.php?mailsent=1');
die(); // we don't want exactly anything after sending redirect header.
} catch (Exception $e){
echo '';
}
Finally in file with your form add the message if $_GET['mailsent'] variable is available.
HTML code of your page...
...
<?php
if (isset($_GET['mailsent']) && intval($_GET['mailsent']) == 1 ){
echo '<div class="messagesbox">Mail was sent</div>';
}
?>
<form action="mail-handler.php" method="POST" id="contact-form">
... your form body skipped here
</form>
Other options
If you don't want to pass arguments via GET array, you can try to use sessions.
Also, you can just create a static thankyou.html page and redirect the user there, after mail submitting
Also, if you move the whole PHP code for the form submittion into index.php you won't need to make redirects.
Finally, as you added - while it's one-page site you should also consider using AJAX probably with jQuery - that way you're will be able to submit the form without leaving the page, display messages without reloading, etc. Anyway, this topic is definitely too broad to be described in this answer and I can only suggest you get familiar with jQuery AJAX.

How to create php form handler and intergrate with existing html web form? [duplicate]

This question already has answers here:
Send email with PHP from html form on submit with the same script
(8 answers)
Closed 7 years ago.
So here is the problem I am facing. I have created a pretty simple web form:
<form method="post" action="#">
<div class="field"> <label for="name">Name</label>
<input name="name" id="name" type="text"> </div>
<div class="field"> <label for="email">Email</label> <input
name="email" id="email" type="email"> </div>
<div class="field"> <label for="message">Message</label> <textarea
name="message" id="message" rows="4"></textarea> </div>
<ul class="actions">
<li><input value="Send Message" type="submit"></li>
</ul>
</form>
I need to know how I can use this form to send data inputed by the user to my email address admin#nue-tech.uk I am aware this can be done in PHP but am unsure how to approach this as I am unfamilliar with PHP. If someone could please point me in the right direction as to how this can be done, and also where I should place the PHP file relative to this, that'd be awesome!
You could copy the code below and paste it in your HTML file below your html. In your html you set the action attribute empty. Don't forget to change your file extension to .php
<?php
if(isset($_POST['submit'])){
$to = "admin#nue-tech.uk";
$from = $_POST['email'];
$name = $_POST['name'];
$subject = "Blablabla"; //Write whatever you want here
$message = $name . "wrote the following:" . "\n\n" . $_POST['message'];
$headers = "From:" . $from;
mail($to,$subject,$message,$headers);
header('location: thank-you.html'); //redirects the user to another page if the mail was send succesfully
} else {
header('location: contact.html'); //if it was not send succesfully it redirects to the contact page again
exit(0);
}
?>
In
header('location: contact.html');
you could also use
echo "Something went wrong. Try again later"
or something simular.
I would highly recommend you search and learn on W3Cschools or at php.net.

Issues with HTML PHP Mailer

i I've been trying to get a .php that works with this HTML code for my website (template), I tried using my old .php from my old website and changing the details but that sadly lead to no avail.
I am clueless when it comes to .php and would really appreciate your help!
What would my .php have to contain?
<form action="#" id="contact-form">
<div id="success"></div>
<ul>
<li class="input-name">
<input type="text" id="name" class="required" placeholder="Name">
</li> <!-- END input-name -->
<li class="input-email">
<input type="text" id="email" class="email" placeholder="Email Address">
</li> <!-- END input-name -->
<li class="input-subject">
<input type="text" id="subject" placeholder="Subject">
</li> <!-- END input-name -->
<li class="input-subject">
<textarea rows="7" cols="50" id="message" class="required" placeholder="Message"></textarea>
</li> <!-- END input-name -->
</ul> <!-- END #contact -->
<button type="submit" class="btn btn-primary btn-lg pull-right">Send Message</button>
</form>
if you are not using ajax then write php file name in form action attribute currently there is #. then you php file will be called.
Change the below code
<form action="#" id="contact-form">
to
<form action="mailer.php" method="post" id="contact-form">
hope this will help.
You have to include the in action="#" the php file. example: action="contactForm.php". That's how the HTML code knows where to send the parameters.
Also, make sure your server supports the 'mail' function.
AND!
I have a good standard example for you of a well written mailing php file that I used. So you can check yourself for syntax issues.
<?php
require_once "Mail.php";
if(isset($_POST['email'])) {
$email = $_POST['email']; //this is how you get your variables from the HTML file. 'edit' is the id of the element.
$email_to = "yourEmail#example.com";
$host = "ssl://smtp.gmail.com:465"; //use your email host - this example is gmail based. (you can search for your own email host via google).
$username = 'username#example.pro';
$password = 'yourPass';
$email_subject = "You have a new email from $email via example.com website";
$message = $_POST['text'];
$headers = array ('From' => $email, 'To' => $email_to,'Subject' => $email_subject);
$smtp = Mail::factory('smtp',
array ('host' => $host,
'auth' => true,
'username' => $username,
'password' => $password));
$mail = $smtp->send($email_to, $headers, $message);
if (PEAR::isError($mail)) {
echo($mail->getMessage());
} else {
echo("Message successfully sent!\n");
}
}
In case of sending emails with ajax - it's an other thing.. and I can help you with that too.

Email attachments that are uploaded from web form with SwiftMailer

I am trying to use swftmailer to - upload a file (jpg,ppt,pdf,word etc with a max upload of eg: 6MB) from a form on a html web page, - email the content of the form with the attached file via swiftmailer.
My form is created & I am using $_POST to capture the field values in a thankyou.php page. The email is sending, but I cant get the file to attach!
The upload/attach file needs to be an option, I found a resource online that only sends the info if a file is uploaded, which is not always going to be the case, so I have turned to swiftmailer which looks great, but in the documentation/examples it specifies a path to upload the attachment too, I just want to be able to read in the file (not specify a path) and send it as an attachment to the given email address along with the other form fields, Name Email,Phone & Message.
Any help would be greatly appreciated.
My HTML (contact.html)
<div id="form-main">
<div id="form-div">
<form class="form" method="post" action="thank-you.php" enctype="multipart/form-data">
<p class="name">
<input name="fieldFormName" type="text" class="validate[required,custom[onlyLetter],length[0,100]] feedback-input" placeholder="Name" id="name" />
</p>
<p class="email">
<input name="fieldFormEmail" type="email" class="validate[required,custom[email]] feedback-input" id="email" placeholder="Email" />
</p>
<p class="phone">
<input name="fieldFormPhone" type="number" class="validate[required,custom[onlyLetter],length[0,20]] feedback-input" placeholder="Phone" id="phone" />
</p>
<p class="text">
<textarea name="fieldDescription" class="validate[required,length[6,300]] feedback-input" id="comment" placeholder="Comment"></textarea>
</p>
<p class="upload">
<small>Send us a Drawing or file</small>
<input name="fieldAttachment" id="attachment" class="feedback-input" type="file">
</p>
<div class="submit">
<input type="submit" value="SEND" id="button-blue"/>
<div class="ease"></div>
</div>
</form>
</div>
</div>
My PHP Code:
<?php
require_once 'lib/swift_required.php';
$fromEmail = $_POST['fieldFormEmail'];
$fromName = $_POST['fieldFormName'];
$fromPhone = $_POST['fieldFormPhone'];
$fromMessage = $_POST['fieldDescription'];
$fromAttachment = $_POST['fieldAttachment'];
// Create the mail transport configuration
$transport = Swift_MailTransport::newInstance();
// Create the message
$message = Swift_Message::newInstance();
$message->setTo(array(
"sender#domain.com" => "Sender Name"
));
$message->setSubject("This email is sent using Swift Mailer");
$message->setBody(
"From: " . $fromName . "\n" .
"Email: " . $fromEmail . "\n" .
"Phone: " . $fromPhone . "\n" .
"Message: " . $fromMessage . "\n"
);
$message->setFrom("$fromEmail", "$fromName");
// *** This is the part I am struggling to understand *** //
$message->attach(Swift_Attachment::newInstance('$fromAttachment'));
// Send the email
$mailer = Swift_Mailer::newInstance($transport);
$mailer->send($message);
?>
Thank you in advance
Replace your code
$message->attach(Swift_Attachment::newInstance('$fromAttachment'));
on this
$message->attach(
Swift_Attachment::fromPath($_FILES['fieldAttachment']['tmp_name'])->setFilename($_FILES['fieldAttachment']['name'])
);
I have taken DarveL's code and added an if statement to to check if a file is uploaded because I still want the email to send if the user does NOT attach a file.
The below code works, so now I just have to add some file type/size validation.
if(is_uploaded_file($_FILES['fieldAttachment']['tmp_name'])) {
$message->attach(
Swift_Attachment::fromPath($_FILES['fieldAttachment']
['tmp_name'])->setFilename($_FILES['fieldAttachment']['name'])
);
}
Check form upload. Maybe you have error in this.
<form enctype="multipart/form-data" action="" method="POST">

Categories