attachment is not sent with phpmailer - php

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!

Related

PHP Emails with PHP Mailer

I'm creating a form that sends an email to the email that was entered into it. I have installed PHP mailer on my server.
Currently when sending emails via PHP they send like this:
All emails sent are via the hosting server when I'd like them to look like this.
Just like any other email sent on the domain they should be mailed by domain.com rather than the server.
I'm just testing this so using a simple form as a proof of concept.
<form method="post" name="process.php" action="process.php">
<p>Name:</p><br><input type="text" name="name"><br><br>
<p>Email Address:</p><br><input type="text" name="email"><br><br>
<br>
<input type="submit" value="Send Email">
</form>
I'm then using this PHP to send the email:
<?php
$name = $_POST['name'];
$email = $_POST['email'];
use PHPMailer\PHPMailer\PHPMailer;
require 'vendor/autoload.php';
$mail = new PHPMailer;
$mail->isSMTP();
$mail->SMTPDebug = 2;
$mail->Host = 'smtp.hostinger.com';
$mail->Port = 587;
$mail->SMTPAuth = true;
$mail->Username = 'noreply#domain.com';
$mail->Password = 'password';
$email_from = "noreply#domain.com";
$email_subject = "Test Email";
$to = $email;
$headers = "From: noreply#domain.com \r\n";
$headers .= "Bcc: noreply#domain.com \r\n";
$headers .= "Reply-To: me#domain.com \r\n";
$headers .= "Content-Type: text/html; charset=UTF-8\r\n";
$email_body = <<<EOM
<p color="#000000">Hello, $name.<br><br> This is a test email for mailing from the domain rather than the server.<br><br> </p>
EOM
;
mail($to, $email_subject, $email_body, $headers);
?>
Basically, I want PHP emails mailed by my domain and I don't know how to do this so any help would be appreciated, my web host doesn't seem able to help me with this.
Thanks in advance.
UPDATE
This code for the form.
<h1>The email gets sent to a bookings address.</h1>
<form method="post" name="process.php" action="process.php">
<p class= "whitetextsubsmall">Name:</p><br><input type="text" name="name"><br><br>
<p class= "whitetextsubsmall">Email Address:</p><br><input type="text" name="email"><br><br>
<br>
<input type="submit" value="Send Email">
</form>
And this code for process.php
<?php
$name = $_POST['name'];
$email = $_POST['email'];
use PHPMailer\PHPMailer\PHPMailer;
require 'vendor/autoload.php';
$mail = new PHPMailer;
$mail->isSMTP();
$mail->SMTPDebug = 2;
$mail->Host = 'smtp.hostinger.com';
$mail->Port = 587;
$mail->SMTPAuth = true;
$mail->Username = 'noreply#domain.com'; /* This is the sender of the bookings. */
$mail->Password = 'password';
$mail->setFrom('noreply#domain.com');
$mail->addAddress('bookings#domain.com', 'Company Bookings');
$mail->addReplyTo($email, $name); /* Reply to the user who submitted the form from the bookings email. */
$mail->Subject = 'Booking Request Test';
$mail->isHTML(TRUE);
$mail->Body = 'Message test <br> Booking Request from: $name <br><br> Email: $email.';
if(!$mail->send()) {
echo 'Message was not sent.';
echo 'Mailer error: ' . $mail->ErrorInfo;
} else {
echo 'Message has been sent.';
}
?>
You are mixing the PHPMailer syntax with PHP mail() syntax.
For the PHPMailer, use the following in your code.
<?php
$name = $_POST['name'];
$email = $_POST['email'];
use PHPMailer\PHPMailer\PHPMailer;
require 'vendor/autoload.php';
$mail = new PHPMailer;
$mail->isSMTP();
$mail->SMTPDebug = 2;
$mail->Host = 'smtp.hostinger.com';
$mail->Port = 587;
$mail->SMTPAuth = true;
$mail->Username = 'noreply#domain.com';
$mail->Password = 'password';
/* Set the mail sender. */
$mail->setFrom($email, $name);
/* Add a recipient. */
$mail->addAddress('noreply#domain.com', 'earningtoanimate');
/* Add a replyto. */
$mail->addReplyTo($email, $name);
/* Add a CC and Bcc. */
$mail->addCC('noreply2#domain.com', 'earningtoanimate2');
$mail->addBCC('noreply3#domain.com', 'earningtoanimate3');
/* Add email subject. */
$mail->Subject = 'Test Email';
/* Add email body. */
$mail->isHTML(TRUE);
$mail->Body = 'There goes your message.';
/* Finally send the mail. */
if(!$mail->send()) {
echo 'Message was not sent.';
echo 'Mailer error: ' . $mail->ErrorInfo;
} else {
echo 'Message has been sent.';
}
Test the above and give your feedback. Note, I didn't test code. Just wrote them here so it's possible to have some edits if need be.
For further reading visit PHPMailer documentation

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.

PHPMailer - HTML content getting blocked

I'm having trouble trying to send out a HTML email.
I can:
Connect to the server fine with SMTP and SSL
I can send a simple HTML email fine
But anything that resembles what I would call "normal" HTML content gets blocked EVERY TIME!
Anyone suggest anything to try? I don't see anything wrong with what I've done, but obvs there's something there...
So this code gets blocked for me:
require 'PHPMailerAutoload.php';
$mail = new PHPMailer;
$mail->isSMTP();
$mail->SMTPDebug = 2;
$mail->Debugoutput = 'html';
$mail->Host = "xxxx";
$mail->Port = 465;
$mail->SMTPAuth = true;
$mail->SMTPSecure = 'ssl';
$mail->Username = "xxx";
$mail->Password = "xxx";
$mail->setFrom('xxx', 'Me');
$mail->addReplyTo('xxx', 'Me');
$mail->addAddress('xxx#me.com');
$mail->Subject = 'Here come the bastards';
$mail->CharSet = 'UTF-8';
$mail->msgHTML('
<html>
<body>
<table style="width: 100%;background-color: #60bb98;">
<tr>
<td>
<a href="#">
<img src="http://mystorymycontent.com/wp-content/themes/MSMC/img/logo-new.gif" />
</a>
</td>
</tr>
<tr>
<td>HELLO EVERYONEZZZ
</td>
</tr>
</table>
</body>
</html>
');
$mail->AltBody = 'Heres all the copy from the HTML verison of the email. Theres a few lines about things and that';
if (!$mail->send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "Message sent!";
}
I'm using PHPMailer to send HTML mails and I had to do this :
$mail->IsHTML();
From the doc :
Before sending this out, we have to modify the PHPMailer object to
indicate that the message should be interpreted as HTML.
Technically-speaking, the message body has to be set up as
multipart/alternative. This is done with: $mail->IsHTML(true);
i agree with #FLX but in the phpmailer example it's written this way
$email ->IsHTML();
not
$mail ->IsHTML();
or the variable with you create the instance.
$VARIABLE = new PHPMailer();
.
.
.
.
$VARIABLE ->IsHTML();
it's just a suggestion

Use PHPmailer to send attachment

I'm using PHPmailer library to send emails and I need to send an attachment.
Currently the file is stored on the server and I have the link to the file stored in var $link.
I'm using the following to try and add the attachment but the email arrives with no attachment:
$phpmailer->AddAttachment('$link');
I have also tried it with a hardcoded path instead of my variable:
$phpmailer->AddAttachment('http://mysite.co.uk/link/to/my/file.pdf');
The email shows up but does not have any attachment.
I have tried using phpmailerException to grab any errors but get no response.
How else can I send an attachment with PHPmailer?
Full PHP code:
require_once 'library/PHPMailer.php';
$phpmailer = new PHPMailer();
$phpmailer->isSMTP(); //switch to smtp
$phpmailer->Host = 'smtp.sendgrid.net';
$phpmailer->SMTPAuth = true;
$phpmailer->SMTPSecure = 'ssl';
$phpmailer->Port = 465;
$phpmailer->Username = 'username';
$phpmailer->Password = 'password';
$phpmailer->AddAttachment('http://mysite.co.uk/blah/cv.pdf');
//$phpmailer->AddAttachment('$link');
$subject = 'Job Application';
$messageConfirmation = "The <b> 'Apply for Job' </b> form has recently been completed on <b>www.mysite.com.</b><br/><br/> <b>Please see contact details below:<br /><br/> </b>";
$messageConfirmation.= "<b>Applying for:</b> $title <br/><br/>";
$messageConfirmation .= "<b>Name:</b> $name <br/><br/><b>Surname:</b> $surname <br/><br/> <b>Email:</b> $email <br/><br/> <b>Comment:</b> $comment <br/><br/>";
$messageConfirmation .= "<b>CV:</b> $link<br /><br />";
$messageConfirmation .= "Please can you call them back in the next 24 hours. <br/><br/> Thank you \n\nMy Site<br/><br/>";
$imgheader = 'http://blah.co.uk/blah/wp-content/uploads/2014/11/header.png';
$imgfooter = 'http://blah.co.uk/blah/wp-content/uploads/2014/11/footer.png';
$message = '<!DOCTYPE HTML>'.
'<head>'.
'<meta http-equiv="content-type" content="text/html">'.
'<title>Email notification</title>'.
'</head>'.
'<body>'.
'<div id="header" style="width: 600px;height: auto;margin: 0 auto;color: #fff;text-align: center;font-family: Open Sans,Arial,sans-serif;">'.
'<img src="'.$imgheader.'" >'.
'</div>'.
'<div id="outer" style="width: 600px;margin: 0 auto;margin-top: 10px;">'.
'<div id="inner" style="width: 600px;margin: 0 auto; padding-left: 20px;background-color: #fff;font-family: Open Sans,Arial,sans-serif;font-size: 13px;font-weight: normal;color: #444;margin-top: 10px;">'.
'<p>'.$messageConfirmation .'</p>'.
'</div>'.
'</div>'.
'<div id="footer" style="width: 600px;height: auto;margin: 0 auto;text-align: center;padding: 10px;font-family: Verdena;">'.
'<img src="'.$imgfooter.'" >'.
'</div>'.
'</body>';
$phpmailer->IsHTML(true);
$phpmailer->AddAddress(CONTACTUSFORMEMAIL);
$phpmailer->From = CONTACTUSFORMEMAIL;
$phpmailer->FromName ='blah';
$phpmailer->WordWrap = 50; // set word wrap to 50 characters
$phpmailer->Subject = $subject;
$phpmailer->Body = $message;
$phpmailer->Send();
$data['success'] = true;
$data['message'] = 'Thank you for your application';
The Problem is that the function AddAttachment uses the function is_file() and is file returns false when accessing URLs (this also applies to relative URLs), is_file() only accepts filepaths. So normally phpmailer should add an error to the error container.
Hi Please try the following code
<?php
$mail = new PHPMailer();
$mail->From = $email_from;
$mail->SetFrom($email_from, $name_from);
$mail->AddAddress($email_to, $name_to);
$mail->AddReplyTo($email_from, $name_from);
$mail->MsgHTML($message_goes_here);
$mail->Subject = $your_subject;
$mail->AddAttachment($file_name_goes_here);
if($mail->Send()) {
} else {
echo "\r\nMail not sent. " . $mail->ErrorInfo;
}
?>
I know it might sound like a radical idea, but you could try reading the docs, or perhaps checking return values of functions, maybe even trying an up to date version of PHPMailer, or basing your code on a recent example.
PHPMailer will only throw exceptions if you enable them at instantiation with $mail = new PHPMailer(true);, and as #TheGreenKey said, it will set an error notice and produce an error message if you enable debugging.
If you want to add URL contents as an an attachment, you can do this:
$mail->addStringAttachment(file_get_contents('http://mysite.co.uk/link/to/my/file.pdf'), 'cv.pdf');`
That's never going to be fast, reliable or efficient though.
The method AddAttachment receives the path of the file.
If you see the source code, you will see that it uses fopen function to open the file, so, I think it doesn't work with links, you should download the file by yourself and pass the path to the function.
send any type of attachment using phpmailer.
<?php
require 'PHPMailer/class.phpmailer.php';
if(isset($_POST['send']))
{
$file_name = $_FILES['file']['name']; //attachment
$file_tmp =$_FILES['file']['tmp_name'];
$abc=microtime();
$path="upload/$abc".$file_name;
move_uploaded_file($file_tmp,$path); //moving attachment to upload folder
$mail = new PHPMailer(true);
$mail->IsSMTP();
$mail->SMTPAuth = false;
$mail->Port = 25;
$mail->Host = "localhost";
$mail->Username = "webmail_username";
$mail->Password = "webmail_password";
$mail->IsSendmail();
$mail->From = "abc#your.com";
$mail->FromName = "your.com";
$mail->AddAddress('receiver_emailid');
$mail->Subject = "Thank you for contacting US";
$mail->WordWrap = 80;
$body="Thank You For Contacting Us";
$mail->MsgHTML($body);
$mail->IsHTML(true);
$mail->AddAttachment($path,$file_name); //Attachment File
if(!$mail->Send())
{
echo "Mail Not Sent";
}
else
{
echo '<script language="javascript">';
echo 'alert("Thank You Contacting Us We Will Response You As Early Possible")';
echo '</script>';
}
}
for more details :- click here

Send email with attachment via PHPMailer

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

Categories