Send email with attachment via PHPMailer - php

I'm preparing to create a form page for a website that will require many fields for the user to fill out and that will be sent to a specified email.
So far I've created a dummy php email page that gets your Message, 1 attachment, and Recipient Email address using Google's SMTP.
Here's my code for uploadtest.html:
<body>
<h1>Test Upload</h1>
<form action="email.php" method="get">
Message: <input type="text" name="message">
Email: <input type="text" name="email"><br>
Attach File: <input type="file" name="file" id="file">
<input type="submit">
</form>
</body>
uploadtest.html is what the user will see
Here's the code for email.php:
<?php
require("class.phpmailer.php");
$mail = new PHPMailer();
$recipiant = $_GET["email"];
$message = $_GET["message"];
$mail->IsSMTP(); // telling the class to use SMTP
$mail->SMTPAuth = true; // SMTP authentication
$mail->Host = "smtp.gmail.com"; // SMTP server
$mail->Port = 465; // SMTP Port
$mail->SMTPSecure = 'ssl';
$mail->Username = "xxxxx#gmail.com"; // SMTP account username
$mail->Password = "xxxxxxxx"; // SMTP account password
$mail->AddAttachment($_FILES['tmp_name']); //****HERE'S MY MAIN PROBLEM!!!
$mail->SetFrom('cinicraftmatt#gmail.com', 'CiniCraft.com'); // FROM
$mail->AddReplyTo('cinicraftmatt#gmail.com', 'Dom'); // Reply TO
$mail->AddAddress($recipiant, 'Dominik Andrzejczuk'); // recipient email
$mail->Subject = "First SMTP Message"; // email subject
$mail->Body = $message;
if(!$mail->Send()) {
echo 'Message was not sent.';
echo 'Mailer error: ' . $mail->ErrorInfo;
} else {
echo 'Message has been sent.';
}
?>
So from what I can tell here, PHPMailer's AddAttachment() method takes as a parameter the URL of the file DIRECTORY you want attached. And this is where my main problem is.
What would the name of the variable be that would get the location of my file (dir/upload.jpg) that I've uploaded so I could use it as a parameter in the AddAttachment() method?

No, it doesn't take URLs, or directories. It takes a direct path to a FILE.
e.g.
$mailer->AddAttachment(
'/path/to/file/on/your/server.txt',
'name_of_file_in_email',
'base64',
'mime/type'
);
The path is self-explanatory. The name_of_file_in_email allows you to "rename" the file, so that you might loaded a file named "foo.exe" on your server, it can appear as "bar.jpg" in the email the client receives.
Your problem is that you're trying to attach an uploaded file, but using the wrong source. It should be
<input type="file" name="thefile" />
^^^^^^^
$_FILES['thefile']['tmp_name']
^^^^^^^
Note the field name relationship to $_FILES.

This will be send like this through PHPMailer Class
$mail->AddAttachment($_FILES['tmp_name'],$_FILES['name']); //****HERE'S MY MAIN PROBLEM!!! So you would have to give file name also.
please try with this
include "phpMailerClass.php";
$email = new PHPMailer();
$email->From = $to;
$email->FromName = $_POST['name'];
$email->Subject = $subject;
$email->Body = $EmailText;
$email->AddAddress( 'shafiq2626#hotmail.com' );
$email->IsHTML(true);
$file_to_attach = $_FILES['file']['tmp_name'];
$filename=$_FILES['file']['name'];
$email->AddAttachment( $file_to_attach , $filename );
$email->Send();
This is code is working fine.

Your <form> tag should specify the enctype attribute like so :
<form ... enctype="multipart/form-data">
...
</form>

Use the following code:
$objectMailers->AddAttachment("file.extension");
tested on PHP 7 and using PHPMailer 5.3

Related

I'm Stumped: How to Send HTML Form using PHP Mailer

OK, so I have done a substantial amount of research over the last several days and am stumped. I have XAMPP and PHP Mailer and I know they are both working correctly locally.
I also have an HTML form that I know is working correctly using Hostgator web hosting. This HTML form calls a .php file named send_email.php which sends the form contents to my email.
My questions are:
What is the new .php code (roughly speaking) to send this HTML form on my local host (XAMPP) using PHP Mailer?
How do I call the new .php file in my HTML file?
What is the file tree structure that I need for both this HTML form and the new .php file which PHP Mailer will use to send it?
Please note: I've changed some of details in my code so I'm not including my actual email address and person info.
Here is my form:
<!-- THE SUBMISSION FORM -->
<div class="container">
<form id="contact" action="send_email.php" method="post">
<h3>Apply Today!</h3>
<h4></h4>
<fieldset>
<input placeholder="Full Name" type="text" name="name" tabindex="1" required autofocus>
</fieldset>
<fieldset>
<input placeholder="Telephone Number" type="tel" name="telephone" tabindex="2" required>
</fieldset>
<fieldset>
<input placeholder="Email Address" type="email" name="email" tabindex="3" required>
</fieldset>
<fieldset>
<input placeholder="Subject" type="text" name="subject" tabindex="4" required>
</fieldset>
<fieldset>
<textarea placeholder="Type your Message Here...." name="message" tabindex="5" required></textarea>
</fieldset>
<fieldset>
<button name="submit" type="submit" id="contact-submit" data-submit="...Sending" tabindex="6">Submit</button>
</fieldset>
</form>
</div>
Here is the send_email.php file I am using (which I know works)
<?php session_start();
if(isset($_POST['submit'])) {
$from = "sender#gmail.com";
$to = "receiver1#gmail.com";
$to2 = "receiver2#gmail.com";
$to3 = "receiver3#gmail.com";
$subject = "NEW LEAD!";
$message =
"|---------BEGIN TRANSMISSION----------|" . PHP_EOL .
PHP_EOL . "The person that contacted you is: ". $_POST['name'] .
PHP_EOL . "E-mail: " . $_POST['email'] .
PHP_EOL . "Telephone: " . $_POST['telephone'] .
PHP_EOL . "Subject: " . $_POST['subject'] .
PHP_EOL . "Message: " . $_POST['message'] . PHP_EOL .
PHP_EOL . "|---------END TRANSMISSION----------|";
$headers = "From:" . $from;
echo "Thank you for contacting us. We will will be in touch.<br/>Go to <a href='/index.php'>Home Page</a>";
mail($to, $subject, $message, $headers);
mail($to2, $subject, $message, $headers);
mail($to3, $subject, $message, $headers);
} else {
echo "You must write a message. </br> Please go to <a href='/index.html'>Home Page</a>";
}
?>
Here is my index.php file in my PHPMAILER folder (which I know works).
<?php
//Import PHPMailer classes into the global namespace
//These must be at the top of your script, not inside a function
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
//Load Composer's autoloader
require 'vendor/autoload.php';
//Instantiation and passing `true` enables exceptions
$mail = new PHPMailer(true);
try {
//Server settings
$mail->SMTPDebug = SMTP::DEBUG_SERVER; //Enable verbose debug output
$mail->isSMTP(); //Send using SMTP
$mail->Host = 'smtp.gmail.com'; //Set the SMTP server to send through
//$mail->Host = gethostbyname('smtp.gmail.com');
$mail->SMTPAuth = true; //Enable SMTP authentication
$mail->Username = 'sender#gmail.com'; //SMTP username
$mail->Password = 'sender-password'; //SMTP password
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; //Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` encouraged //TCP port to connect to, use 465 for `PHPMailer::ENCRYPTION_SMTPS` above
$mail->Port = 587; //TCP port to connect to, use 465 for `PHPMailer::ENCRYPTION_SMTPS` above
//Recipients
$mail->setFrom('receiver1#gmail.com', 'Mailer');
$mail->addAddress('receiver2#gmail.com', 'Dylan');
//Content
$mail->isHTML(true); //Set email format to HTML
$mail->Subject = 'Here is the subject';
$mail->Body = 'This is the HTML message body <b>in bold!</b>';
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
$mail->send();
echo 'Message has been sent';
} catch (Exception $e) {
echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}
This is my location for PHP Mailer on XAMPP:
c:/Users/dylan/.bitnami/stackman/machines/xampp/volumes/root/htdocs/phpmailer
This is the location for my HTML form and send_email.php :
c:/Users/dylan/.bitnami/stackman/machines/xampp/volumes/root/htdocs/WEBSITE
You should not have to change the code at all; it should work equally well wherever it's run from. So long as you're using a sending mechanism that your hosting provider allows, e.g. that they don't block outbound SMTP, it should work fine. Have you tried it?
Aside from that, your file structure looks a bit unusual. Composer installs PHPMailer for you and automatically loads it when you ask for it, so composer is also responsible for where it is stored; you don't need to make your own phpmailer folder. If you're hosting a single site, it's probably not necessary to put things in subfolders of your web root, so you can use a flatter structure like:
c:/Users/dylan/.bitnami/stackman/machines/xampp/volumes/root/htdocs/
index.php
send_email.php
vendor/
composer/
phpmailer
If you are hosting multiple sites you would typically have multiple folders within .../htdocs/, each of which will have a similar internal structure.
You have 0 knowledge of php
FIRST OF ALL, When you use .php files you can use html in it
You think this is a joke ?
try {
//Server settings
$mail->SMTPDebug = SMTP::DEBUG_SERVER; //Enable verbose debug output
$mail->isSMTP(); //Send using SMTP
$mail->Host = 'smtp.gmail.com'; //Set the SMTP server to send through
//$mail->Host = gethostbyname('smtp.gmail.com');
$mail->SMTPAuth = true; //Enable SMTP authentication
$mail->Username = 'sender#gmail.com'; //SMTP username
$mail->Password = 'sender-password'; //SMTP password
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; //Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` encouraged //TCP port to connect to, use 465 for `PHPMailer::ENCRYPTION_SMTPS` above
$mail->Port = 587; //TCP port to connect to, use 465 for `PHPMailer::ENCRYPTION_SMTPS` above
//Recipients
$mail->setFrom('receiver1#gmail.com', 'Mailer');
$mail->addAddress('receiver2#gmail.com', 'Dylan');
//Content
$mail->isHTML(true); //Set email format to HTML
$mail->Subject = 'Here is the subject';
$mail->Body = 'This is the HTML message body <b>in bold!</b>';
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
$mail->send();
echo 'Message has been sent';
} catch (Exception $e) {
echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}
This is copy and pasting to a new LEVEL !
$mail->setFrom('receiver1#gmail.com', 'Mailer');
$mail->addAddress('receiver2#gmail.com', 'Dylan');
You need to set it up
THE WHOLE CODE IS WRONG!
Go to Home Page";
mail($to, $subject, $message, $headers);
mail($to2, $subject, $message, $headers);
mail($to3, $subject, $message, $headers);
} else {
echo "You must write a message. Please go to Home Page";
}
?>
Last of all
This is my location for PHP Mailer on XAMPP:
c:/Users/dylan/.bitnami/stackman/machines/xampp/volumes/root/htdocs/phpmailer
This is the location for my HTML form and send_email.php :
c:/Users/dylan/.bitnami/stackman/machines/xampp/volumes/root/htdocs/WEBSITE
YOU PUT PHPMAILER IN THE DIRECTORY OF YOU WEB PAGE!!!!!!!1

PHP Email form script

Hi I have this PHP script that I found on a blog
<?php
if(isset($_POST['submit'])) {
$to = "youremail#gmail.com";
$subject = "Forms";
$name_field = $_POST['name'];
$email_field = $_POST['email'];
$message = $_POST['message'];
$body = "From: $name_field\n E-Mail: $email_field\n Message:\n $message";
echo "Data has been submitted to $to!";
mail($to, $subject, $body);
} else {
echo "blarg!";
}
?>
Which is run when the following is executed in HTML
<form method="POST" action="mailer.php">
Your Name<br>
<input type="text" name="name" size="19"><br>
<br>
Your Email<br>
<input type="text" name="email" size="19"><br>
<br>
Message<br>
<textarea rows="9" name="message" cols="30"></textarea>
<br>
<br>
<input type="submit" value="Submit" id="submitBTN" name="submit">
</form>
According to the blog all i have to do is put the html and php files onto my web server (Which i don't have so i can't test this). Will it send an email to the email specified in $to ? I've never used PHP but this doesn't really makes sense how it can just email someone once its on the web. Thanks for an explanation/if this script would work straight up!
This should theoretically work, but you will have to configure PHP to use your email server. I would recommend using something like PHPMailer to send email, that is what I always do. PHPMailer allows you to specify your IMAP/POP3 email server host, username & password, and email port, in the same manner that your email client does.
Here is a link to information about using Gmail in PHPMailer.
This snippet (taken from the PHPMailer readme) shows how to configure your server:
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'smtp1.example.com;smtp2.example.com'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'user#example.com'; // SMTP username
$mail->Password = 'secret'; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 587; // TCP port to connect to
Now, you can configure header information for where the email is from, and who it is going to:
$mail->setFrom('from#example.com', 'Mailer');
$mail->addAddress('joe#example.net', 'Joe User'); // Add a recipient
$mail->addAddress('ellen#example.com'); // Name is optional
$mail->addReplyTo('info#example.com', 'Information');
$mail->addCC('cc#example.com');
$mail->addBCC('bcc#example.com');
You can even add attachments to the email:
$mail->addAttachment('/var/tmp/file.tar.gz'); // Add attachments
$mail->addAttachment('/tmp/image.jpg', 'new.jpg'); // Optional name
$mail->isHTML(true); // Set email format to HTML
Finally, we put the subject and body into the email:
$mail->Subject = 'Here is the subject';
$mail->Body = 'This is the HTML message body <b>in bold!</b>';
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
Now, we send the email:
if(!$mail->send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
echo 'Message has been sent';
}
You will need to setup a mail server on your server in order to send emails.
Not sure where you need to specify this though for PHP to use..
Take a look here: php mail setup in xampp
(Xampp mentioned in the link is a program that acts as the server so that people can look at your webpages online)
Xampp: https://www.apachefriends.org/index.html
I did the same task long time ago.
I accomplished this trough XAMPP (php and apache) and gmail.
Here you can find a video with the complete explanation.

inserting HTML POST form field data into PHPmailer email body

I have tried every hint I have found across the web and here but what I cannot achieve is for the sent email to contain the form data in the html formatted message. The mailing function is working and I get the email properly.
The form is basically:
<form method="post" action="test.php" name="Work Record" autocomplete="off">
<input type="text" name="first_name" id="staff_name2" placeholder="First" required />
<input type="text" name="last_name" id="staff_name" placeholder="Last" required />
<input name="checkbox" type="checkbox" class="head-l" id="checkbox" onChange="this.form.submit()">
And using the latest phpmailer from google the action script is as follows. I have the emailing function working through gmail, I am just not sure what to put where to pull the data from the form and put it into the email body. The code that is pasted in the body now is that we used to use before switching to phpmailer. Thank you!
<?php
require '/home/newnplhftp/nplh.us/smtp/phpmailer/class.phpmailer.php';
$mail = new PHPMailer;
$mail->IsSMTP(); // Set mailer to use SMTP
$mail->Host = 'smtp.gmail.com'; // Specify main and backup server
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'xxxxxxxxxxxxxxxx'; // SMTP username
$mail->Password = 'xxxxxxxxx'; // SMTP password
$mail->SMTPSecure = 'ssl'; // Enable encryption, 'ssl' also accepted
$mail->Port = 465; // set the SMTP port for the GMAIL server
$mail->From = 'xxxxxxxxxxxxxx';
$mail->FromName = 'NPLH';
$mail->AddAddress('xxxxxxxxxxxxxxxxxxxxx'); // Name is optional
$mail->AddCC('');
$mail->AddBCC('');
$mail->WordWrap = 50; // Set word wrap to 50 characters
$mail->IsHTML(true); // Set email format to HTML
$mail->Subject = 'xxxxxxxxxxxxxxx';
$mail->Body = '
<html>
<h2><b>$first_name $last_name, $license_type</b></h2>
</html>';
$mail->AltBody = '';
if(!$mail->Send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
exit;
}
echo 'Thank you, your message has been sent!';
?>
Please set;
$mail->Body = '
<html>
<h2><b>$first_name $last_name, $license_type</b></h2>
</html>';
to
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$license_type = $_POST['license_type'];
$mail->Body = "
<html>
<h2><b>".$first_name." ".$last_name.", ".$license_type."</b></h2>
</html>";
The variables you are trying to send need to be captured from the the form first. This would happen on test.php since this is where you are posting the values to.
So you would do this
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$license_type = $_POST['license_type'];
Then you can use them inside the mail body.
$mail->Body = "<html><h2><b>$first_name $last_name, $license_type</b></h2></html>";
Though I would highly suggest validating that data in some way first.

attachment is not sent with phpmailer

I'm trying to send an attachment with the phpMailer script.
Everything is working correctly since my email is sent correctly, however I do have a problem with an attachment that is not sent.
HTML part:
<p>
<label>Attachment :</label>
<input name="doc" type="file">
</p>
PHP:
<?php
require 'PHPMailerAutoload.php';
$mail = new PHPMailer;
$mail->isSMTP();
$mail->Host = '*****';
$mail->SMTPAuth = true;
$mail->Port = 465;
$mail->Username = '*****';
$mail->Password = '*****';
$mail->SMTPSecure = 'ssl';
$mail->From = $_POST["name"];
$mail->FromName = 'Your Name';
$mail->Subject = 'Message Subject';
$mail->addAddress('*****');
$mail->addAttachment($_FILES["doc"]);
$mail->isHTML(true);
$mail->Subject = 'Here is the subject';
$mail->Body = "You got a new message from your website :
Name: $_POST[name]
Company: $_POST[company]
Phone: $_POST[phone]
Email: $_POST[email]
Message: $_POST[message]";
if(!$mail->send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
exit;
}
?>
<!DOCTYPE HTML>
<html>
<head>
<title>Thanks!</title>
</head>
<body>
<p> <img src="img/correct.png" alt="icon" style=" margin-right: 10px;">Thank you! We will get back to you soon.</p>
</body>
</html>
Try:
if (isset($_FILES['doc']) &&
$_FILES['doc']['error'] == UPLOAD_ERR_OK) {
$mail->AddAttachment($_FILES['doc']['tmp_name'],
$_FILES['doc']['name']);
}
Basic example can also be found [here](https://code.google.com/a/apache-extras.org/p/phpmailer/wiki/AdvancedMail).
The function definition for `AddAttachment` is:
public function AddAttachment($path,
$name = '',
$encoding = 'base64',
$type = 'application/octet-stream')
Please have a look about how PHP file uploads work. This array key:
$_FILES["doc"]
... will never contain a file. At most, it'll contain an array with information about where to find the file.
Untested solution, but should work:
change
$mail->addAttachment($_FILES["doc"]);
to
$mail->addAttachment($_FILES["doc"]["tmp_name"], $_FILES["doc"]["name"], "base64", $_FILES["doc"]["tmp_type"]);
However, please consider learning php upload file handling as already commented by others. Don't use user input without validation. Never!

How to get user mails in my free gmail inbox through contact us form on my website

How to get user mails in my free gmail inbox through contact us form on my website. I do not use email with my website name . i use free gmail. I tried many script but the all need email account on domain.
Does this question have something to do with This One?
Well, so you have a form on your site, your users fill it up and you need an email with that data, right?
Simple example:
<form action="sendMail.php" method="post">
Name: <input type="text" name="name" id="name" /><br />
Email: <input type="text" name="email" id="email" /><br />
Text: <textarea name="text"></textarea><br />
<input type="submit" value="Send" />
</form>
then, the php page wich send the mail:
//php sendThis.php page
<?php
require("class.phpmailer.php");
$name = $_POST['name'];
$email = $_POST['email'];
$text = $name . ', ' . $email . ' has filled the form with the text:<br />' . $_POST['text'];
$from = 'your.email#gmail.com';
$to = 'your.email#gmail.com';
$gmailPass = 'your gmail password';
$mail = new PHPMailer();
$mail->IsSMTP();
// enable SMTP authentication
$mail->SMTPAuth = true;
// sets the prefix to the server
$mail->SMTPSecure = "ssl";
// sets GMAIL as the SMTP server
$mail->Host = 'smtp.gmail.com';
// set the SMTP port
$mail->Port = '465';
// GMAIL username
$mail->Username = $from;
// GMAIL password
$mail->Password = $gmailPass;
$mail->From = $from;
$mail->FromName = $from;
$mail->AddReplyTo($from, $from);
$mail->Subject = 'This is a test!';
$mail->Body = $text;
$mail->MsgHTML($text);
$mail->IsHTML(true);
$mail->AddAddress($to, $to);
if(!$mail->Send()){
echo $mail->ErrorInfo;
}else{
echo 'sent!';
$mail->ClearAddresses();
$mail->ClearAttachments();
}
?>
EDIT: just tested and works fine. Make sure that the 3 files (class.phpmailer.php, class.pop3.php and class.smtp.php) are in the correct include path
Basically, it involves the PHP mail() function:
<?php
mail(yourGmailAddress, object, message);
?>
As you have already observed, this solution works only if the webserver operates a mail server. This mail server may forbid unknown users. So you need to have an email account on that web/mail server (I believe this is the case). The second step then is to forward mail from your website address to you gmail account. I am 90% certain that it is possible from your gmail configuration. It may also be possible from your website mail configuration. But don't configure both!
Try enabling openssl.
Uncomment the line:
extension=php_openssl.dll
in your php.ini file.
You can also put your email address into "action" attribute of the form element. But that's very unreliable. Like this:
<form method='post' action='mailto:your#email.com?Subject=Hello'>
...
</form>
Users must have email client installed and configured for this to work properly. There are some other drawbacks. You have to do some research to find whether this method is for you or not.
http://www.google.com/search?client=opera&rls=en&q=form+action+mailto&sourceid=opera&ie=utf-8&oe=utf-8

Categories