Swiftmailer and Symfony2 - php

Having some problems implementing swiftmailer with the new symfony2 beta4, below is my code
$mailer = $this->container->get('mailer');
$name = ucwords(str_replace('.',' ', $user->getScreenName()));
$email = 'me#me.com'; //$user->getEmail();
$message = $mailer::newInstance()
->setSubject('New Password')
->setFrom('Neokeo <blah#blah.com>')
->setTo("$name <$email>")
->setBody($this->renderView('MyBundle:User:reset.html.php', array('user',$user)));
$mailer->send($message);
and the error
Catchable fatal error: Argument 1 passed to Swift_Mailer::newInstance() must implement interface Swift_Transport, none given
does anyone have any idea what i can do to fix this?

$mailer is an instance of the Swift_Mailer class (which is the class used for sending messages), but for creating a message, you need the Swift_Message class.
$message = Swift_Message::newInstance()
http://swiftmailer.org/docs/message-quickref

Related

Swiftmailer - Uncaught Error: Call to undefined method Swift_SmtpTransport::newInstance()

I'm trying to send email using the Swiftmailer.
I'm getting an Uncaught Error:
Call to undefined method Swift_SmtpTransport::newInstance().
Here is the code:
require_once 'swift/lib/swift_required.php';
$transport = Swift_SmtpTransport::newInstance('smtp.gmail.com', 465, 'ssl')
->setUsername ('email#gmail.com')
->setPassword ('password');
$mailer = Swift_Mailer::newInstance($transport);
$message = Swift_Message::newInstance('Weekly Hours')
->setFrom (array('email#gmail.com' => 'My Name'))
->setTo (array('email#hotmail.com' => 'Recipient'))
->setSubject ('Weekly Hours')
->setBody ('Test Message', 'text/html');
$result = $mailer->send($message);
Based on the above code, what would be causing that mistake?
I'm not quite familiar with SwiftMailer, but from the brief overview of the error you provided, and their documentation page, I can suggest you to try using new operator. From the error, it's clear that
Swift_SmtpTransport class doesn't have a newInstance method, so when you use it to create a new instance, it throws an error. Maybe try using this instead:
require_once 'swift/lib/swift_required.php';
$transport = new Swift_SmtpTransport('smtp.gmail.com', 465, 'ssl');
$transport->setUsername('email#gmail.com')->setPassword('password');
$mailer = new Swift_Mailer($transport);
$message = new Swift_Message('Weekly Hours');
$message
->setFrom(['email#gmail.com' => 'My Name'])
->setTo(['email#hotmail.com' => 'Recipient'])
->setSubject('Weekly Hours')
->setBody('Test Message', 'text/html');
$result = $mailer->send($message);
Edit: PHP Doesn't allow a direct method call after instantiating an object (without parenthesis). Thanks, Art Geigel.
Swift_Mailer::newInstance($transport);
The newInstance method is available in version 5.4, in newer version, it is removed.
Check version in composer.json.
"swiftmailer/swiftmailer": "^5.4"
add this lines in file : ./swift/classes/Swift/SmtpTransport.php
/**
* Create a new SmtpTransport instance.
*
* #param string $host
* #param integer $port
* #param string $security
*
* #return Swift_SmtpTransport
*/
public static function newInstance($host = 'localhost', $port = 25, $security = null)
{
return new self($host, $port, $security);
}
it was deleted in new version, but if you update from github, you need everytime add it

Sending email does not work when I use my helper in Yii php

I'm using Yii framework while my question is probably intended to PHP expert.
I have created a controller to send email from my web application, it works fine.
Given that, I intend to use email in several sontrollers in my app, I wanted to created a helper but that does not work. Email is not sent. (I'm using swiftmailer)
The code of the working controller is the following:
<?php
class MailController extends Controller
{
/**
* Declares class-based actions.
*/
public function actionSendemail() {
// Plain text content
$plainTextContent = "This is my first line ;-)\nThis is my second row of text";
// Get mailer
$SM = Yii::app()->swiftMailer;
// New transport mailHost= localhost, mailPort = 25
$Transport = $SM->smtpTransport(Yii::app()->params['mailHost'], Yii::app()->params['mailPort']);
// Mailer
$Mailer = $SM->mailer($Transport);
// New message
$Message = $SM
->newMessage('My subject')
->setFrom(array('test1#localhost.localdomain' => 'Example Name'))
->setTo(array('myemail#domain.com' => 'Recipient Name'))
// ->addPart($content, 'text/html')
->setBody($plainTextContent);
// Send mail
$result = $Mailer->send($Message);
}
}
The helper code is the following
<?php
// protected/components/Email.php
class Email {
public static function sendEmail($subject, $from, $to, $body)
{
// Get mailer
$SM = Yii::app()->swiftMailer;
// New transport
$Transport = $SM->smtpTransport(Yii::app()->params['mailHost'], Yii::app()->params['mailPort']);
// Mailer
$Mailer = $SM->mailer($Transport);
// New message
$Message = $SM
->newMessage($subject)
->setFrom(array($from => 'Example Name'))
->setTo(array($to => 'Recipient Name'))
// ->addPart($content, 'text/html')
->setBody($body);
// Send mail
$result = $Mailer->send($Message);
}
}
the way I call it is the following
$subject= 'My subject';
$from = Yii::app()->params['adminEmail']; // adminEmai is a globalparam like above controller
$to='xxxx#xxx.com';
$body='my body';
Email::sendEmail($subject, $from, $to, $body);
when I run this code, I have no error, but I dont receive the email.
Thank you for your help.
I found my error.
my global parameters in config.php was not set correctly.
So content I put in the from field was not recognized by my hmailserver which is configured for the moment with the content test1#localhost.localdomain
sorry for the question and thanks

extending swiftmailer use smtp server

I have a config array with some smtp settings.
I am looking for a way to extend Swiftmailer to auto fill in these details.
I cannot find anything about extending swiftmailer. I did found some information about plugins, but these existing plugins of swiftmailer won't tell me anything.
// automatic use smtp.domain.com, username, password ??
$transport = Swift_MailTransport::newInstance();
$mailer = Swift_Mailer::newInstance($transport);
$message = Swift_Message::newInstance('Test')
->setFrom(array('mail#domain.com' => 'from user'))
->setTo(array('mail#domain.com' => 'from user'))
->setBody('Body')
;
$result = $mailer->send($message);
Can anyone tell me how to do this?
I don't see why you should extend SwiftMailer for that requirement. It's much easier to create a class that handles the preparation e.g.
class SwiftMailerPreparator {
private $mailer;
public __construct(Swift_Mailer $mailer) {
$this->mailer = $mailer;
}
public function prepare(array $settings) {
// do your thing here
}
}
Also since SwiftMailer is opensource you can just look at the code and see how it works.
You could wrap everything into a service class like this:
class MyMailerAssistant
{
/**
* Service method to fastly send a message
* #param $subject
* #param $body
*/
public static function sendMessage($subject, $body)
{
// automatic use smtp.domain.com, username, password ??
$transport = Swift_MailTransport::newInstance();
$mailer = Swift_Mailer::newInstance($transport);
$message = Swift_Message::newInstance('Test')
->setSubject($subject)
->setFrom(array('mail#domain.com' => 'from user'))
->setTo(array('mail#domain.com' => 'from user'))
->setBody($body);
$result = $mailer->send($message);
}
}
and calling it simply in this way:
MyMailerAssistant::sendMessage('Hello', 'This is the email content');
Anyway I strongly discourage you inserting your configuration into a method, I would always load it from a modular external configuration file.

Retrieving SMTP conversation in SwiftMailer

I am using SwiftMailer to send emails and my site is all of a sudden having timeout issues when trying to send an email.
I need to extract the "SMTP conversation" so my host can debug it.
Is there any code that can give me this?
include('SwiftMailer/swift_required.php');
$transport = Swift_SmtpTransport::newInstance('smtp.example.com', 587);
$transport->setUsername('username');
$transport->setPassword('password');
$swift = Swift_Mailer::newInstance($transport);
// Create a message
$message = new Swift_Message($subject);
$message->setFrom($from);
$message->setBody($message, $content_type, SITE_CHARSET);
$message->setTo($to);
try {
$swift->send($message);
} catch (Swift_TransportException $e) {
// Log array for further inspection
}
Example with Laravel
Dump the conversation to log:
$content = 'Test';
$title = 'Test now()= ' . date("Y-m-d",time());
$logger = new \Swift_Plugins_Loggers_ArrayLogger();
Mail::getSwiftMailer()->registerPlugin(new \Swift_Plugins_LoggerPlugin($logger));
Mail::send('emails.send', ['title' => $title, 'content' => $content], function ($message){
$message->from('fromuser#mydomain.com');
$message->to('touser#mydomain.com');
});
Log::info($logger->dump());
And send.blade.php at \resources\emails
<html>
<head></head>
<body style="background: orange; color: white">
<h1>{{$title}}</h1>
<p>{{$content}}</p>
AGARCIA - 2018
</body>
</html>
You might want to take a look at the SwiftMailer Logger Plugin which will allow you log all the interactions between your client and the SMTP server.
There is two types of loggers available:
The ArrayLogger - (Keeps a collection of log messages inside an array. The array content can be cleared or dumped out to the screen)
The EchoLogger (Prints output to the screen in realtime. Handy for very rudimentary debug output)
You can register the plugin using either:
$logger = new Swift_Plugins_Loggers_ArrayLogger();
$swift->registerPlugin(new Swift_Plugins_LoggerPlugin($logger));
or
$logger = new Swift_Plugins_Loggers_EchoLogger();
$swift->registerPlugin(new Swift_Plugins_LoggerPlugin($logger));
Just make sure you have the plugin installed and that your class autoloader can access the required class on demand.
Refer to the documentation for further details.

Swift Mailer: Multi recipients option doesn't work

Although there are many same questions, none of the solutions worked for me. Mail gets sent only if there is only one recipient otherwise generates error below. Also I'm only sending internal emails, no external.
Any idea?
CODE:
$to = 'one#example.com, two#example.com, three#example.com';
$transport = Swift_SmtpTransport::newInstance('192.168.whatever', 25);
$mailer = Swift_Mailer::newInstance($transport);
$message = Swift_Message::newInstance('Test')
->setFrom(array('myself#example.com'))
->setTo(array($to))
->setBody('html content goes here', 'text/html');
$result = $mailer->send($message);
echo $result;
ERROR:
Fatal error: Uncaught exception 'Swift_RfcComplianceException' with message 'Address in mailbox given [one#example.com, two#example.com, three#example.com] does not comply with RFC 2822, 3.6.2.' in C:\wamp\www\ssl\swift_emailer\lib\classes\Swift\Mime\Headers\MailboxHeader.php:308 Stack trace: #0 C:\wamp\www\ssl\swift_emailer\lib\classes\Swift\Mime\Headers\MailboxHeader.php(238): Swift_Mime_Headers_MailboxHeader->_assertValidAddress('lukas.borecki#l...') #1 C:\wamp\www\ssl\swift_emailer\lib\classes\Swift\Mime\Headers\MailboxHeader.php(96): Swift_Mime_Headers_MailboxHeader->normalizeMailboxes(Array) #2 C:\wamp\www\ssl\swift_emailer\lib\classes\Swift\Mime\Headers\MailboxHeader.php(60): Swift_Mime_Headers_MailboxHeader->setNameAddresses(Array) #3 C:\wamp\www\ssl\swift_emailer\lib\classes\Swift\Mime\SimpleHeaderFactory.php(60): Swift_Mime_Headers_MailboxHeader->setFieldBodyModel(Array) #4 C:\wamp\www\ssl\swift_emailer\lib\classes\Swift\Mime\SimpleHeaderSet.php(75): Swift_Mime_SimpleHead in C:\wamp\www\ssl\swift_emailer\lib\classes\Swift\Mime\Headers\MailboxHeader.php on line 308
LOOKED AT:
Swift website
swift mailer error 'Swift_RfcComplianceException'....
Google forum
And many more.
Try
$to = array('one#example.com', 'two#example.com', 'three#example.com');
....
->setTo($to)
TRy this example with swiftmailer:
parameters.yml
destinatarios: [email1, email2, email3]
services:
your service name:
class: your namespace
arguments: ["%destinatarios%"]
the class of the service:
protected $destinatarios;
public function __construct($destinatarios)
{
$this->destinatarios = $destinatarios;
}
->setCc($this->destinatarios)

Categories