Send MULTIPLE Attachments from Input on Form via PHPMailer - php

I have searched all around but cannot find a specific answer. I have a form there the user can put in MULTIPLE attachments. I am using PHPMailer to send the submitted form. I have looked everywhere and it seems people who explain how to upload multiple files but NOT from user input. THANK YOU!.
My attachment upload button name is "attachments"
if (isset($_POST["submit"])) {
$optionOne = $_POST['optionOne'] ;
$tick = $_REQUEST['tick'] ;
$results = $_REQUEST['results'] ;
$option = $_POST['option'] ;
$option = $_POST['requirements'] ;
$mail = new PHPMailer;
//Server settings
$path = 'upload/' . $_FILES["attachments"]["name"];
move_uploaded_file($_FILES["attachments"]["tmp_name"], $path);
$mail->SMTPDebug = 2; // Enable verbose debug output
$mail->isSMTP(); // Set mailer to use SMTP
$mail->isSendmail(); // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'bonnie'; // SMTP username
$mail->Password = 'bonnie'; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 587; // TCP port to connect to
//Recipients
$mail->setFrom('bonniethompson12345#gmail.com', 'Mailer');
$mail->addAddress('bonniethompson12345#gmail.com'); // Add a recipient
$mail->isHTML(true);
$mail->AddAttachment($path); // Set email format to HTML
$mail->Subject = 'Form submission';
$mail->Body = 'This course is identified in my Work Plan and Learning Agreement: $optionOne \n \n I am attending this session because: $tick \n \n What would you like to achieve as a result of your attendance: $results \n \n Do you require adjustments or additions to the session delivery to support your participation: $option \n \n Please provide details of your requirments: $requirements</b>';
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
//$mail->AddAttachment('Logo.png');
if(!$mail->send()) {
echo "Failure to send";
} else {
echo "Message has been sent successfully";
}
}
<p>Please upload any supporting documentation to support your registration request </p>
<div class="browse-button">
<input type="file" name="attachments" multiple="multiple"></input>
</div>

The thing you're missing is the naming of the input element; you need to use array naming to make it handle multiple files correctly, so build it like this:
<input type="file" name="attachments[]" multiple="multiple">
The important bit is the [] at the end of the element name, which means that the multiple values will get submitted as an array. When you receive a submission from that, try a var_dump($_FILES) so you can see what you've got. You should also check the return value of move_uploaded_file() rather than assuming it works. Also you don't need a closing </input> tag if you're using HTML5.
The multiple file upload example provided with PHPMailer demonstrates exactly what you're asking, and includes the error checking I mentioned.
It's also covered in the PHP docs. Look harder next time!

Related

PHP to send email with buttons that prompts answer from recipient and send back value to actual database

I would like to ask, how can i make the email i sent out to consist of two buttons which is accept or reject that when the recipient click on reject/accept, the value actually sends back to the database.
Does anyone have idea on this method ?
PHP
$subject1="E-Calibration Registration Form Approval Notice for HOD";
$message1="Dear HOD, you currently have a pending E-Calibration Registration Form waiting for approval.";
$to1="67508#siswa.unimas.my";
//starting outlook
com_load_typelib("outlook.application");
if (!defined("olMailItem")) {define("olMailItem",0);}
$outlook_Obj1 = new COM("outlook.application") or die("Unable to start Outlook");
//just to check you are connected.
echo "<center>Loaded MS Outlook, version {$outlook_Obj1->Version}\n</center>";
$oMsg1 = $outlook_Obj1->CreateItem(olMailItem);
$oMsg1->Recipients->Add($to1);
$oMsg1->Subject=$subject1;
$oMsg1->Body=$message1;
$oMsg1->Save();
$oMsg1->Send();
echo "</br><center>Email has been sent succesfully</center>";
This is my php code for my email
The full solution consists of multiple parts:
Part 1: Send email script
I will use PHPMailer as an example. You should refer to the links for installation details.
<?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.example.com'; //Set the SMTP server to send through
$mail->SMTPAuth = true; //Enable SMTP authentication
$mail->Username = 'user#example.com'; //SMTP username
$mail->Password = 'secret'; //SMTP password
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; //Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` encouraged
$mail->Port = 587; //TCP port to connect to, use 465 for `PHPMailer::ENCRYPTION_SMTPS` above
//Recipients
$mail->setFrom('sender#example.com', 'Sender');
$mail->addAddress('67508#siswa.unimas.my');
//Content
$mail->isHTML(true); //Set email format to HTML
$mail->Subject = 'E-Calibration Registration Form Approval Notice for HOD';
$id = 12345;
$body = '<p>Dear HOD, you currently have a pending E-Calibration Registration Form waiting for approval.</p>';
$body.= '<p>Accept Reject</p>';
$mail->Body = $body;
$mail->send();
echo 'Message has been sent';
} catch (Exception $e) {
echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}
Part 2: Response script
<?php
if(!isset($_GET['id'], $_GET['answer'])) {
die('missing parameters');
}
$id = (int)$_GET['id']; // assume ID is an integer
$answer = trim($_GET['answer']);
if(!in_array($answer, array('accept', 'reject'))) {
die('invalid answer');
}
// TODO: Save the info to MS Access DB
// read https://stackoverflow.com/questions/19807081/how-to-connect-php-with-microsoft-access-database for the codes
?>
So this functionality should start in the email you are sending. The email template or code should first of all be HTML to be able to accommodate the buttons. So the email mode should be HTML. These buttons can be linked to a form or direct links which denote Accept or Reject actions.
These can be the PHP file which then sends that information to the database.
<input type="submit" name="accept" value="Accept">
<input type="submit" name="accept" value="Reject">
Then in your PHP code, you can have your normal code to read these values and store them in the database.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// collect value of input field
$data = $_REQUEST['accept'];
// store in DB
}

Get data from database and use in mail function in php

I am new to php and currently doing a project
I stored data in database by using a form.
I have a mail function, when on clicking the submit button, a mail is send to reputed email id. I am using phpmailer library.
This is my mail function
class mail
{
public function sendMail(){
require 'vendor/autoload.php';
$mail = new PHPMailer(); // Passing `true` enables exceptions or null without exception
//Server settings
$mail->SMTPDebug = 0; // Enable verbose debug output
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'smtp.gmail.com'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'xyz#gmail.com'; // SMTP username
$mail->Password = 'xyz123'; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 587; // TCP port to connect to
//Recipients
$mail->setFrom('xyz#gmail.com', 'xyz');
$mail->addAddress('abc#gmail.com', 'abc');
$mail->addCC('zxc#gmail.com');
//Attachments
$mail->addAttachment('lob.png', 'sample.png'); // Add attachments
// Optional name
//Content
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = 'Report';
$mail->Body = 'This is the HTML message body <b>in bold!</b>';
if (!$mail->send()) {
return "Error sending message" . $mail->ErrorInfo;
} else {
return "Message sent!";
}
}
}
This is my code to store data into database as send.php
if(isset($_POST['submit'])){
$name = $_POST['name'];
$age = $_POST['age'];
$quality = $_POST['quality'];
$sql = "INSERT INTO user(name,age,quality) VALUES('$name','$age','$quality')";
}
This is my html form
<form class="quality" method="POST" action="send.php">
<label for="name">Name</label>
<input type = "text" class = "form-quality" name="name" value="" / >
<label for="age">Age</label>
<input type="text" class ="form-quality" name="age" value="" / >
<label for="quality">Quality</label>
<input type="ratio" class ="form-quality" name="quality" value="E" / >
<input type="ratio" class ="form-quality" name="quality" value="P" / >
</form>
1) How to get the data's from database ?
2) In mail function previously sending emails to one or two id's, but i need as when i select "value = E" from ratio button , it should send to one email and if i select "value= P" it should send to another email based on user selected values stored in the database
Anyone with a best reply will be much more needed help for me
Assuming that when you said you are doing a project is within an education environment and not for professional purpose:
When you get the data from you form on if(isset($_POST['submit'])) send those variables to the sendMail function as parameters, then inside the function you can make a variable using your parameters to build a well formed message that you can send in your $mail->Body .
Inside the function you can also check if what you recieved on your radio-button input was "E" or "P" and give different values (receivers email) and pass it to your addAddress.
If this is not a school project you MUST be very carefully on what you send or you insert to the db. Validate everything you recieve on your form before sending and go ahead and check the link in the comments about SQL injection.
This should've been a comment insetead of a reply but i don't have enough reputation to comment so sorry about that.

how to send two different email to two different email addresses using PHPMailer in php

I am trying to send two different emails to two different recipients using PHPmailer but only the second email is arriving.
My code:
/**
* This code shows settings to use when sending via Google's Gmail servers.
*/
//SMTP needs accurate times, and the PHP time zone MUST be set
//This should be done in your php.ini, but this is how to do it if you don't have access to that
date_default_timezone_set('Etc/UTC');
require 'PHPMailer/PHPMailerAutoload.php';
//Create a new PHPMailer instance
$mail = new PHPMailer;
//Tell PHPMailer to use SMTP
$mail->isSMTP();
//Enable SMTP debugging
// 0 = off (for production use)
// 1 = client messages
// 2 = client and server messages
$mail->SMTPDebug = 2;
//Ask for HTML-friendly debug output
$mail->Debugoutput = 'html';
//Set the hostname of the mail server
$mail->Host = 'smtp.gmail.com';
// use
// $mail->Host = gethostbyname('smtp.gmail.com');
// if your network does not support SMTP over IPv6
//Set the SMTP port number - 587 for authenticated TLS, a.k.a. RFC4409 SMTP submission
$mail->Port = 587;
//Set the encryption system to use - ssl (deprecated) or tls
$mail->SMTPSecure = 'tls';
//Whether to use SMTP authentication
$mail->SMTPAuth = true;
//Username to use for SMTP authentication - use full email address for gmail
$mail->Username = "olaozias#gmail.com";
//Password to use for SMTP authentication
$mail->Password = "password";
//Set who the message is to be sent from
$mail->setFrom('olaozias#gmail.com', 'Department of Information Science');
//Set an alternative reply-to address
$mail->addReplyTo('olaozias#gmail.com', 'Department of Information Science');
//Set who the message is to be sent to
$mail->addAddress($email , 'Parent');
//Set the subject line
$mail->Subject = 'Student Attendance System';
//Read an HTML message body from an external file, convert referenced images to embedded,
//convert HTML into a basic plain-text alternative body
//$mail->msgHTML(file_get_contents('contents.html'), dirname(__FILE__));
//Replace the plain text body with one created manually
$mail->Body = 'Dear Parent \r\n This email is sent from the university of gondar , Department of information science to inform you that your child '. $firstname.' has been registered for semester '.$semister. ' in order to see your child attendance status and to communicate easily with our department use our attendance system. First download and install the mobile application which is attached in this email to your phone and use these login credentials to login to the system \r\n Your child Id: '.$student_no. '\r\n Password: '.$parent_pass.'\r\n Thank you for using our attendance system \r\n University of Gondar \r\n Department of Information Science ';
//Attach an image file
//$mail->addAttachment('AllCallRecorder.apk');
$mail->send();
$mail->ClearAddresses();
$mail->AddAddress($stud_email,'Student');
$mail->Subject = 'Student Attendance System';
$mail->Body = "email 2";
//send the message, check for errors
if (!$mail->Send()) {
//echo "Mailer Error: " . $mail->ErrorInfo;
echo '
<script type = "text/javascript">
alert("Mailer Error: " . $mail->ErrorInfo);
window.location = "student.php";
</script>
';
} else {
echo '
<script type = "text/javascript">
alert("student Added successfully and an Email the sent to email address provided");
window.location = "student.php";
</script>
';
//echo "Message sent!";
}
the second email is delivered successfully but the first one is not.
There are a couple of different possibilities. The fact that the second one is sending properly is a good indication that your code is working in general. Focusing on the first one, I'd suggest three things:
Add error checking to the first send() call. You have if (!$mail->Send()) {... on the second one, but you aren't checking the first one. You can use $mail->ErrorInfo as you have in a comment in the second part. (By the way, the $mail->ErrorInfo you have in the script tag will not work. Variables in single quoted strings like that will not be parsed, so you'll just get the literal string "$mail->ErrorInfo" there if there is an error.)
Add error checking to the first addAddress() call. PHPMailer will give you an error that you can check if the email address is invalid for some reason. As far as the code you've shown here, $email appears to be undefined, but so does $stud_email and you've said that one is working properly, so I assume those are both defined somewhere before the code that you've shown here, but a possible cause for this is that $email is undefined or doesn't have the value you expect it to.
The email is being sent, but not received. It's pretty easy for a message to be mis-identified as spam at multiple points between the sender and the receiver. This is more difficult to diagnose, but if you add the error checking to the first send() call and don't get any errors, you'll at least be able to rule that out as a point of failure.
you can do an array with de emails and subject.
$recipients = array(
'person1#domain.com' => 'Person One',
'person2#domain.com' => 'Person Two',
// ..
);

PHPMailer: Mass Emails - Send all variable messages at once, instead of individually

i'm currently trying to figure out the best way to do this.
The current system i've made sends email one by one and fills in the information for each entry as in the array, such as email, first name and last name.
The problem here is if i send alot of messages it takes forever to run through as it's calling a function everytime, instead i want it to send them all at once through one single function.
I know you can add multiple to's but then the body of the email won't send the correct information relative to each email. If anyone can help me with this i'd really appreciate it, as i've searched all over for a solution.
<?php
require '../phpmailer/PHPMailerAutoload.php';?>
<?php
/* Block List */
$blocklist = array('emailblocked#gmail.com', 'emailblocked2#gmail.com');
$emaillist = array(
array(
'Email'=>'example#gmail.com',
'First Name'=>'John',
'Last Name'=>'Doe'
),
array(
'Email'=>'example2#gmail.com',
'First Name'=>'Joe',
'Last Name'=>'Doe'
),
array(
'Email'=>'example3#gmail.com',
'First Name'=>'Jane',
'Last Name'=>'Doe'
),
);
foreach($emaillist as $emailkey){
if (in_array($emailkey['Email'], $blocklist)) {
echo 'Message has been been blocked for '.$emailkey['Email'].'<br>';
}else{
$mail = new PHPMailer;
// $mail->SMTPDebug = 3; // Enable verbose debug output
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'smtp.mandrillapp.com'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'username#example.com'; // SMTP username
$mail->Password = 'passwordgoeshere'; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 587; // TCP port to connect to
$mail->From = 'noreply#example.com';
$mail->FromName = 'Example';
$mail->addAddress($emailkey['Email'], $emailkey['First Name'].' '.$emailkey['Last Name']); // Add a recipient
$mail->addReplyTo('info#example.com', 'Information');
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = $emailkey['First Name'].' '.$emailkey['Last Name'];
$emailtemp = file_get_contents('templates/temp-1.html');
$emailtempfilteremail = str_replace("[[email]]", $emailkey['Email'], $emailtemp);
$emailtempfilterfirstname = str_replace("[[firstname]]", $emailkey['First Name'], $emailtempfilteremail);
$emailtempfilterlastname = str_replace("[[lastname]]", $emailkey['Last Name'], $emailtempfilterfirstname);
$mail->Body = $emailtempfilterlastname;
$mail->AltBody = 'This is a spicy email!';
if(!$mail->send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
echo 'Message has been sent to '.$emailkey['Email'].'<br>';
}
$mail->ClearAllRecipients();
}
}
?>
Thank you
There's an example of how to send to a list from a database efficiently in the examples bundled with PHPMailer. There's nothing inherently likely to get you blacklisted by using PHPMailer for sending large volumes, but you do need to tread carefully. Mandrill isn't magic - it's as vulnerable as anything else to being blocked if you send spam through it.
If you want to send 50 simultaneously from PHP, fire up multiple processes with the pcntl extension, but it won't actually help you very much as you'll be increasing overhead enormously. You can set SMTPKeepAlive = true in PHPMailer which will reduce overhead a lot (it avoids making a new connection for every message), but it still won't send simultaneous messages - nothing will. There isn't an option in SMTP to send multiple messages with different bodies simultaneously on the same connection.
Sending to a big list during a page load in a browser is very unreliable; use a cron script or background process to do your actual sending and just set it up through your web interface. One tip if you are waiting for a page load - call ignore_user_abort() early on so that it won't stop sending if your browser closes the connection - and beware the page refresh! If you want to send much faster, install a local mail server like postfix and use that to relay - it will be far faster and more reliable than sending directly.
Yes, it is possible with a modification of your code, the problem is not with the PHPMailer itself, but with your approach. You should avoid using an new instance of the class inside a loop (this leads to memory exhaustion with large lists), instead, only invoke $mail->addAddress(...) or $mail->Subject(...) inside the foreach loop.
If you read the source code of the PHPMailer, you will notice how exactly the functions addAddress(), Subject() or Body() works.
Your code should look something like this:
<?php
/*Move your "generic" initialization outside the loop*/
$mail = new PHPMailer;
// $mail->SMTPDebug = 3; // Enable verbose debug output
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'smtp.mandrillapp.com'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'username#example.com'; // SMTP username
$mail->Password = 'passwordgoeshere'; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 587; // TCP port to connect to
$mail->From = 'noreply#example.com';
$mail->FromName = 'Bet Monkey';
$mail->isHTML(true); // Set email format to HTML
$mail->addReplyTo('info#example.com', 'Information');
$emailtemp = file_get_contents('templates/temp-1.html');
$mail->AltBody = 'This is a spicy email!';
/*Start the loop by adding email addresses*/
foreach($emaillist as $emailkey){
if (in_array($emailkey['Email'], $blocklist)) {
echo 'Message has been been blocked for '.$emailkey['Email'].'<br>';
}else{
$mail->addAddress($emailkey['Email'], $emailkey['First Name'].' '.$emailkey['Last Name']); // Add a recipient
$mail->Subject = $emailkey['First Name'].' '.$emailkey['Last Name'];
$emailtempfilteremail = str_replace("[[email]]", $emailkey['Email'], $emailtemp);
$emailtempfilterfirstname = str_replace("[[firstname]]", $emailkey['First Name'], $emailtempfilteremail);
$emailtempfilterlastname = str_replace("[[lastname]]", $emailkey['Last Name'], $emailtempfilterfirstname);
$mail->Body = $emailtempfilterlastname;
if(!$mail->send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
echo 'Message has been sent to '.$emailkey['Email'].'<br>';
}
$mail->ClearAllRecipients();
}
}
Using the above approach I personally have send hundreds of thousands emails, but, as they say in the comments - you'll risking to be blacklisted (you can check here or here for details).

PHPMailer from is showing as Root User

I am using PHP Mailer to send emails and i am using SMTP
here is the code i am using:
$email = new PHPMailer();
$email->IsSMTP(); // telling the class to use SMTP
$email->Host = "mail.integradigital.co.uk"; // SMTP server
$email->SMTPDebug = 2; // enables SMTP debug information (for testing)
// 1 = errors and messages
// 2 = messages only
$email->SMTPAuth = true; // enable SMTP authentication
$email->Host = "mail.integradigital.co.uk"; // sets the SMTP server
$email->Port = 26; // set the SMTP port for the GMAIL server
$email->Username = "sending#************.co.uk"; // SMTP account username
$email->Password = "********"; // SMTP account password
$email->SetFrom($result["emailfrom"]);
$email->FromName($result["emailfrom"]);
$email->Subject = $result["subject"];
$email->Body = $result["message"];
but its sending and showing as from Root User - root#localhost
i know i can change this in the class.phpmailer.php file but i want to be able to set it in the code above
is this possible?
Okay, in short:
$email->From = "email.address#gmail.com";
$email->FromName = "Support Team";
This worked out for me.
Wrap the whole thing in a try catch. And initialize phpmailer with exceptions enabled
$email = new PHPMailer(true);
It looks like the default values are used. So something goes wrong when calling setFrom(). And it's failing silently because it returns false without exceptions enabled.
try {
// your mail code here
} catch (phpmailerException $e) {
echo $e->getMessage();
}
And change the setting of email and from name to:
$email->setFrom($result["emailfrom"], $result["emailfrom"]);
FromName is a property not a method.
class.phpmailer.php file contains the "var $FromName = 'Root User';" section which can be changed to "Desired Name" from "Root User" and have your job done.
Inside your form when you are getting the 1. email and 2. name it should look like this
<input type="text" name="emailfrom">
<input type="text" name="namefrom">
Inside your php code it should look like this.
$mail->setFrom($_POST['emailfrom'],$_POST['namefrom']);
I was having the same issue when I was using these settings on infinityhost I hope this helps.
$mail->Port = 587; // Which port to use, 587 is the default port for TLS security.
$mail->SMTPSecure = 'tls'; // Which security method to use. TLS is most secure.```
I had this problem when I was sending only the first parameter to setFrom(), as name <email>.
setFrom() did not know how to parse that construction.
Changing to two separate parameters solved the issue.
Use:
$mail->setFrom('here email add of sender','here name of the sender');
First parameter is the email addres if it is empty or not a valid email address it will show as ROOT user while sending mail using php mailer
For PHPMailer Version: 5.1
This worked for me:
$mail->SetFrom('no-reply#example.com', 'Name From');
Hope it works.
Edit your phpmailer.php, changing:
if($mail->Send()){
to:
if (mail($_POST["email"],
$_POST["subject"],
$_POST["message"],
$_POST["sender"])) {
echo'Email Sended';
}
*HTML*
<form action="phpmailer.php" method="POST">
<input type="hidden" name="sender" value="From: Support Team<Support#email.com>"/>
</form>
if ($mail->Send()) { is set to Auto root, if you send email and From is not declared at the same time.

Categories