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!
Related
I`ve started to explore a Swiftmailer, and faced this issue.Added some info about errors
I just copied code from swiftmailer documentation, and adapted. When I try to send a message, it gives a messages about errors. I dont know, where is a problem, thats why ive attached all my code:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 'On');
require '../../../../vendor/autoload.php';
// Create the Transport
$transport = (new Swift_SmtpTransport('smtp.gmail.com', 587, 'tls'))
->setUsername('mymail#gmail.com')
->setPassword('my_app_pass_from_google');
// Create the Mailer using your created Transport
$mailer = new Swift_Mailer($transport);
// Create a message
$message = (new Swift_Message('Wonderful Subject'))
->setFrom(['mymail#gmail.com' => 'Me'])
->setTo(['mymail#gmail.com' => 'Also me'])
->setBody('Here is the message itself')
;
// Send the message
$result = $mailer->send($message);
if ($result){
echo 'Nice';
}
else{
echo 'bruh';
}
?>
P.S. Tried to change ports in code, also in php.ini. I use MAMP.
Tried to change ports in code, also in php.ini. I use MAMP. Also tried SMTP of other service(not gmail.com), there I have same problem, but page have been downloading slowly(dont know why)
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 need to create a custom mailing script in magento in Shell folder. I got the sample script from internet. this script was described as a stand alone script and no template id's are required and this type of script is what I needed and program didn't work for me.Below is the script.
require '../app/Mage.php';
ini_set('display_errors', true);
ini_set('max_execution_time', 3600); // just put a lot of time
ini_set('default_socket_timeout', 3600); // same
set_time_limit(0);
class Mage_Shell_Report
{
public function myfunc()
{
$body = "Hi there, here is some plaintext body content";
$mail = Mage::getModel('core/email');
$mail->setToName('reig');
$mail->setToEmail('rieg.philippe#neuf.fr');
$mail->setBody($body);
$mail->setSubject('The Subject');
$mail->setFromEmail('boutique#infosys.com');
$mail->setFromName("divine");
$mail->setType('text');// You can use 'html' or 'text'
try {
$mail->send();
if($mail->send())
{
$msg = true;
echo "<br>mail sent<br>";
}
else
{
echo "<br>mail not send<br>";
}
Mage::getSingleton('core/session')->addSuccess('Your request has been sent');
}
catch (Exception $e) {
Mage::getSingleton('core/session')->addError('Unable to send.');
$this->_redirect('');
}
echo "<br>end program<br>";
}
}
echo "out-1";
$shell1 = new Mage_Shell_Report();
$shell1->myfunc();
?>
This program shows no error . Though mail function returns success , i am not receiving any mail. i am testing in local using SMTP. Other email's, like order email, customer emails are sent successfully and can be viewed in SMTP mailbox. I browsed through pages and came to know that this issue has something to do with queuing but am not clear about that. Kindly help me out
Im using the below php code to send an email to one address and bcc 2 other addresses. It sends to the recipient fine but I can only get it to send to one of the 2 bcc addresses. (see comments in code for what ive tried)
Oddly enough though, $result comes back as 3 so it seems that its trying to send the second bcc email but it never comes through.
<?php
$tracker='tracking#pnrbuilder.com';
$subject = $_POST['subject'];
$sender = $_POST['sender'];
$toEmail=$_POST['toEmail'];
$passedInEmail=stripslashes($_POST['message']);
$passedInEmail=preg_replace('/ /',' ',$passedInEmail);
require_once('swiftLib/simple_html_dom.php');
require_once('swiftLib/swift_required.php');
$transport = Swift_MailTransport::newInstance();
$mailer = Swift_Mailer::newInstance($transport);
// Create the message
$message = Swift_Message::newInstance();
//turn the meesage into an object using simple_html_dom
//so we can iterate through and embed each image
$content = str_get_html($passedInEmail);
// Retrieve all img src tags and replace them with embedded images
foreach($content->find('img') as $e)
{
if($e->src != "")
{
$value = $e->src;
$newValue = $message->embed(Swift_Image::fromPath($value));
$e->src = $newValue;
}
}
$message->setSubject($subject);
$message->setFrom($sender);
$message->setTo($toEmail);
//this is my problem
$message->setBcc(array('tracking#pnrbuilder.com',$sender));
//as it is above only "sender" gets the email
//if I change it like this:
//$message->setBcc($tracker,$sender);
//only "tracker" gets the email
//same if I change it like this:
//$message->setBcc($sender);
//$message->addBcc($tracker);
$message->setReplyTo(array('flights#pnrbuilder.com'));
$message->setBody($content,'text/html');
$result = $mailer->send($message);
if ($result=3) {
echo 'Email Sent!';
}
else {
echo 'Error!';
}
?>
What is the proper way to do this?
You can find the swiftmailer tutorial here
example:
$message->setBcc(array(array('some#address.tld' => 'The Name'),array('another#address.tld' => 'Another Name')));
Try setting the names for the email addresses and see if it makes any difference.
This ended up being an issue on the server side, I contacted my hosting provider (GoDaddy) who were able to make some changes on their end fixing the problem. Thank you to all those who tried to help!