• Global community
    • Language:
      • Deutsch
      • English
      • Español
      • Français
      • Português
  • 日本語コミュニティ
    Dedicated community for Japanese speakers
  • 한국 커뮤니티
    Dedicated community for Korean speakers
Exit
2

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

Participant ,
Aug 04, 2023 Aug 04, 2023

Copy link to clipboard

Copied

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>

TOPICS
Code

Views

470

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Community Expert ,
Aug 04, 2023 Aug 04, 2023

Copy link to clipboard

Copied

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 & Moderator
Alt-Web Design & Publishing ~ Web : Print : Graphics : Media

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Community Expert ,
Aug 11, 2023 Aug 11, 2023

Copy link to clipboard

Copied

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

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
LEGEND ,
Aug 11, 2023 Aug 11, 2023

Copy link to clipboard

Copied

quote

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.

 


By @L e n a

 

From what l can remember the folders/scripts needed to use phpmailer are available to download on github it was, l think, so you don't have to install composer and deploy it via the terminal.

 

I've used it in the past and there's no way l would have installed composer or spun up workfiles via the terminal, far too much dependency on this kind of workflow to produce something so simple.

 

Edited:

I have just checked, and yes, phpmailer it's still available to download as a zip file so for simplicity l would go with that unless you particularly like installing extra stuff to get stuff which can be downloaded directly, many do, or more likely don't actually know it can be done simpler.

 

Maybe not even use phpmailer at all, theres plenty of solutions just using the php mail function , which is obviously available to the OP as they are currently using it to process their form.

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Community Expert ,
Aug 11, 2023 Aug 11, 2023

Copy link to clipboard

Copied

I completely agree with you, PHPMailer can be installed simply by copying the necessary files. It is true that if you need a simple van, why bother with a truck?

 

From experience, a project always starts with very small needs and over time these needs increase, even become much more demanding. This frequently leads to finer management of dependencies and compatibilities between the various necessary tools.

 

In addition, the sharing of work within the team, and many other aspects very often complicate file exchanges in order to take certain features into account.

 

This is where composer comes in, and using it is so appealing that one sometimes forget to do without it. You are right to point that out.

 

However, for the uninitiated, I would say that installing composer and setting up dependencies is a two-line operation. This allows us to focus directly on the core of the application developed.

 

But again, I completely agree with you, it is possible to do without composer and/or PHPMailer and do with other tools such as mail (PHP).

 

However, it is important to remember for @daveharr1s0n  that with mail(), it is often necessary to take into account aspects such as encoding and this depending on the files transmitted, to ensure protection against data injection, to sometimes have to manage SMTP sending compatibility, to check that the headers are formatted correctly... in short, a whole bunch of tasks which means that sooner or later we switch, certainly for comfort, to packages (open source) more sophisticated and more complete, surrounded by highly responsive communities.

 

Once again, everyone is free to surround themselves with the tools that suit them best, and the interest of a forum like this one is precisely this plurality, and this diversity of approaches, linked to everyone.

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Community Expert ,
Aug 11, 2023 Aug 11, 2023

Copy link to clipboard

Copied

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 & Moderator
Alt-Web Design & Publishing ~ Web : Print : Graphics : Media

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
LEGEND ,
Aug 11, 2023 Aug 11, 2023

Copy link to clipboard

Copied

quote

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?

 

 


By @Nancy OShea

 

lol........I wasnt actually thinking that myself but I was thinking they may be part of the team at the 'studio' which I believe Birnou may have mentioned in the past. However, Inspector Clouseau, you may be correct, perhaps Birnou likes to wind down at the weekend by swapping his breeches for a dress. (no offence intended - just a bit of light hearted banter)

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Community Expert ,
Aug 11, 2023 Aug 11, 2023

Copy link to clipboard

Copied

I don't care which pronouns or apparel people prefer. That's not my concern. 

 

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...

 

 

Nancy O'Shea— Product User, Community Expert & Moderator
Alt-Web Design & Publishing ~ Web : Print : Graphics : Media

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Community Expert ,
Aug 12, 2023 Aug 12, 2023

Copy link to clipboard

Copied

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!

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Community Expert ,
Aug 12, 2023 Aug 12, 2023

Copy link to clipboard

Copied

Judging by your reaction, I see I touched a nerve. Fair enough.  I assure you, I intended no disrespect towards @L e n a.  

 

"A fool's folly" is an English expression for the pursuit of something that has little likelihood of success.

image.png

The closest French translation for "this is a fool's folly" that I could come up with is "c'est une folie d'imbécile."  If my terminology or grammar are improper, please correct me.  I'm apt to make mistakes as French is neither my first nor second language. 

 

To provide further context, this is @L e n a's topic about MX 2004.

https://community.adobe.com/t5/fireworks-discussions/fw-mx-2004/td-p/13986515

 

Nancy O'Shea— Product User, Community Expert & Moderator
Alt-Web Design & Publishing ~ Web : Print : Graphics : Media

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Community Expert ,
Aug 17, 2023 Aug 17, 2023

Copy link to clipboard

Copied

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]

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Community Expert ,
Aug 17, 2023 Aug 17, 2023

Copy link to clipboard

Copied

LATEST
quoteBirnou likes to wind down at the weekend by swapping his breeches for a dress.

By @osgood_

the weekend !

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines