using phpmailer class to send attachment in email: Could not access file - php

I have this function below "sendMail", to send emails using phpmailer class.
And its working fine, Im already sending emails with sucess.
But now Im trying to add one attachment to my function, so I added this to my code:
$mail->AddAttachment(BASE.'/'.'images/2014/05/image4.jpg','image 4');
And Im having this error:
Could not access file: localhost/project/images/2014/05/image4.jpg
But this directory is exactly the correct directory to my image, so I dont understand why this error is happening.
Somebody there knows if Im missing something here?
My function to send email:
function sendMail($subject,$message,$emissor,$emissorName,$receptor,$receptorName, $reply = NULL, $replyName = NULL){
require_once('mail/class.phpmailer.php');
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->SMTPAuth = true;
$mail->IsHTML(true);
$mail->SMTPSecure = "tls";
$mail->Host = MAILHOST;
$mail->Port = MAILPORT;
$mail->Username = MAILUSER;
$mail->Password = MAILPASS;
$mail->From = utf8_decode($emissor);
$mail->FromName = utf8_decode($emissorName);
$mail->Subject = utf8_decode($subject);
$mail->Body = utf8_decode($message);
$mail->AddAddress(utf8_decode($receptor),utf8_decode($receptorName));
$mail->AddAttachment(BASE.'/'.'images/2014/05/image4.jpg','image 4');
if($reply != NULL){
$mail->AddReplyTo(utf8_decode($reply),utf8_decode($replyNome));
}
if($mail->Send()){
return true;
}
else{
return false;
}
}
And my server acess file, when I acess this url: htttp://localhost/projeto/banner-imagens/2014/05/bib_idh.jpg, I get my image!

Your path is incorrect. Remove BASE and replace it with the actual file path to the project folder. Put in the full path or relative path based on the script.
Add an attachment from a path on the filesystem.
http://phpmailer.github.io/PHPMailer/classes/PHPMailer.html#method_addAttachment
IF that doesn't fix it also make sure the file is readable. Meaning the file permissions are set so that web server can access the file.

Related

Could not access file PHPMailer in Laravel

I am creating a project using Laravel. I want to send an email with an attachment; however, this is not working. I know there are many questions regarding this, but unfortunately, I could not find the answer.
$file1 = $_FILES['file']['tmp_name'];
$path = base_path();
$path .= '/public/uploads/'.$_FILES['file']['name'];
move_uploaded_file($_FILES['file']['tmp_name'], $path);
DB::statement("UPDATE orders SET pdf = '".$fileData."' WHERE id = '".$id."'");
$mail = new PHPMailer\PHPMailer(); // create a n
$mail->isSMTP();
$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 = 'smtp.gmail.com';
$mail->Port = 465; // or 587
$mail->IsHTML(true);
$mail->Username = 'xxxxx#gmail.com';
$mail->Password = 'xxxxxx';
$mail->SetFrom('xxxxx#gmail.com', 'xxxxx.com');
$mail->Subject = 'xxxxx Ready';
$mail->Body = $text;
$mail->AddAddress("xxxxxx.com");
$mail->AddAttachment($pdfLink, $fileData, $encoding = 'base64', $type = 'application/pdf');
$mail->Send();
The generated PDF link is accessible, and when I open the PDF link in a new tab, it works. However, I don't know why PHPMailer told me that I could not access.
I got the solution, i am just getting the file from server. This is the reason this is not working.The file should upload from actual path.
login to your gmail account, go to Enable access
MAIL_DRIVER=smtp
MAIL_HOST=smtp.googlemail.com
MAIL_PORT=465
MAIL_USERNAME=ENTER_YOUR_GMAIL_USERNAME
MAIL_PASSWORD=ENTER_YOUR_GMAIL_PASSWORD
MAIL_ENCRYPTION=ssl
and all must be working fine )

PhpMailer not working with html

I am using PhpMailer class to send emails that contains html,I noticed that if the body on email contain img tags the email not receiving and no errors showing.
Any suggestions?
my code so far:
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->SMTPAuth = true;
$mail->SMTPSecure = 'ssl';
$mail->Host = "smtp.gmail.com";
$mail->Port = 465;
$mail->Username = "myusername";
$mail->Password = "mypassword";
$mail->setFrom($from);
$mail->addAddress($to);
$mail->Subject = $subject;
$mail->Body =$body;
$mail->IsHTML(true);
if ($mail->send()) {
return 1;
} else {
return 0;
}
if you're trying to send it from localhost and read in gmail, it won't work because gmail often creates proxy image links. you need to send image links that direct to internet-accessible location. That's probably it.
If you're sending email with links to internet-accessible locations, please attach them to the question and I'll update the answer, too.
EIDT: after chat with the asker, it was determined the email HTML was missing normal HTML markup: <html><body>ACTUALCONTENT</body></html>, after adding those,image shown up correctly.
You can use the AddEmbeddedImage method to attach image to your body. So your code should look like this.
$mail->AddEmbeddedImage($_REQUEST['image_name'], 'ImageName');
And then in your $body you can use this image
$body.= "<img src='cid:ImageName' />";

Error Sending Emails using PHPMailer over SMTP

I've had a look around as to why my PHP script was not sending any emails when I had the $mail->isSMTP(); set.
Before I go into the problem, I would like to point out that I am using mailgun.org as my SMTP server. My PHP script is simple, I have an HTML form that forwards data to a PHP file which in turn calls the PHPMailer script and sends an email.
Here is the code to my PHP Script:
date_default_timezone_set('Asia/Manila');
require 'phpmailer/PHPMailerAutoload.php';
// include 'phpmailer/class.phpmailer.php';
// require 'phpmailer/class.smtp.php';
$mail = new PHPMailer;
//$mail->isSMTP();
$mail->SMTPDebug = 0;
$mail->Debugoutput = 'html';
$mail->Host = "smtp.mailgun.org";
$mail->Port = 465;
$mail->SMTPAuth = true;
$mail->SMTPSecure = "ssl";
$mail->Username = ""; //Username removed
$mail->Password = ""; //Password removed
$mail->setFrom('', ''); //Email address and Name removed
$mail->addReplyTo($userMail, $firstName);
$mail->addAddress('emailOne#example.com', 'Name'); //Actual Values Changed
$mail->addAddress('emailTwo#example.com', 'Name'); //Actual Values Changed
$mail->addAddress('emailThree#example.com', 'Name'); //Actual Values Changed
$mail->Subject = 'New Application for website by '. $firstName;
$mail->msgHTML($theMessage);
$mail->AltBody = $theMessage;
if (!$mail->send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else { //Some HTML code here
}
Now then, as you can see, I have commented out the $mail->isSMTP(); line. This is because whenever I try to use it, the code does not load, and after a long wait gives a 500 error. (Sadly, by cPanel setup does not allow me to view apache logs).
I tried importing just the class.phpmailer.php file, but that gave me a fatal error that the class SMTP was not defined, which was expected. I then included the class.smtp.php file which gave me the same 500 error.
I had a look around StackOverflow and came across this answer however it did not help my case.
I have had a look at Mailgun's logs, but they have no record of the script even trying to connect.
Additional Information: If it matters, I have the following files in the same directory:
- sendMail.php //The script above
- class.phpmailer.php
- class.smtp.php
- PHPMailerAutoload.php
- index.html //Not important in this situation.
I hope someone will be able to help me out, I'm relying on the non-smtp method for now. :/
Try this working fine..!
date_default_timezone_set('Asia/Manila');
require 'phpmailer/PHPMailerAutoload.php';
// include 'phpmailer/class.phpmailer.php';
// require 'phpmailer/class.smtp.php';
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->SMTPDebug = 1;
$mail->SMTPAuth = true;
$mail->SMTPSecure = 'ssl';
$mail->Host = "smtp.gmail.com";
$mail->Port = 465;
$mail->Username = ""; //Username removed
$mail->Password = ""; //Password removed
$mail->addReplyTo($userMail, $firstName);
$mail->SetFrom('emailOne#example.com', 'my name');
$mail->Subject = 'New Application for website by '. $firstName;$mail->MsgHTML($theMessage);
$mail->AddAddress('aswad#yahoo.com', 'my name');
if($mail->Send()) {
echo "Message sent!";
}else {
echo "Mailer Error: " . $mail->ErrorInfo;
}

PHP - Dompdf and PHPMailer unexpected behavior

I am working on a web application using PHP as a server-side and a jQuery framework as a client-side.
One of the scenarios of the application is to send an email with pdf file attached I am doing this using PHPMailer and Dompdf libraries.
I had created a function named sendMail in a file name send.php accept 4 params (receiver email,subject,data,email number) the last param is because I have 5 different emails may be sent depending on the situation and data param is the data will be rendered in the html email body.
The problem is when I call the function from send.php it work as expected the email sent and pdf file created and attached to the email .
but when I require send.php in any other file and call sendMail function I get the email only without any pdf file and the file not even generated or saved on the server.
send.php
<?php
require_once 'dompdf/autoload.inc.php';
// reference the Dompdf namespace
use Dompdf\Dompdf;
require 'PHPMailerAutoload.php';
$body = "test message";
sendMail('peter#w34.co','MLS mail',$body,5);
function sendMail($email,$subject,$body,$index){
$mail = new PHPMailer;
$mail->IsSMTP(); // telling the class to use SMTP
$mail->SMTPDebug = 1; // debugging: 1 = errors and messages, 2 = messages only
$mail->SMTPAuth = true; // SMTP authentication
$mail->SMTPSecure = 'tls'; // secure transfer enabled REQUIRED for GMail
$mail->Host = "smtp.gmail.com"; // SMTP server
$mail->Port = 587; // SMTP Port
$mail->Username = "peterwilson.intake34#gmail.com"; // SMTP account username
$mail->Password = "Password"; // SMTP account password // TCP port to connect to
$mail->From = 'peter#example.com';
$mail->FromName = 'Wilson';
$mail->addAddress($email); // Add a recipient
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = $subject;
$mail->Body=$body;
// instantiate and use the dompdf class
$dompdf = new Dompdf();
$dompdf->loadHtml($body);
// Render the HTML as PDF
$dompdf->render();
$output = $dompdf->output();
$file_to_save= "../work-orderes/file.pdf";
file_put_contents($file_to_save, $output);
$mail->addAttachment('../work-orderes/file.pdf');
if(!$mail->send()) {
// echo $mail->ErrorInfo;
} else {
return 1;
}
}
?>
save.php
<?php
require("sendSmtp/send.php");
session_start();
$body = "Hello World!";
sendMail('peter#w34.co','MLS mail',$body,5);
?>
Any suggestions about why Dompdf not works when calling it from any other file ??
What I have tried
removing dompdf and reinstall the latest stable version from
here
cleaning all code and just leave sendMail function and calling it
try to write the code from the beginnig
I solved it finally!
after debugging I found that everything going fine till $output = $dompdf->output(); after that I get an error on save the file using $file_to_save= "../work-orderes/file.pdf";
this work properly when I call the function sendMail() from send.php but when I call it from another file I get an error regarding accessing the path.
The Answer here that I should use the absolute path not the relative one like below
$file_to_save= $_SERVER['DOCUMENT_ROOT']."\work-orderes/file.pdf";
now the file saved successfully and attached to the email like expected!

PHP Mailer - Internal Server Error

I have been trying to make the contact form on my website to work and I've spent weeks trying to figure it out and I couldn't.
Here's the problem - I purchased a web template and it came with the PHPMailer. I'm now done plugging my content into the template, but the contact form has been a pain. I've followed the instructions the best I know on the PHP file, but it's giving me an "Internal Server Error" when I am testing the contact form.
Here's the code that came with my purchase:
$name = trim($_POST['name']);
$email = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];
$site_owners_email = 'name#mydomain.com'; // Replace this with your own email address
$site_owners_name = 'My Name'; // Replace with your name
try {
require_once('/Beta-BRC/php/PHPMailer/class.phpmailer.php');
$mail = new PHPMailer();
$mail->CharSet = 'UTF-8';
$mail->From = $email;
$mail->FromName = $name;
$mail->Subject = "[WEB Form] ".$subject;
$mail->AddAddress($site_owners_email, $site_owners_name);
$mail->Body = $message;
$mail->Mailer = "smtp";
$mail->Host = "smtp.gmail.com"; // Replace with your SMTP server address
$mail->Port = 465;
$mail->SMTPSecure = "SSL";
$mail->SMTPAuth = true; // Turn on SMTP authentication
$mail->Username = "name#mydomain.com"; // SMTP username
$mail->Password = "mypassword"; // SMTP password
//echo "true";
if($mail->Send()) {
echo "true";
} else {
echo "Error sending: " . $mail->ErrorInfo;
}
} catch (Exception $e) {
echo $e;
}
Quick note - I've alrealy tried using a GMAIL account on this part but it still does not work.
$mail->Username = "name#mydomain.com"; // SMTP username
$mail->Password = "mypassword"; // SMTP password
There's no need to log into Gmail with phpmailer. Below is an example of my phpmailer function using the default settings.
public function sendEmail($toaddress,$toname,$subject,$message){
if($template = file_get_contents('/home/username/domains/mydomain.com/public_html/html/email-template.html')){
$template = str_replace("[SUBJECT]",$subject,$template);
$template = str_replace("[CONTENT]",nl2br($message),$template);
$mailer = new PHPMailer;
$mailer->XMailer = "Organization Name 4.0.0";
if($this->is_logged_in()){
$mailer->AddCustomHeader("X-Originating-User-ID",$this->acct['id']);
}
$mailer->AddCustomHeader("X-Originating-IP",$_SERVER['REMOTE_ADDR']);
$mailer->setFrom("outbound#mydomain.com","From Name");
$mailer->AddAddress($toaddress,$toname);
$mailer->Subject = $subject;
$mailer->MsgHTML($template);
$mailer->AltBody = $message;
return $mailer->Send();
}else{
return false;
}
}
The email address listed doesn't actually exist. The email is just being sent from my server and phpmailer just says it's from that email address.
Try modifying my function to suit your needs and let me know how that works.
Note: You'll need to make sure your mail server is turned on for this to work
Although you don't have to use my function at all. Try debugging your code by checking some error logs on your server. Typically in the apache error logs (if you're running apache, however). Checking error logs is a huge part of troubleshooting your code and often can help you become more proactive.
I hope this helps even the slightest!
The specific cause of the Internal Server Error is the incorrect path you've supplied to the require_once statement that loads the PHPMailer class.
The path you've supplied is /Beta-BRC/php/PHPMailer/class.phpmailer.php, where the correct statement should be
require_once('/home/trsta/public_html/Beta-BRC/php/PHPMailer/class.phpmailer.php');
or perhaps more generally:
require_once($_SERVER['DOCUMENT_ROOT'].'/home/trsta/public_html/Beta-BRC/php/PHPMailer/class.phpmailer.php');
You've provided effectively a URL, but PHP requires the path in the server file system, which is not the same.
That should get you past this error. It's possible that there are others.

Categories