I am using Symfony 1.4 with Propel as ORM. i have configured web server schedulers to trigger a mailing function at every 1Hour. To send mails i am using PHP Swift mailer class, and not the symfony's inbuild Swiftmailer(default in 1.3,1.4). But while using it is giving me error..
as "Catchable fatal error: Argument 1 passed to Swift_Transport_EsmtpTransport::__construct() must implement interface Swift_Transport_IoBuffer, none given in /home/msconslt/sfprojects/test/lib/mailClasses/classes/Swift/Transport/EsmtpTransport.php on line 64".
The code that i am using...
require_once(dirname(__FILE__).'/../../config/ProjectConfiguration.class.php');
$configuration =ProjectConfiguration::getApplicationConfiguration('frontend', 'dev', true);
// Remove the following lines if you don't use the database layer
$databaseManager = new sfDatabaseManager($configuration);
//Create the Transport
$transport = Swift_SmtpTransport::newInstance('smtp.gmail.com', 465, "ssl")
->setUsername('myid#gmail.com')
->setPassword('mypassword')
;
//Create the Mailer using your created Transport
$mailer = Swift_Mailer::newInstance($transport);
//Create a message
$message = Swift_Message::newInstance("Test Mail")
->setFrom(array('myid#gmail.com' => 'Harry'))
->setTo(array('someid#gmail.com'))
->setBody('<html>'.
'<head></head>'.
'<body> <span>Dear, </span><br/> Hi there..</body>'.
'</html>',
'text/html'
);
$mailer->send($message);
is there any other way to send mail through Cron jobs??
Yes. See the relevant part of the 1.4 book: Sending an email from a task.
This problem is because you need add this reference in your taks :
requiere_once dirname(__FILE__) . '/../vendor/symfony/lib/vendor/swiftmailer/swift_required.php
Related
I am working on a project that doesn't use any framework and I would like to use Symfony Mailer component to handle sending emails.
The installation part (composer require) was well handled and everything is included in my code without any error. However, I still have a problem : the documentation of the component seems to be written only for using it with the symfony framework.
Indeed, it is refering to autoloaded config files that o
bviously don't exist in my app.
This implementation seems to be very tricky and I was wondering if any of you guys already faced the same problem and what solution you came up with?
Your question made me wonder too how it is easy to send mail only with the mailer component.
So I created a new project from scratch and tried the simplest possible version following the mailer component documentation.
use Symfony\Component\Mailer\Mailer;
use Symfony\Component\Mailer\Transport;
use Symfony\Component\Mime\Email;
class MyMailer
{
// googleDns format is gmail+smtp://USERNAME:PASSWORD#default
public function __construct(private string $googleDsn)
{
}
public function send()
{
$template = file_get_contents('https://raw.githubusercontent.com/leemunroe/responsive-html-email-template/master/email.html');
$transport = Transport::fromDsn($this->googleDsn);
$mailer = new Mailer($transport);
$email = (new Email())
->from('mygmail#address.com')
->to('thedelivery#gmail.com')
->subject('Time for Symfony Mailer!')
->html($template);
$mailer->send($email);
}
}
And I successfully received my mail. I send my mail with gmail, for your information. Transport class should do the sending job for you, but if not you can have a look to inside vendor/symfony/mailer/Transport folder
I'm using Monolog (https://github.com/Seldaek/monolog) in my project and we want to receive an email when there are errors in our application. The logs are working as expected but if the log level is ERROR (below log level is DEBUG), I want the logger to send me an email.
I tried to use the class NativeMailHandler but it doesn't seems to work and I would prefer to use our SMTP mail server (works great in PHP but I can't figure out how to link it with Monolog error handler)
$logger = new Logger('LOG');
$logHandler = new StreamHandler('synchro.log',Logger::DEBUG);
$logger->pushHandler($logHandler);
I created PHPMailer handler for Monolog. It enables you to send logs to emails with PHPMailer.
It is available on GitHub and Packagist, but it can also be used without Composer (which requires manual installation of Monolog and PHPMailer).
<?php
use MonologPHPMailer\PHPMailerHandler;
use Monolog\Formatter\HtmlFormatter;
use Monolog\Logger;
use Monolog\Processor\IntrospectionProcessor;
use Monolog\Processor\MemoryUsageProcessor;
use Monolog\Processor\WebProcessor;
use PHPMailer\PHPMailer\PHPMailer;
require __DIR__ . '/vendor/autoload.php';
$mailer = new PHPMailer(true);
$logger = new Logger('logger');
$mailer->isSMTP();
$mailer->Host = 'smtp.example.com';
$mailer->SMTPAuth = true;
$mailer->Username = 'server#example.com';
$mailer->Password = 'password';
$mailer->setFrom('server#example.com', 'Logging Server');
$mailer->addAddress('user#example.com', 'Your Name');
$logger->pushProcessor(new IntrospectionProcessor);
$logger->pushProcessor(new MemoryUsageProcessor);
$logger->pushProcessor(new WebProcessor);
$handler = new PHPMailerHandler($mailer);
$handler->setFormatter(new HtmlFormatter);
$logger->pushHandler($handler);
$logger->error('Error!');
$logger->alert('Something went wrong!');
Well, I found a solution to my problem, maybe it will help someone one day:
Since the class NativeMailHandler is using the mail() php function. I changed the code in monolog/monolog/src/Monolog/Handler/NativeMailhandler.php of the function send() and I declared my PHPMailer() there instead of the mail() function.
$mailHandler = new NativeMailerHandler(your_email#email.com, $subject, $from,Logger::ERROR,true, 70);
$logHandler = new StreamHandler('synchro.log',Logger::DEBUG);
$logger->pushHandler($logHandler);
$logger->pushHandler($mailHandler); //push the mail Handler. on the log level defined (Logger::ERROR in this example), it will send an email to the configured mail in the send() function in monolog/monolog/src/Monolog/Handler/NativeMailhandler.php
I'm trying to use different SMTP configuration for each user of my application. So, using Swift_SmtpTransport set a new transport instance, assign it to Swift_Mailer and then assign it to Laravel Mailer.
Below the full snippet:
$transport = Swift_SmtpTransport::newInstance($mailConfig['smtp_host'], $mailConfig['smtp_port'], 'ssl');
$transport->setUsername($mailConfig['smtp_user']);
$transport->setPassword($mailConfig['smtp_pass']);
$smtp = new Swift_Mailer($transport);
Mail::setSwiftMailer($smtp);
Mail::queue(....);
Messages are added to the queue but never dispatched. I guess that since the "real" send is asyncronous it uses default SMTP configuration, and not the transport set before Mail::queue().
So, the question is: how to change mail transport when using Mail::queue()?
Instead of using Mail::queue, try creating a queue job class that handles sending the email. That way the transport switching code will be executed when the job is processed.
The Job Class Structure Documentation actually uses a mailing scenario as an example, which receives a Mailer instance that you can manipulate. Just use your code in the class's handle method:
public function handle(Mailer $mailer)
{
$transport = Swift_SmtpTransport::newInstance($mailConfig['smtp_host'], $mailConfig['smtp_port'], 'ssl');
$transport->setUsername($mailConfig['smtp_user']);
$transport->setPassword($mailConfig['smtp_pass']);
$smtp = new Swift_Mailer($transport);
$mailer->setSwiftMailer($smtp);
$mailer->send('viewname', ['data'], function ($m) {
//
});
}
Best way from notifications since Laravel 7 : https://laravel.com/docs/9.x/notifications#customizing-the-mailer
public function toMail($notifiable)
{
return (new MailMessage)
->mailer('postmark')
->line('...');
}
I am working on a test where I need 300 different mailers (to fill Mailtrap Enterprise) so having 300 different configs was not good for me.
I am posting the simple solution I found looking at Illuminate\Mail\Mailer class
$transport = Transport::fromDsn('smtp://user:pass#host:port');
Mail::setSymfonyTransport($transport);
Mail::to('to#email.com')
->send((new LaravelMail())
->subject('Subject')
);
Having this you can do some string manipulation to switch between transport configurations
I have successfully used Zend_Mail from ZF1 to connect to a GMail account using SMTP, but have not been able to get it to work with Zend\Mail. The following produced a "Connection timed out" exception:
use Zend\Mail\Message;
use Zend\Mail\Transport\Smtp as SmtpTransport;
use Zend\Mail\Transport\SmtpOptions;
$transport = new SmtpTransport();
$options = new SmtpOptions([
'host' => 'smtp.gmail.com',
'connection_class' => 'login',
'connection_config' => [
'username' => 'my_username#gmail.com',
'password' => 'redacted',
'port' => 587,
'ssl' => 'tls',
],
]);
$transport->setOptions($options);
$message = new Message();
$message->addTo('recipient#example.org')
->setFrom('me#example.org')
->setSubject('hello, fool!')
->setBody("testing one two three! time is now ".date('r'));
$transport->send($message);
However! The very same connection parameters work fine when I do the equivalent of the above with PHP Swiftmailer, and also with Python, and also with the older Zend_Mail. All of this of course in the same environment (my Ubuntu 14.04 box). So, I think there must be an issue with Zend\Mail -- or perhaps more accurately Zend\Mail\Transport\Smtp.
Unfortunately I am not enough of a hero (and lack the skills) to dig into Zend\Mail\Transport\Smtp and fix it, so I turned next to Swiftmailer (http://swiftmailer.org/). And it works just great,
$transport = Swift_SmtpTransport::newInstance('smtp.gmail.com', 587, 'tls');
$transport->setUsername('my_username#gmail.com')
->setPassword('redacted');
$mailer = Swift_Mailer::newInstance($transport);
$message = Swift_Message::newInstance();
$message->setSubject("testing from Swiftmailer")
->setFrom("me#example.org")
->setTo('recipient#example.org')
->setBody("yadda yadda blah blah blah!");
$result = $mailer->send($message); // nice and easy!
but lacks one nice feature: Zend\Mail has a File transport that simply dumps your message to a file, very handy for development and testing, when you don't really want to send email messages to anyone.
What to do? I am familiar with the configuration trick of setting an "environment" environment variable to "development", "production", etc., and making my code decide how to configure itself accordingly. But in my thought experiments so far, this gets a little awkward.
One idea: subclass Swift_Mailer and override send() to simply write the message to disk, and consult the $environment to decide whether to instantiate the real thing or the subclass that doesn't really send.
But I would love to hear some other ideas and suggestions.
For swiftmailer you can use SpoolTransport with a FileSpool to store messages to filesystem.
Example (by Norio Suzuki):
/**
* 270-transport-spool-file.php
*/
require_once '../vendor/autoload.php';
require_once './config.php';
// POINT of this sample
$path = FILE_SPOOL_PATH;
$spool = new Swift_FileSpool($path);
$transport = Swift_SpoolTransport::newInstance($spool);
$mailer = Swift_Mailer::newInstance($transport);
$message = Swift_Message::newInstance();
$message
->setFrom(MAIL_FROM)
->setTo(MAIL_TO)
->setSubject('SpoolTransport (file) sample')
->setBody('This is a mail.')
;
// Serialized Swift_Message objects were spooled to $path
$result = $mailer->send($message);
OK, this is a two-part answer and you can pick.
Answer #1: don't worry about writing to a file, just use Swiftmailer's undocumented Swift_NullTransport like so:
$transport = new Swift_NullTransport::newInstance();
/* and so forth */
The send() method of Swift_Transport_NullTransport (parent of Swift_NullTransport) does nothing but act as though it succeeded, which in my case is about as good as dumping to a file.
Answer #2: roll your own somehow, e.g., either (a) by extending one of the Transport classes and overriding send(), or (b) writing another Transport whose send() writes to a file, and then making a PR on Github for the benefit of all sentient beings.
I use Zend\Mail\Transport\Smtp to send an email. Below is my code.
use Zend\Mail\Message;
use Zend\Mail\Transport\Smtp as SmtpTransport;
use Zend\Mail\Transport\SmtpOptions;
public function smtpConfig($message)
{
$transport = new SmtpTransport();
$options = new SmtpOptions(array(
'name' => localhost,
//'host' => 10.92.32.81,
'port' => 25,
));
$transport->setOptions($options);
echo $transport->send($message);
}
public function sendMail($to,$from,$subject,$body)
{
$message = new Message();
$message->addTo($to)
->addFrom($from)
->setSubject($subject)
->setBody($body);
$this->smtpConfig($message);
}
I have configured smtp in local system and I'm able to receive email without any warnings/low priority errors. I delivered this code for project testing. Mail functionality is working fine in their system but in browser console following warning/error is displayed and I dont see this error in my local setup.
Parse error: syntax error, unexpected '[' in D:\applications\www-php\kiosquebo\vendor\zendframework\zend-mail\src\Headers.php on line 39
Any solution given is appreciated.
According to the line in the file you're getting the error, PHP is failing to parse this line:
protected $headersKeys = [];
The only issue that is possible here is that your PHP version is too old and does not work with the [] array definer.
You should update your PHP version to at least 5.4.