I am developing a small E-mail app using PHP, For sending out emails I use PHPMailer, All the functionalities work apart form one "Attachments". Attachments just don't go through with the sent email. I tried many different ways to fix it but the one I have now I belief is not far off a working order....
I will post small parts of code that deal with the Attachment process....
HTML Code:
<form action="php/smtp_saved.php" method="post">
<input type="file" name="attach" id="attach" />
</form>
PHP Code:
if ($_POST['action'] == 'Send') {
if (preg_match('<,>', $email['recipient'])) {
$address = explode(',', $email['recipient']);
if (sizeof($address) < 19) {
foreach ($address as $recipient) {
$save = new saveSaved();
$save->save($_SESSION['user'], $email['recipient'], gmdate('Y-m-d H:i:s', strtotime ('+1 hour')), $_SESSION['delete'],$email['HTML']);
require_once('../PHPMailer/PHPMailerAutoload.php');
require_once('../PHPMailer/class.smtp.php');
$mail = new PHPMailer;
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'smtp.gmail.com'; // Specify main and backup server
$mail->Port = '465';
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = $_SESSION['user']; // SMTP username
$mail->Password = $_SESSION['pass']; // SMTP password
$mail->SMTPSecure = 'ssl'; // Enable encryption, 'ssl' also accepted
$mail->From = $_SESSION['user'];
$mail->FromName = 'OneTwoTrade';
//$mail->addAddress($email['recipient']); // Add a recipient
//$mail->addAddress('ellen#example.com'); // Name is optional
$mail->addAddress(trim($recipient));
if (preg_match('<,>', $email['cc'])) {
$cc = explode(',', $email['cc']);
if (sizeof($cc) < 9) {
foreach ($cc as $carbonC) {
$mail->addCC($carbonC);
}
} else {
exit ('Max 10 Recipients Per Email');
}
} else {
$mail->addCC($email['cc']);
}
//$mail->addBCC('bcc#example.com');
$mail->WordWrap = 50; // Set word wrap to 50 characters
if(is_uploaded_file($_FILES['attach']['tmp_name'])) {
$file = $_FILES['attach']['name'];
$mail->AddAttachment($file);
}
/*
if(isset($_FILES['uploaded_file']) && $_FILES['uploaded_file']['error'] == UPLOAD_ERR_OK){
$mail->addAttachment($_FILES['uploaded_file']['tmp_name'],
$_FILES['uploaded_file']['name']);
}
*/
// Add attachments
//$mail->addAttachment('/tmp/image.jpg', 'new.jpg'); // Optional name
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = $email['subject'];
$mail->Body = $email['HTML'];
//$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
//$mail->SMTPDebug =1;
if (!$mail->send()) {
header("Location: ../saved_emails.php?error2");
//echo 'Message could not be sent.';
//echo 'Mailer Error: ' . $mail->ErrorInfo;
exit;
}
}
}
}
Can someone help me to spot a mistake or direct to a decent source of information....?
When attaching a file via a form add enctype="multipart/form-data" attribute to the form tag. I think the problem occurs because of this.
<form action="php/smtp_saved.php" method="post" enctype="multipart/form-data">
<input type="file" name="attach" id="attach" />
</form>
After a little search, I have found this: Both temp_name and name keys for the attached file are used in AddAttachment() function:
if(isset($_FILES['attach']) && $_FILES['attach']['error'] == UPLOAD_ERR_OK) {
$mail->AddAttachment($_FILES['attach']['tmp_name'], $_FILES['attach']['name']);
}
$file = $_FILES['attach']['name']; should be $file = $_FILES['attach']['tmp_name'];. The actual file data is in $_FILES['attach']['tmp_name']. $_FILES['attach']['name'] is just the name given to the uploaded file on the client side.
OK guys Want to thx all of you who tried to help me and pushed me to the solution, I managed to fix it this is what I had to do...
if(is_uploaded_file($_FILES['attach']['tmp_name'])) {
$file = $_FILES['attach']['tmp_name'];
$name = $_FILES['attach']['name'];
$mail->AddAttachment($file, $name);
}
:)))))))))))))))))))))))))))))))))))))))))
Works like a charm, just checked the PHPMailer Documentation and the AddAttachment Method needs two parameters,
Related
I'm experiencing an issue where only the text from body is appearing the image is coming through broken, does anyone see where I might be going wrong?
<?php
require("php/PHPMailer.php");
require("php/SMTP.php");
if (isset($_GET['email'])) {
$emailID = $_GET['email'];
if($emailID = 1){
$mail = new PHPMailer\PHPMailer\PHPMailer();
$mail->IsSMTP(); // enable SMTP
$mail->SMTPDebug = 1; // debugging: 1 = errors and messages, 2 = messages only
$mail->SMTPAuth = true; // authentication enabled
$mail->SMTPSecure = 'ssl'; // secure transfer enabled REQUIRED for Gmail
$mail->Host = "";
$mail->Port = 465; // or 587
$mail->IsHTML(true);
$mail->Username = "";
$mail->Password = "";
$mail->SetFrom("");
$mail->Subject = "Test";
$mail->Body = '<html><body><p>My Image</p><img src="images/EmailHeader.png" width="75%"></body></html>';
$mail->AddAddress("");
if(!$mail->Send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
}
else {
echo "Message has been sent";
}
}
}
?>
The image URL you are using is relative. You will need to use the full URL.
Instead of:
<img src="images/EmailHeader.png" width="75%">
It needs to be an absolute URL that the public can see, such as:
<img src="https://image-website.com/images/EmailHeader.png" width="75%">
You can not upload image with relative path in Email. You have to use full path because when the mail is send it require whole path to fetch the image content.,
Replace this line,
$mail->Body = '<html><body><p>My Image</p><img src="images/EmailHeader.png" width="75%"></body></html>';
With this line,
$mail->Body = '<html><body><p>My Image</p><img src="http://your-domainname.com/images/EmailHeader.png" width="75%"></body></html>';
Another option is that you can use use base64 images for it. But in your case you have to give full path.
I have a script that runs FPDF that creates and stores a PDF file in a folder.
That works fine.
My question is, am I able to send an email in that same script?
I have attempted it but i always get "Page cannot be displayed"
EDIT I dont want the files attached to the email. I just wish to send a email with some wording thats all.
Wont paste my whole code as its just the end that has the problem:
//display pdf
mkdir("FileBrowser/files/$name", 0777);
$total = count($_FILES['files']['name']);
// Loop through each file
for($i=0; $i<$total; $i++) {
//Get the temp file path
$tmpFilePath = $_FILES['files']['tmp_name'][$i];
//Make sure we have a filepath
if ($tmpFilePath != ""){
//Setup our new file path
$newFilePath = "FileBrowser/files/$name/" . $_FILES['files']['name'][$i];
//Upload the file into the temp dir
if(move_uploaded_file($tmpFilePath, $newFilePath)) {
//Handle other code here
}
}
}
$filename = "FileBrowser/files/$name/$name.pdf";
$pdf->Output($filename, 'F');
require ('PHPMailer/class.phpmailer.php');
$mail = new PHPMailer;
$mail->IsSMTP(); // Set mailer to use SMTP
$mail->Host = '****'; // Specify main and backup server
$mail->Port = 587; // Set the SMTP port
$mail->SMTPAuth = true;
$mail->Username = '****'; // SMTP username
$mail->Password = '****'; // SMTP password
$mail->From = 'Testing#test.co.za';
$mail->FromName = 'Testing';
$mail->AddAddress('****', 'John Smith'); // Add a recipient
$mail->IsHTML(true); // Set email format to HTML
$mail->Subject = 'Here is the subject';
$mail->Body = 'This is the HTML message body <strong>in bold!</strong>';
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
if(!$mail->Send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
exit;
}
?>
I'm trying to use the phpemailer to send emails from my server. It's working fine except one thing:
<?php
$serverName = "xxx.x.x.xxx"; //serverName\instanceName
$connectionInfo = array( "Database"=>"test", "UID"=>"xxxxxx", "PWD"=>"xxxxxx");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn ) {
echo "Connection established.<br />";
}else{
echo "Connection could not be established.<br />";
die( print_r( sqlsrv_errors(), true));
}
$sqll=sqlsrv_query($conn,"select bla from table");
//while($row=sqlsrv_fetch_array($sql))
// {
// $cnp=substr($row['bla'],-6);
// echo $bla;
// echo "<br>";
// }
$con=mysqli_connect("localhost","root","","database");
$sql=mysqli_query($con,"select * from table");
if(isset($_POST['submitted'])){
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;
$mail->SMTPAuth = true;
//Ask for HTML-friendly debug output
$mail->Debugoutput = 'html';
//Set the hostname of the mail server
$mail->Host = "xxxxxx";
//Set the SMTP port number - likely to be 25, 465 or 587
$mail->Port = xxx;
$mail->SMTPSecure = 'ssl';
//Whether to use SMTP authentication
$mail->SMTPAuth = true;
//Username to use for SMTP authentication
$mail->Username = "xxxxxx";
//Password to use for SMTP authentication
$mail->Password = "xxxxxx";
//Set who the message is to be sent from
$mail->setFrom('xxxxxx');
//Set an alternative reply-to address
$mail->addReplyTo('xxxxxx');
//Set who the message is to be sent to
while($row=mysqli_fetch_array($sql))
{
echo $row['bla'];
echo "<br>";
$mail->AddBCC($row['bla2']);
//Set the subject line
$mail->Subject = 'text text';
//Read an HTML message body from an external file, convert referenced images to embedded,
//convert HTML into a basic plain-text alternative body
//Replace the plain text body with one created manually
$mail->Body = "test test<br>link:<a href='http://localhost:8181/?cod=".$bla."'>click</a>";
$mail->IsHTML(true);
$mail->send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
echo 'Message has been sent';
}
}
}
?>
<form name="contact" method="post" action="">
<input type="submit" name="submitted" value="Submit">
</form>
The problem is: I'm trying to send an email with a different link to every email I've got in my database. I had put this part between the while:
$mail->AddBCC($row['email']);
//Set the subject line
$mail->Subject = 'text text';
//Read an HTML message body from an external file, convert referenced images to embedded,
//convert HTML into a basic plain-text alternative body
//Replace the plain text body with one created manually
$mail->Body = "test test<br>link:<a href='http://localhost:8181/?cod=".$bla."'>click</a>";
$mail->IsHTML(true);
$mail->send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
echo 'Message has been sent';
}
}
The emails are being sent but for example if i have 3 emails in my table then to email1 is sent the email 3 times, to email2 is sent 2 times and the email3 is sent one time. Why is that? why does the email being sent 3 times to the first email in my table?
I think, the problem is that you are adding the emails to the BCC, therefore, in the first loop, you are sending it to the first email, on the second, you are sending to the first email, and the newly added second email, and... so on...
You should clean the bcc before adding a new email.
call $mail->ClearBCCs() after $mail->send()
Clears all recipients assigned in the BCC array. Returns void.
--or--
Move your $mail->send() to after the loop to send all BCC addressed emails at once. (you may need to do this in batches depending on the mail server)
I've added the following line after I send the email:
$mail->ClearAllRecipients();
And now the emails are sent sent only one time. Thanks to all!
i am using phpmailler for sending mail,mail works successfully but without attachments. i want to send mail with attachments.
i have tried this code.
thanks in advance.
$s2="select * from tbl_new_user where login_name='".$rw['clientname']."'";
$q2=mysql_query($s2) or die($s2);
$row=mysql_fetch_array($q2);
$s22="select * from tbl_job_schedule where clientname='".$rw['clientname']."' and jobdate='".$_SESSION['strmonth']."-".$_REQUEST['dt']."-".$_SESSION['yy']."'";
$q22=mysql_query($s22) or die($s22);
$row2=mysql_fetch_array($q22);
$mail = new PHPMailer;
$mail->IsSMTP(); // Set mailer to use SMTP
$mail->Host = 'smtpout.secureserver.net'; // Specify main and backup server
$mail->Port = '80';
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'username'; // SMTP username
$mail->Password = 'password'; // SMTP password
$mail->SMTPSecure = ''; // Enable encryption, 'ssl' also accepted
$mail->SMTPDebug = 1;
$mail->From = 'abc#abc.com';
$mail->FromName = 'abc#abc.com';
$mail->AddAddress($row['client_email'], ''); // Add a recipient
$mail->AddAddress($row['client_email2']); // Name is optional
$mail->AddAddress($row['client_email3']);
$mail->AddAddress($row['client_email4']);
$mail->AddAddress($row['client_email5']);
$mail->AddAddress($row['client_email6']);
$mail->AddReplyTo('info#example.com', 'Information');
//$mail->AddCC('cc#example.com');
//$mail->AddBCC('bcc#example.com');
$mail->WordWrap = 50;
// Set word wrap to 50 characters
if($row2['file1']!='')
{
$mail->AddAttachment('kurtacompany/techreporting/upload/'.$row2['file1'].''); // Add attachments
}
if($row2['file2']!='')
{
$mail->AddAttachment('kurtacompany/techreporting/upload/'.$row2['file2'].''); // Add attachments
}
if($row2['file3']!='')
{
$mail->AddAttachment('kurtacompany/techreporting/upload/'.$row2['file3'].''); // Add attachments
}
if($row2['file4']!='')
{
$mail->AddAttachment('kurtacompany/techreporting/upload/'.$row2['file4'].''); // Add attachments
}
if($row2['file5']!='')
{
$mail->AddAttachment('kurtacompany/techreporting/upload/'.$row2['file5'].''); // Add attachments
}
if($row2['file6']!='')
{
$mail->AddAttachment('kurtacompany/techreporting/upload/'.$row2['file6'].''); // Add attachments
}
if($row2['file7']!='')
{
$mail->AddAttachment('kurtacompany/techreporting/upload/'.$row2['file7'].''); // Add attachments
}
if($row2['file8']!='')
{
$mail->AddAttachment('kurtacompany/techreporting/upload/'.$row2['file8'].''); // Add attachments
}
if($row2['file9']!='')
{
$mail->AddAttachment('kurtacompany/techreporting/upload/'.$row2['file9'].''); // Add attachments
}
if($row2['file10']!='')
{
$mail->AddAttachment('kurtacompany/techreporting/upload/'.$row2['file10'].''); // Add attachments
}
//$mail->AddAttachment('/tmp/image.jpg', 'new.jpg'); // Optional name
$mail->IsHTML(true); // Set email format to HTML
$mail->Subject = 'Reporting';
$mail->Body = '<p>This is an automated email report for the work done today.
Below are the comments showing on what we have worked,if you have any questions please go to the reporting URL provided and update your comment or can send a separate email to me directly on my email ID provided.</p>
<b>Work Comments : "'.$row2['client_cmnt'].'"</b>';
$mail->AltBody = '';
if(!$mail->Send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
exit;
}
echo 'Message has been sent';
echo "<script>window.close()</script>";
}
Make sure the path your are using for your attachments is valid.
i.e. does a file exist at kurtacompany/techreporting/upload/'.$row2['file3'] ?
It might be as simple as you missing a / from the beginning to indicate it should start searching from the root directory. If in doubt, try an absolute link to confirm:
http://www.mywebsite.com/kurtacompany/techreporting/upload/'.$row2['file3']
I am rather puzzled with this one.
//SMTP servers details
$mail->IsSMTP();
$mail->Host = "mail.hostserver.com";
$mail->SMTPAuth = false;
$mail->Username = $myEmail; // SMTP usr
$mail->Password = "****"; // SMTP pass
$mail->SMTPKeepAlive = true;
$mail->From = $patrickEmail;
$mail->FromName = "***";
$mail->AddAddress($email, $firstName . " " . $lastName);
$mail->WordWrap = 50;
$mail->IsHTML(true);
$mail->Subject = $client_subject;
$mail->Body = $client_msg;
if($mail->Send())
{
$mail->ClearAllRecipients();
$mail->ClearReplyTos();
$mail->ClearCustomHeaders();
...
$mail->From = "DO_NOT_REPLY#...";
$mail->FromName = "****";
$mail->AddAddress($ToEmail1, "***"); //To: (recipients).
$mail->AddAddress($ToEmail2, "***"); //To: (recipients).
$mail->WordWrap = 50;
$mail->IsHTML(true);
$mail->Subject = $notification_subject;
$mail->Body = $notification_msg;
if($mail->Send())
{
...
The first email sends fine. The second one doesn't. What could be the reason for that behavior? Am I missing some kind of reset?
Update: using a different mail server seems to work so apparently it's a setting of that specific mail server causing problems. Any idea what that could be?
Some providers impose restrictions on the number of messages that can be sent within a specific time span. To determine if your problem depends by a provider "rate limit", you should try to add a pause after the first send. For example:
if ($mail->Send()) {
sleep(10); // Seconds
...
if ($mail->Send()) {
...
}
}
Then, by progressively lowering the sleep time, you should be able to determine which is the rate limit.
Try this:
As #Felipe Alameda A mentioned Remove $mail->SMTPKeepAlive = true;
// for every mail
if(!$mail->Send())
{
echo 'There was a problem sending this mail!';
}
else
{
echo 'Mail sent!';
}
$mail->SmtpClose();
IMHO you need to create new PHPMailer object for every sent email. If you want to share some common setup, use something like this:
$mail = new PHPMailer();
/* Configure common settings */
while ($row = mysql_fetch_array ($result)) {
$mail2 = clone $mail;
$mail2->MsgHTML("Dear ".$row["fname"].",<br>".$cbody);
$mail2->AddAddress($row["email"], $row["fname"]);
$mail2->send();
}
I think your problem is $mail->SMTPAuth = false;
It is hard to believe there are ISP or SMTP providers that don't require authentication, even if they are free.
You may try this to check for errors instead of or in addition to checking for send() true:
if ( $mail->IsError() ) { //
echo ERROR;
}
else {
echo NO ERRORS;
}
//Try adding this too, for debugging:
$mail->SMTPDebug = 2; // enables SMTP debug information
Everything else in your code looks fine. We use PHPMailer a lot and never had any problems with it
The key may lie in the parts you have omitted. Is the domain of the sender of both emails the same? Otherwise the SMTP host may see this as a relay attempt. If you have access to the SMTP server logs, check these; they might offer a clue.
Also, check what $mail->ErrorInfo says... it might tell you what the problem is.
i personally would try to make small steps like sending same email.. so just clear recipients and try to send identical email (this code works for me). If this code passes you can continue to adding back your previous lines and debug where it fails
and maybe $mail->ClearCustomHeaders(); doing problems
//SMTP servers details
$mail->IsSMTP();
$mail->Host = "mail.hostserver.com";
$mail->SMTPAuth = false;
$mail->Username = $myEmail; // SMTP usr
$mail->Password = "****"; // SMTP pass
$mail->SMTPKeepAlive = true;
$mail->From = $patrickEmail;
$mail->FromName = "***";
$mail->AddAddress($email, $firstName . " " . $lastName);
$mail->WordWrap = 50;
$mail->IsHTML(true);
$mail->Subject = $client_subject;
$mail->Body = $client_msg;
// all above is copied
if($mail->Send()) {
sleep(5);
$mail->ClearAllRecipients();
$mail->AddAddress('another#email.com'); //some another email
}
...
Try with the following example.,
<?php
//error_reporting(E_ALL);
error_reporting(E_STRICT);
date_default_timezone_set('America/Toronto');
require_once('../class.phpmailer.php');
//include("class.smtp.php"); // optional, gets called from within class.phpmailer.php if not already loaded
$mail = new PHPMailer();
$body = file_get_contents('contents.html');
$body = eregi_replace("[\]",'',$body);
$mail->IsSMTP(); // telling the class to use SMTP
$mail->Host = "mail.yourdomain.com"; // SMTP server
$mail->SMTPDebug = 2; // enables SMTP debug information (for testing)
// 1 = errors and messages
// 2 = messages only
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->Host = "mail.yourdomain.com"; // sets the SMTP server
$mail->Port = 26; // set the SMTP port for the GMAIL server
$mail->Username = "yourname#yourdomain"; // SMTP account username
$mail->Password = "yourpassword"; // SMTP account password
$mail->SetFrom('name#yourdomain.com', 'First Last');
$mail->AddReplyTo("name#yourdomain.com","First Last");
$mail->Subject = "PHPMailer Test Subject via smtp, basic with authentication";
$mail->AltBody = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
$mail->MsgHTML($body);
$address1 = "whoto#otherdomain.com";
$address2 = "whoto#otherdomain.com";
$mail->AddAddress($address1, "John Doe");
$mail->AddAddress($address2, "John Peter");
$mail->AddAttachment("images/phpmailer.gif"); // attachment if any
$mail->AddAttachment("images/phpmailer_mini.gif"); // attachment if any
if(!$mail->Send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "Message sent!";
}
?>
Note : Better you can make a multiple user email and name as an ARRAY, like
<?php
$recipients = array(
'person1#domain.com' => 'Person One',
'person2#domain.com' => 'Person Two',
// ..
);
foreach($recipients as $email => $name)
{
$mail->AddCC($email, $name);
}
(or)
foreach($recipients as $email => $name)
{
$mail->AddAddress($email, $name);
}
?>
i think this may help you to resolve your problem.
I think you've got organizational problems here.
I recommend:
Set your settings (SMTP, user, pass)
Create new email object with info from an array holding messages and to addresses
Send email
Goto step 2