Can't attach files from form using phpMailer - php

I need send an email with attachments (words, pdf...) from a Contact form.
The email is sent well, but with .pdf not attached and with .docx I have a file without extension (choosing office to run it looks perfectly)
This is my code:
<form method="post" action="components/trabajamail.php" enctype="multipart/form-data">
<input type="file" name="userfile" accept="application/pdf,application/msword">
<button type="submit">Send</button>
My php file based on This:
$mail = new PHPMAILER ();
$mail->setFrom ( 'from#mail.com', 'Mailer' ); // Add a recipient
$mail->addAddress ( 'to#mail.com' );
$mail->isHTML ( true ); // Set email format to HTML
$mail->Subject = 'Subject';
$mail->Body = "Message";
$mail->CharSet = 'UTF-8';
// Attach the uploaded file
if (array_key_exists ( 'userfile', $_FILES )) {
$uploadfile = tempnam ( sys_get_temp_dir (), sha1 ( $_FILES ['userfile'] ['name'] ) );
if (move_uploaded_file ( $_FILES ['userfile'] ['tmp_name'], $uploadfile )) {
$mail->addAttachment ( $uploadfile, 'File' );
}
}
if (! $mail->send ()) {
echo "<div class='alert alert-warning'><strong>Error!</strong></div>";
} else {
echo "<div class='alert alert-success'><strong>Success!</strong></div>";
}
The last if never show me nothing, but i cant find the problem
I have read some threads with similar problems and I have used examples from the officinal page but I do not get this to work

Related

Custom PHP Mailer attachment not attached with email

I have customize mailer function where except file attachment, rest of things are working well. To make it simplify, I have added only code related to attachment. As output, I can see file uploaded to server but it's going to attach in email. I am getting all details in email except file attachment. it's customize mailer class which I have created but not sure why attachment not sending to email.
Mailer.class.php
<?php
class Mailer
{
private $addAttachment = [];
public function addAttachment($addAttachment)
{
if (empty($addAttachment))
{
$this->setError('No Attachments','empty');
}else{
$this->addAttachment[] = $addAttachment;
echo $addAttachment;
}
return $this;
}
}
For Sending test.php
require_once 'Mailer.class.php';
$toemails = array("my_email_address#gmail.com");
$toemail = implode(',', $toemails);
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$attachment = $_FILES["uploaded_file"]["tmp_name"];
$folder = '/uploads/';
$file_name1 = $_FILES["uploaded_file"]["name"];
move_uploaded_file($_FILES["uploaded_file"]["tmp_name"], "$folder".$_FILES["uploaded_file"]["name"]);
print_r($_FILES);
$mailer = new Mailer(true);
$mailer->setToEmail($toemail)
->setFromName(isset($_POST['fname'])?$_POST['fname']:'')
->setFromEmail(isset($_POST['email'])?$_POST['email']:'')
->setSubject('Application Regarding'.$_POST['Title'])
->addAttachment('/uploads/'.$_FILES["uploaded_file"]["name"])
->setBody($body)
->run();
exit();
if(!$mailer->sendMail()) {
echo "Something has gone wrong, please contact the site administrator or try again.";
}
else {
echo "Email Successfully Submitted";
}
print "</pre>";
}
?>
print_r($_FILES) gives me following Output for attachment:
Array
(
[uploaded_file] => Array
(
[name] => Image_Manager.pdf
[type] => application/pdf
[tmp_name] => /tmp/phplBV7gV
[error] => 0
[size] => 150300
)
)

PHPMailer form input file

I'm loosing my mind since yesterday, I'm pretty sure I'm close but...
Well, I have a HTML form with an input type file and I would like get the file submitted attached with the email sent.
Here is my HTML (simplified):
<form enctype="multipart/form-data" id="contact-form-cv" name="contact-form-cv" method="POST" data-name="Contact Form CV">
<div class="form-group">
<div class="controls">
<!-- FILE -->
<input type="hidden" name="MAX_FILE_SIZE" value="300000">
<input type="file" name="cv-file" id="file" class="input-file form-control special-form my-file">
<label for="file" class="btn btn-tertiary js-labelFile">
<span class="js-fileName"><i class="fa fa-upload"></i> Attach CV*</span>
</label>
<!-- Button -->
<button id="cv-valid-form" type="submit" class="btn btn-lg submit">Submit</button>
</div>
</div>
JS
I have a JS file used to display alert messages when the user is filling the form :
$("#contact-form-cv [type='submit']").click(function(e) {
e.preventDefault();
// Get input field values of the contact form
var cvuser_file = $('input[name=cv-file]').val();
// Datadata to be sent to server
post_data = {'cvuserFile':cvuser_file};
// Ajax post data to server
$.post('../contact-me-cv.php', post_data, function(response){
// Load json data from server and output message
if(response.type == 'error') {
...
} else {
...
}
}, 'json');
});
PHP
<?php
// Use PHP To Detect An Ajax Request
if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
// Exit script for the JSON data
$output = json_encode(
array(
'type'=> 'error',
'text' => 'Request must come from Ajax'
));
die($output);
}
if(empty($_POST["cvuserFile"])) {
$output = json_encode(array('type'=>'error', 'text' => '<i class="icon ion-close-round"></i> Please attach your CV'));
die($output);
}
$path = 'upload/' . $_FILES["cvuserFile"]["name"];
move_uploaded_file($_FILES["cvuserFile"]["tmp_name"], $path);
require 'php/class/class.phpmailer.php';
$mail = new PHPMailer();
//Set PHPMailer to use SMTP.
$mail->IsSMTP();
//Set SMTP host name
$mail->Host = 'smtp.gmail.com';
//Set TCP port to connect to
$mail->Port = '587';
//Set the encryption system to use - ssl (deprecated) or tls
$mail->SMTPSecure = 'tls';
//Set this to true if SMTP host requires authentication to send email
$mail->SMTPAuth = true;
$mail->isHTML(true);
//Provide username and password yo your google account
$mail->Username = "*****#gmail.com";
$mail->Password = "*******";
$mail->WordWrap = 50;
$mail->From = $_POST["cvuserEmail"];
$mail->FromName = $_POST["cvuserName"];
$mail->setFrom('*****', '**** ****');
$mail->addAddress('*****', 'John Doe');
//Set the subject line
$mail->AddAttachment($path);
$mail->Subject = 'New message from my website!';
$mail->Body = 'Hello' . "\r\n" ;
if(!$mail->send())
{
$output = json_encode(array('type'=>'error', 'text' => '<i class="icon ion-close-round"></i> Oops! Looks like something went wrong, please check your PHP mail configuration.'));
die($output);
unlink($path);
}
else
{
$output = json_encode(array('type'=>'message', 'text' => '<i class="icon ion-checkmark-round"></i> Hello '.$_POST["cvuserName"] .', Your message has been sent, we will get back to you asap !'));
die($output);
}
?>
Is someone able to save my life on that matter?
I'm well receiving the form submission but without the file, I just have an empty file in the email.
Note that I'm working under MAMP for now.
Thanks to this amazing community
You need to use move_uploaded_file (http://php.net/manual/en/function.move-uploaded-file.php) to move your uploaded file in to an accessible location on your file system.
You variable $uploadfile should contain the path to the file.
tempnam (http://php.net/manual/en/function.tempnam.php) only creates a new (empty) file - it doesn't move your uploaded file!

Trouble getting file attachment to work with Swiftmailer

I am trying to use swiftmailer to upload a file from a form, but I still get an error.
I really don't know where I'm going wrong. Any help and explanation would be greatly appreciated.
index.html
<form method="post" action="mail.php" enctype="multipart/form-data">
Attach a file: <input type="file" id="attachment" name="attachment">
<button type="submit">SUBMIT</button>
</form>
mail.php (correct)
Then it imports mail_sender.php
mail_sender.php
<?php
$file = 'attachment/'.basename($_FILES['attachment']['name']);
$upload = move_uploaded_file($_FILES['attachment']['tmp_name'],$file);
if(isset($timeZone) && $timeZone != ""){
date_default_timezone_set($timeZone);
}
else{
date_default_timezone_set("UTC");
}
// Require the Swift Mailer library
require_once 'swift_required.php';
$messageText = "";
if($emailMethod == 'phpmail'){
$transport = Swift_MailTransport::newInstance();
}elseif($emailMethod == 'smtp'){
$transport = Swift_SmtpTransport::newInstance( $outgoingServerAddress, $outgoingServerPort, $outgoingServerSecurity )
->setUsername( $sendingAccountUsername )
->setPassword( $sendingAccountPassword );
}
$mailer = Swift_Mailer::newInstance($transport);
// Creating the message text using fields sent through POST
foreach ($_POST as $key => $value)
{
// Sets of checkboxes will be shown as comma-separated values as they are passed in as an array.
if(is_array($value)){
$value = implode(', ' , $value);
}
$messageText .= ucfirst($key).": ".$value."\n\n";
}
if(isset($_POST['email']) && isset($_POST['name']) ){
$fromArray = array($_POST['email'] => $_POST['name']);
}else{ $fromArray = array($sendingAccountUsername => $websiteName); }
$message = Swift_Message::newInstance($emailSubject)
->setFrom($fromArray)
->addPart(strip_tags($messageText), 'application/pdf')
->attach(Swift_Attachment::fromPath($file))
->setTo(array($recipientEmail => $recipientName))->setBody($messageText, 'text/html');
}
// Send the message or catch an error if it occurs.
try{
echo($mailer->send($message));
}
catch(Exception $e){
echo($e->getMessage());
}
exit;
?>
Thanks in advance

Sending attachment(s) in email

I've never touched PHP, but was tasked with fixing an Intern's code..
I am trying to attach a file being uploaded to an email that I am sending. The email sends, but without the file. I am using PHPMailerAutoUpload.php (found on GitHub).
Here's the code I am using.
The attachment is being saved via move_uploaded_file
move_uploaded_file( $resume['tmp_name'] , $up_dir .basename( $random_var . '_wse_' . $resume['name'] ) )
Note: I have commented out the move_uploaded_file function to make sure I wasn't getting rid of the attachment.
require_once('phpmailer/PHPMailerAutoload.php');
$mail = new PHPMailer(true);
$mail->IsSMTP();
$mail->SMTPDebug = 2;
$mail->SMTPAuth = false;
$mail->Host = 'oursmtp';
$mail->Port = 25;
$mail->setFrom( $_POST['E-mail'] , $_POST['first_name'] . " " . $_POST['last_name'] );
$mail->addAddress( 'test#test.com' );
$mail->Subject = "Test" . #date('M/D/Y');
$mail->msgHTML($msgDoc);
if (isset($_FILES['uploaded_file']) &&
$_FILES['uploaded_file']['error'] == UPLOAD_ERR_OK) {
$mail->AddAttachment($_FILES['uploaded_file']['tmp_name'],
$_FILES['uploaded_file']['name']);
}
if (!$mail->send()) {
$mailError = $mail->ErrorInfo;
$outcomeArr = array(
'outcome'=>'failure',
'message'=>'Error' . $mailError
);
echo json_encode( $outcomeArr );
exit();
} else {
// success
$outcomeArr = array(
'outcome'=>'success',
'message'=>'Thank you'
);
echo json_encode( $outcomeArr );
}
From what I have read, $_FILES is a temporary storage for uploaded files in PHP. With this code, the email sends, but with no attachment (only a link to the uploaded file location).
I tried following this, but it isn't working for me.
Your intern was apparently a rockstar that had no need to check for or indicate error conditions, and then mail will send even if there's no attachment or if there was an error during the upload. Change these bits to the code to tell you why the file wasn't attached:
if (isset($_FILES['uploaded_file']) && $_FILES['uploaded_file']['error'] == UPLOAD_ERR_OK) {
if( ! $mail->AddAttachment($_FILES['uploaded_file']['tmp_name'], $_FILES['uploaded_file']['name']) ) {
echo 'Error adding attachment: ' . $mail->ErrorInfo;
}
} else if( !isset($_FILES['uploaded_file']) ) {
echo 'No uploaded file found';
} else {
echo 'Uploaded file error: ' . $_FILES['uploaded_file']['error'];
}

How can I easily allow users to upload multiple files?

I'm looking for a very easy way to allow users to upload files (html) to my site. I've tried things like plupload and uploadify and they seem to difficult to implement/buggy. Are there any simple solutions out there?
I actually just worked on this issue recently. Ill let you use my code i wrote. What it does is as soon as a user browses for one file, another upload box pops up and so on and so on. And then, i use phpmailer to send the files as email attachments. Look up phpmailer for more details...
The javascript to add more upload fields.. (put in HEAD)
<script type="text/javascript">
function addElement()
{
var ni = document.getElementById('org_div1');
var numi = document.getElementById('theValue');
var num = (document.getElementById('theValue').value -1)+ 2;
numi.value = num;
var newDiv = document.createElement('div');
var divIdName = num; newDiv.setAttribute('id',divIdName);
newDiv.innerHTML = '<input type="file" class="fileupload" size="80" name="file' + (num) + '" onchange="addElement()"/> <a class="removelink" onclick=\'removeElement(' + divIdName + ')\'>Remove This File</a>';
// add the newly created element and it's content into the DOM
ni.appendChild(newDiv);
}
function removeElement(divNum)
{
var d = document.getElementById('org_div1');
var olddiv = document.getElementById(divNum);
d.removeChild(olddiv);
}
</script>
The HTML..
<div id="org_div1" class="file_wrapper_input">
<input type="hidden" value="1" id="theValue" />
<input type="file" class="fileupload" name="file1" size=
"80" onchange="addElement()" /></div>
The process.php page. NOTE: MUST EDIT!!! Search phpmailer and download their class.phpmailer.css class. Edit the configs in the file. Create and "uploads" directory.
<?php
require("css/class.phpmailer.php");
//Variables Declaration
$name = "Purchase Form";
$email_subject = "New Purchase Ticket";
$body = "geg";
foreach ($_REQUEST as $field_name => $value){
if (!empty($value)) $body .= "$field_name = $value\n\r";
}
$Email_to = "blank#blank.com"; // the one that recieves the email
$email_from = "No reply!";
//
//==== PHP Mailer With Attachment Func ====\\
//
//
//
$mail = new PHPMailer();
$mail->IsQmail();// send via SMTP MUST EDIT!!!!!
$mail->From = $email_from;
$mail->FromName = $name;
$mail->AddAddress($Email_to);
$mail->AddReplyTo($email_from);
foreach($_FILES as $key => $file){
$target_path = "uploads/";
$target_path = $target_path .basename($file['name']);
if(move_uploaded_file($file['tmp_name'], $target_path)) {
echo "the file ".basename($file['name'])." has been uploaded";
}else {
echo "there was an error";
}
$mail->AddAttachment($target_path);
}
$mail->Body = $body;
$mail->IsHTML(false);
$mail->Subject = $email_subject;
if(!$mail->Send())
{ echo "didnt work";
}
else {echo "Message has been sent";}
foreach($_FILES as $key => $file){
$target_path = "uploads/";
$target_path = $target_path .basename($file['name']);
unlink($target_path);}
}
?>
Let me know if you have any questions!!
Check out the jQuery Mulitple File Upload Plugin. The Uploading multiple files page in the PHP documentation will give you an idea what the submitted result looks like and some examples for working with it.

Categories