I'm using PHPMailer to send customers receipt of their order in a pdf format. PDF creation works like a dream, but it just wont attach it to mail. I've tried to my gmail and my own servers email, but it wont send the attachment. Here's my code:
<?php
//Lähetä tilausvahvistus
require_once('mail/class.phpmailer.php');
$bodytext = '
Olemme vastaanottaneet tilauksenne '. $ordernumber .'.
Tilaamanne tuotteet löytyvät liitteestä.'
;
$email = new PHPMailer();
$email->From = 'no-reply#xxx.fi';
$email->FromName = 'no-reply#xxx.fi';
$email->Subject = 'Olemme vastaanottaneet tilauksenne ' . $ordernumber;
$email->Body = $bodytext;
$email->AddAddress('christian.nikkanen#gmail.com');
$email->AddAttachment('kuitit/kuitti777.pdf','kuitti777.pdf');
return $email->Send();
?>
I've tried relative path and direct path, but no, it wont send.
Have you validate your path correctly?
Try to write your path again using $_SERVER['DOCUMENT_ROOT']
check that PHP is interpreting your path to the file correctly. Try sticking the $pathtofile in a session and using that rather than statically assigning (or dumping it to output) so you can ensure it isn't a simple path issue.
Related
I'm using this function to send a mail, and it works perfectly:
mail('emailhere','subjecthere','contenthere');
I'm also using this code to create a word file and offer the user to download it:
// I use my templace that's with my files :
$templateProcessor = new TemplateProcessor('Template.docx');
// I fill the template values from an sql query :
$templateProcessor->setValue('titre', $options['titre']);
$templateProcessor->setValue('source', $options['source']);
$templateProcessor->setValue('auteur', $options['auteur']);
$templateProcessor->setValue('date_pub', $options['date_pub']);
$templateProcessor->setValue('contenu', $options['contenu']);
// I give the user the file (I don't fully understand how this works but it does)
header("Content-Disposition: attachment; filename=$title.docx");
$templateProcessor->saveAs('php://output');
What I'm trying to do is, I want to create a word file from that template, put it inside that mail and send it
I apologize for the lack of code that I tried, but I really don't know where to start even.
I have been recommended to use this:
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
$email = new PHPMailer();
$email->SetFrom('you#example.com', 'Your Name'); //Name is optional
$email->Subject = 'Message Subject';
$email->Body = $bodytext;
$email->AddAddress( 'destinationaddress#example.com' );
$file_to_attach = 'PATH_OF_YOUR_FILE_HERE';
$email->AddAttachment( $file_to_attach , 'NameOfFile.pdf' );
return $email->Send();
But I don't know what the path to the file is?
Add the following lines of code:
// Create a temporary file to store the template.
$temp_file = tempnam(sys_get_temp_dir(), 'PHPTemplate');
// Save the template
$templateProcessor->saveAs($temp_file);
// Attach the temporary file (template) to the email
$mailer->addAttachment($temp_file, 'nameofile.docx');
// Send Email
return $email->Send();
I'm using xpertmailer to send email direct to the remote SMTP server following an MX lookup. This works really well and works on an old closed source NAS drive running PHP4 and on current PHP5 boxes.
<?php
define('DISPLAY_XPM4_ERRORS', true); // display XPM4 errors
require_once '/path-to/SMTP.php'; // path to 'SMTP.php' file from XPM4 package
$f = 'me#mydomain.net'; // from mail address
$t = 'client#destination.net'; // to mail address
// standard mail message RFC2822
$m = 'From: '.$f."\r\n".
'To: '.$t."\r\n".
'Subject: test'."\r\n".
'Content-Type: text/plain'."\r\n\r\n".
'Text message.';
$h = explode('#', $t); // get client hostname
$c = SMTP::MXconnect($h[1]); // connect to SMTP server (direct) from MX hosts list
$s = SMTP::Send($c, array($t), $m, $f); // send mail
// print result
if ($s) echo 'Sent !';
else print_r($_RESULT);
SMTP::Disconnect($c); // disconnect
?>
I'm now trying to add an attachment to it, but I've no idea how to get an attachment to be included and sent.
Anyone any ideas how I can do this ?
Thanks
Example:
$m = new MAIL;
// attach source
$a = $m->Attach('text message', 'text/plain');
$f = '/path/image.gif';
// attach file '$f', disposition 'inline' and give a name 'photo.gif' with ID value (this ID value can be used in embed HTML images)
$a = $m->Attach(file_get_contents($f), FUNC::mime_type($f), 'photo.gif', null, null, 'inline', MIME::unique());
echo $a ? 'attached' : 'error';
i want to send an email with attachment using wordpress' wp_mail function.
With this function it works fine to send emails but the attachment isn't there when i check my email.
function dd_send_email(){
$dd_path = $_POST['upload_image'];
// echo $dd_path;
$email_sent = false;
// get email template data
$email_template_object = dd_get_current_options();
// if email template data was found
if ( !empty( $email_template_object ) ):
// setup wp_mail headers
$wp_mail_headers = array('Content-Type: text/html; charset=UTF-8');
$mail_attachment = $dd_path;
// use up_mail to send email
$email_sent = wp_mail( array( 'example#mail.no') , $email_template_object['dd_emne_forhaandsbestilling'], $email_template_object['dd_email_text_forhaandsbestilling'], $wp_mail_headers, $mail_attachment );
endif;
return $email_sent;
}
The variable $dd_path (something like: http://localhost/norskeanalyser/wp-content/uploads/Testanalyse-2.pdf) contains the path of the file which i do upload from the media uploader in another function.
Thanks for your help!
I did found the answer by myself. Because wp_mail needs the file path like this /uploads/2016/03/example.jpg we have to convert our url to a path like this.
I did achive this by doing the following and thought i can share it with you:
// change url to path
$dd_url = $_POST['upload_image'];
$dd_path = parse_url($dd_url);
// cut the path to right directory
$array = explode("/norskeanalyser/wp-content", $dd_path['path']);
unset($array[0]);
$text = implode("/", $array);
and then i did save the $text into $mail_attachment and called it in wp_mail like above.
I have this function that sends emails to customers from a folder files/weekly reports.
// Sends the "Weekly Report.pdf" file (from /files/weekly reports)
public function send_pdf_customer($prod_id){
if ($this->is_connected()){
$prod_row = $this->kas_model->get_prod_row_by_id($prod_id);
var_dump($prod_row[0]->prod_client_email);
$email = $prod_row[0]->prod_client_email;
// All recipients who get the email.
//$recipients = "me#example.com, may#example.pro, daniel.m#exmaple.com, maayan#exmaple.pro";
// $recipients = "me#example.com";
$recipients = $email;
$this->load->library('email');
$this->email->from('me#example.pro', 'example - weekly Report');
$this->email->to($recipients);
//$this->email->bcc($recipients);
$this->email->subject('example - weekly Report');
$this->email->message('Currently on test mode. Please update if you find any errors.');
$this->email->attach("files/weekly_reports/$prod_id-Weekly_report.pdf");
// SEND
$this->email->send();
return TRUE;
}
}
As you can see, I have this line:
$this->email->attach("files/weekly_reports/$prod_id-Weekly_report.pdf");
which clearly points to the file.
This is the main function that calls the send function:
public function main_weekly_report(){
$today = date('Y-m-d');
$reports = $this->kas_model->get_wr_table();
foreach ($reports as $report) {
// Outputs the current report that it is on.
var_dump($report);
// Delete the content of the folder containing the PDFs
if ($this->delete_pdf()){
// Creates a new PDF
$this->create_pdf($report->wr_app_id, $report->wr_date1, $report->wr_date2, $report->wr_date3);
// Increment "dates" to next week.
// $this->kas_model->weekly_inc_date($report->wr_id, 'wr_date1', $today);
// $this->kas_model->weekly_inc_date($report->wr_id, 'wr_date2', $today);
// Sends to the report to the customer:
if ( $this->is_connected() ) {
$this->send_pdf_customer($report->wr_app_id);
echo "Sent to customer!";
}
}
}
}
The result of this is:
the first file in the email (6-Weekly_report.pdf),
then the first AND the second file via different email (6-Weekly_report.pdf && 7-Weekly_report.pdf),
then the first, second and the third file different email ( 6-Weekly_report.pdf && 7-Weekly_report.pdf && 8-Weekly_report.pdf )... ect'.
Why is it stacking the files instead of sending them separably?
Why is it stacking the files instead of sending them separably although I delete the files using a different function? (the function works too, I had a post on it here too: How to return "TRUE" after deleting all files in a folder on my server?)
Using the delete/send functions outside the current one won't help me, because for each they send to different custumer.
I have this .php file in my config folder which the controller uses:
<?php
$config['protocol'] = "smtp";
$config['smtp_host'] = "ssl://smtp.gmail.com";
$config['smtp_port'] = "465";
$config['smtp_user'] = "my#email.com";
$config['smtp_pass'] = "hello";
$config['charset'] = "utf-8";
$config['mailtype'] = "html";
$config['newline'] = "\r\n";
$config['crlf'] = "\r\n";
$config['validate'] = FALSE;
?>
Can you please help me find a workaround?
Without being able to see the load function, it looks like it's stacking the PDF's because $this->email is the same instance every time the function is called. So when the function is called the second time, instead of creating a new email it's just re-using the old one and overriding all the previous settings, but attaching another file without removing the old one
I am new to PHP and Swiftmailer.
What I am trying to do is set up a PHP site on a webserver and use SwiftMailer to send e-mails.
The code I got does work on my local XAMPP server, but will produce the error message:
"Fatal error: Class 'Swift_Attachment' not found in /[address to my php file]"
when executed from the on-line webserver.
Here is my code:
<?php
// Get this directory, to include other files from
$dir = dirname(__FILE__);
// Get the contents of the pdf into a variable for later
ob_start();
require_once($dir.'/pdf_selbst_lir.php');
$pdf_html = ob_get_contents();
ob_end_clean();
// Load the dompdf files
require_once($dir.'/dompdf/dompdf_config.inc.php');
$dompdf = new DOMPDF(); // Create new instance of dompdf
$dompdf->load_html($pdf_html); // Load the html
$dompdf->render(); // Parse the html, convert to PDF
$pdf_content = $dompdf->output(); // Put contents of pdf into variable for later
// Get the content of the HTML email into a variable for later
ob_start();
require_once($dir.'/Templates/html.php');
$html_message = ob_get_contents();
ob_end_clean();
// Swiftmailer
require_once($dir.'/swiftmailer-5.0.1/lib/swift_required.php');
// Create the attachment with your data
$attachment = Swift_Attachment::newInstance($pdf_content, 'pdfname.pdf', 'application/pdf');
// Create the Transport
$transport = Swift_SmtpTransport::newInstance('mymailserver', 587, 'tls')
->setUsername('username')
->setPassword('password')
;
// Create the Mailer using your created Transport
$mailer = Swift_Mailer::newInstance($transport);
// Create the message
$message = Swift_Message::newInstance()
->setFrom(array('senderaddress' => 'Sender Name'))
->setSubject('subject')
->addBcc('somebccaddress')
->setBody($html_message, 'text/html')
->attach($attachment);
try {
$message->addTo('somerecipient');
}
catch (Swift_RfcComplianceException $e)
{
// Address was invalid
echo "Email address not correct.";
}
// Send the message
if ($mailer->send($message))
$success = true;
else
$error = true;
?>
Note that when I comment out all the attachment-related stuff, the error message switches to
"Fatal error: Class 'Swift_SmtpTransport' not found in /[address to my php file]" and points to the "$transport" line.
So it appears the overall SwiftMailer is not working, and this is not attachment-related.
Help would be greatly appreciated!
I don'see ->setTo( your_mail_dest) and ->send()
try with a simple send like this
$message = Swift_Message::newInstance()
->setFrom(array('senderaddress' => 'Sender Name'))
->setTo( **** your_mail_dest ****)
->setSubject('subject')
->addBcc('somebccaddress')
->setBody($html_message, 'text/html')
->attach($attachment)
->send();
Case closed.
It turned out that the code was working fine after all. All I needed to do was upgrade Swiftmailer (now running on 5.4.2-DEV). Sorry for the hassle and thanks scaisEdge for helping!