Skip to main content
daveharr1s0n
Inspiring
August 4, 2023
Question

How do I send Email with attachment on form submission using PHP?

  • August 4, 2023
  • 4 replies
  • 1607 views

Hello PHP pros,

 

This one's probably a simple one for those of you versed in php (which I'm not). I'm trying to add "upload file" capability to an existing form. The form works, I just don't know what I have to add to the following code so that a user can add an attachment to a message.

 

I've tried a few things from what I've read online, but I must be missing something.

 

Any help would be greatly appreciated!

 

Thanks!

 

Dave

 

 

 

<?php
// NOTE: this page must be saved as a .php file.
// And your server must support PHP 5.3+ PHP Mail().
// Define variables and set to empty values
$result = $message = $human = "";
$errName = $errMessage = $errHuman = "";
if ( isset( $_POST[ "submit" ] ) ) {
$message = $_POST[ 'message' ];
$human = intval( $_POST[ 'human' ] );
//valid address on your web server
$from = 'webmaster@daveharrison.info';
//your email address where you wish to receive mail
$to = 'dave@daveharrisonwebdesign.com';
$subject = 'MESSAGE FROM YOUR WEB SITE';
$headers = "From:$from\r\nReply-to:$email";
$body = "Message: $message";
//Check if message is entered
if ( empty( $_POST[ "message" ] ) ) {
$errMessage = "Please enter your message.";
} else {
$message = test_input( $_POST[ "message" ] );
}
//Check if simple anti-bot test is entered
if ( empty( $_POST[ "human" ] ) ) {
$errHuman = "Please enter the sum.";
} else {
if ( $human !== 13 ) {
$errHuman = 'Wrong answer. Please try again.';
}
}
// If there are no errors, send the email & output results to the form
if ( !$errMessage && !$errHuman ) {
if ( mail( $to, $subject, $body, $from ) ) {
$result = '<div class="alert alert-success"><h2><span class="glyphicon glyphicon-ok"></span> Message sent!</h2><h3>Thank you for contacting us. Someone will be in touch with you soon.</h3></div>';
} else {
$result = '<div class="alert alert-danger"><h2><span class="glyphicon glyphicon-warning-sign"></span> Sorry there was a form processing error.</h2> <h3>Please try again later.</h3></div>';
}
}
}
//sanitize data inputs
function test_input( $data ) {
$data = trim( $data );
$data = stripslashes( $data );
$data = htmlspecialchars( $data );
$data = ( filter_var( $data, FILTER_SANITIZE_STRING ) );
return $data;
}
//end form processing script
?>

<!DOCTYPE html>
<html lang="en">
<head>
<title>test</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
<style>
/* Set height of the grid so .sidenav can be 100% (adjust if needed) */
.row.content {
height: 1500px
}
/* Set gray background color and 100% height */
.sidenav {
background-color: #FFFFFF;
height: 100%;
}
/* Set black background color, white text and some padding */
footer {
background-color: #FFFFFF;
color: white;
padding: 15px;
}

/* On small screens, set height to 'auto' for sidenav and grid */
@media screen and (max-width: 767px) {
.sidenav {
height: auto;
padding: 15px;
}
.row.content {
height: auto;
}
}
.carouselWidth {
width: 95%;
margin-right: auto;
margin-left: auto;
}
</style>
</head>
<body>
<div class="container-fluid">
<div class="row content">
<div class="col-sm-3 sidenav"> </div>
<div class="col-sm-6">


<div class="row">

</div>



<p><small>DROP ME A LINE SOMETIME!</small></p>
<div class="center-block">

<!--begin HTML Form-->
<form role="form" method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<!--when submit button is clicked, show results here-->
<div class="form-group"> <?php echo $result;?> </div>
<div class="form-group">
<textarea class="form-control" rows="3" name="message" requiredplaceholder="What's new?"><?php echo $message;?></textarea>
<span class="required small"><?php echo $errMessage;?></span> </div>
<div class="form-group">
<div class="col-sm-4">
<h6 class="human">A number between 1 and 1,806,010</h6>
<input type="text" class="form-control" id="human" name="human" placeholder="Your Answer" value="<?php echo $human;?>">
<span class="required small"><?php echo $errHuman;?></span><br>
<button type="submit" id="submit" name="submit" class="btn btn-success">SUBMIT</button>
&nbsp;
<button type="reset" id="reset" name="reset" class="btn btn-success">RESET</button>
</div>
</div>

<!--end Form-->
</form>
<!--end col block--></div>
</div>
<div class="col-sm-3 sidenav"> </div>
</div>
</div>
<footer class="container-fluid"> </footer>
</body>
</html>

This topic has been closed for replies.

4 replies

B i r n o u
Legend
August 17, 2023
quoteBirnou likes to wind down at the weekend by swapping his breeches for a dress.

By @osgood_

the weekend !

B i r n o u
Legend
August 17, 2023

Back from vacation... lol

quote

Up until now, I honestly thought L e n a  and B I R N O U were different people who worked together.  But now I wonder...

By @Nancy OShea

 

[abuse removed by Moderator]

Community Expert
August 11, 2023

In addition to what propose @Nancy OShea , I would add that PHPMailer remains today an excellent solution to manage its mails, and even its SMTP.

 

However, some servers may consider it a threat, so don't be scared if it does. Well, stay alert, these are still powerful tools that can be sniffed at for malicious purposes.

 

But far be it from me to frighten you.

 

To use send attachments, to mail, explore the basic offered by PHPMailer, https://github.com/PHPMailer/PHPMailer/blob/master/examples/send_file_upload.phps

 

You will however need to install the dependencies and I would only know too advise you the use of composer https://getcomposer.org for this purpose.

 

If you've never used composer, now might be the time to do so, and it's actually very easy to use, and so useful.

This little article should be able to enlighten you https://alexwebdevelop.com/phpmailer-tutorial/

This movie can be useful too https://app.pluralsight.com/course-player?clipId=1d6168e3-b3ad-47bb-a3a4-1d8b3b03ef32

 

Once composer installed, you'll have to install PHPMailer, for that open a terminal and just enter, in the appropriate root folder : 

 

composer requires phpmailer/phpmailer

 

 

Everything is said on the PHPmailer github https://github.com/PHPMailer/PHPMailer/ scroll down the page, and just below the installation procedure, you even have a little appetizer script.. .

Don't forget to visit the all examples page https://github.com/PHPMailer/PHPMailer/tree/master/examples

Nancy OShea
Community Expert
Community Expert
August 11, 2023

Mademoiselle @L e n a, please pardon me if I say anything that offends you. That is not my intention.  

 

Lately, I notice YOUR posts have taken on the same tone & comportement as Monsieur B I R N O U.  Are you the same person now? And if so, why the charade?

 

 

Nancy O'Shea— Product User & Community Expert
Community Expert
August 12, 2023

Wow!!! What can I say to that?!!!

 

Don't worry @Nancy OShea , I don't feel offended at all, just a little sad about the way you've been replying to me for the past few days, and to see that in a forum on which contributors are supposed to be respectful of each other, and interested in their problems in order to try to help them, we can be used as a vent if we don't respond what is in the prevailing thinking... No doubt a reflection of today's society...

 

Not to mention the fact that you called me an imbecile (in French, please) in a discussion about Fw MX2004, even though I was taking into account the thoughts of @markl80449518 , who has found a solution that works (in a previously locked thread) :

quote

No worries... Got it to work. I once again have Studio MX 2004 working on my new laptop (Win11Pro) But, thank you for getting back to me... Glad I was able to get it to work, because nothing compares, this is so much better than any other software I've used...

By @markl80449518


@osgood_ is right to laugh at your latest find of the day and welcome his humor 🙂


@B i r n o u and I have been working in the same studio for over 30 years now and share the same ideas on many things, both in work and in life...but we're two very different people !!! 😉

 

I think you're better than that, and that these slip-ups are due to a bad day. If not, I sincerely pity you.

Have a nice day!

Nancy OShea
Community Expert
Community Expert
August 4, 2023

For reference:

https://www.php.net/manual/en/features.file-upload.post-method.php

 

PHPMailer can process forms with file attachments.

https://github.com/PHPMailer/PHPMailer

 

Nancy O'Shea— Product User & Community Expert