Retrieving SMTP conversation in SwiftMailer - php

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.

Related

Can't send mail with Gmail

I'm trying to send an email when a user is subscribing in my web site.
To save me time ... I'm using Swift_Mailer with Symfony.
First, I tried to send a mail with the console :
php .\bin\console swiftmailer:email:send
And that's working, the mail was sent and the client received it.
So now I said to myself, I will be able to send emails with the code.
That's my Controller code :
public function register(Request $request, \Swift_Mailer $mailer)
{
// Here saving new user in the database
$this->sendMail($user->getEMail(), $mailer);
$content = $this->renderView("register.html.twig");
return new Response($content);
}
private function sendMail($email, \Swift_Mailer $mailer)
{
$message = (new \Swift_Message('Hello Email'))
->setFrom(['my.email#gmail.com' => "my name"])
->setTo($email)
->setBody('Here is the message itself');
$mailer->send($message);
}
And That's my .env file :
MAILER_URL=gmail://my.email#gmail.com:myPasswordHere#localhost
When I'm trying to send the mail, no error, I tried this StackOverflow link, but no problem, echo "Successfull", but nothing in the Gmail send box and nothing my client email box.
Can you please help me to ... save me time ^^
------------------------------------------------------------- EDIT 1 ------------------------------------------------------------
I never edited the config/packages/swiftmailer.yaml file, that's it's content :
swiftmailer:
url: '%env(MAILER_URL)%'
spool: { type: 'memory' }
------------------------------------------------------------- EDIT 2 ------------------------------------------------------------
I also tryed to make a new transporter with this code :
$transport = (new \Swift_SmtpTransport('smtp.gmail.com', 465))
->setUsername('my.email#gmail.com')
->setPassword('myPasswordHere');
$mailer = new \Swift_Mailer($transport);
And that's the error I get : Connection could not be established with host smtp.gmail.com [php_network_getaddresses: getaddrinfo failed: Unknown host. #0]
------------------------------------------------------------- EDIT 3 ------------------------------------------------------------
I've got a swiftmailer.yaml fil in the config/packages/dev folder and that's it's default content :
# See https://symfony.com/doc/current/email/dev_environment.html
swiftmailer:
# send all emails to a specific address
#delivery_addresses: ['me#example.com']
I tried to put the same content as in the config/packages/swiftmailer.yaml, but no result.
I don't see something like this in your code:
// Create the Transport
$transport = (new \Swift_SmtpTransport('mail hoster etc', port))
->setUsername('your email')
->setPassword('your password');
// Create the Mailer using your created Transport
$mailer = new \Swift_Mailer($transport);
Maybe it's a reason why your mails isn't sent.

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.

Swiftmailer config : send mail using gmail

I can send email from my pc using swiftmailer, but mail not sending in server.
I'm using swiftmailer 5.0.1. Project details are,
A simple php project in netbeans
swiftmailer 5.0.1
twig 1.13.1
My code is
public function init() {
$this->username = 'username#gmail.com';
$this->password = 'password';
$this->host = 'ssl://smtp.gmail.com';
$this->port = 465;
$this->from = 'username#gmail.com';
$this->subject = 'Company - contact';
$this->body_part_type = 'text/html';
}
public function send_email($from_name_add, $to_add, $fullname, $email, $mobile, $content) {
$this->init();
$transport = Swift_SmtpTransport::newInstance($this->host, $this->port)
->setUsername($this->username)
->setPassword($this->password);
$mailer = Swift_Mailer::newInstance($transport);
$message = Swift_Message::newInstance();
$cid = $message->embed(Swift_Image::fromPath('../public_html/pic/logo.png'));
$this->body = $this->renderEmailTemplate('email', $fullname, $email, $mobile, $content, $cid);
$message->setSubject($this->subject)
->setFrom(array('username#gmail.com' => '' . $from_name_add))
->setTo($to_add)
->setContentType($this->body_part_type)
->setBody($this->body);
$result = $mailer->send($message);
return $result;
}
This code works FINE in my pc. But after upload this code/project to server, mail not sending. Error is,
<br />
<b>Fatal error</b>: Uncaught exception 'Swift_TransportException' with message 'Connection could not be established with host ssl://smtp.gmail.com [Connection timed out #110]' in /home/am***/lib/Swift/classes/Swift/Transport/StreamBuffer.php:259
Stack trace:
#0 /home/am***/lib/Swift/classes/Swift/Transport/StreamBuffer.php(64): Swift_Transport_StreamBuffer->_establishSocketConnection()
#1 /home/am***/lib/Swift/classes/Swift/Transport/AbstractSmtpTransport.php(115): Swift_Transport_StreamBuffer->initialize(Array)
#2 /home/am***/lib/Swift/classes/Swift/Mailer.php(80): Swift_Transport_AbstractSmtpTransport->start()
#3 /home/am***/controller/send_mail.php(54): Swift_Mailer->send(Object(Swift_Message))
#4 /home/am***/public_html/contact.php(43): send_mail->send_email('Am*** Inc', 'fe****#gma...', 'asdf', 'asdf#in.com', '111111111111', 'Testing mail')
#5 {main}
thrown in <b>/home/am***/lib/Swift/classes/Swift/Transport/StreamBuffer.php</b> on line <b>259</b><br />
HINT: There is an allready running php symfony2 project in that server, this project can send mail successfully.
Here is the symfony2 code,
$message = \Swift_Message::newInstance()
->setSubject($sub)->setFrom($from)->setTo($to)->setContentType("text/html")
->setBody($this->renderView('FZAm***Bundle:Layout:mail.html.twig', array
('name' => $this->fullname, 'mobile' => $this->mobile, 'email' => $this->email,
'content' => $this->content, 'time' => $this->sys_time, 'ip' => $userip,
'server_time' => date('Y-m-d H:i:s'))
));
try {
$this->get('mailer')->send($message);
// catch and other follows.
Config details are,
mail_contact_from: username#gmail.com
mail_contact_to: username#gmail.com
mail_contact_sub: Contact info
I passed only this details and all settings are default. If any info needed please ask i'l post.
Reason i'm changing from symfony2 project to this ordinary php+swift+twig is my hosting is only 100mb and i need to upload more images. But symfony2 occupy more space.
Looks like your live server is missing OpenSSL, so you need to enable it in order to get secure connections working (i.e. enable the php_openssl module). Also check this question.
After some search in google.
To send mail using gmail auth you need to use this code,
$transport = Swift_SmtpTransport::newInstance('ssl://smtp.gmail.com', 465);
This is the correct way to send mail. This mail will be send by gmail.
PHP use mail() to send just a mail,
mail($to,$subject,$message,$headers);
This code sends a mail using php code.
Swiftmailer can also send a mail using this php mail() function,
Here is swift code.
$transport = Swift_MailTransport::newInstance();
// nothing inside ()
The problem in this mail is, gmail displays following message,
This message may not have been sent by: username#gmail.com
Sometimes this mail will go to spam.

How to send facebook chat message via JAXL?

I am trying to send direct message with JAXL in the name of a user (authenticated application with xmpp_login). In the jaxl facebook chat example there exist a message echo structure, still it redirects received XMPPStanza to the sender. But trying to generate XMPPStanza to send performs nothing with
$client->send($stanza);
here is my XMPPStanza initialization code
$stanza = new XMPPMsg(null);
$stanza->from = $client->full_jid->to_string();
$stanza->to = 'example-facebook-id#chat.facebook.com';
$stanza->type = 'chat';
$stanza->body = 'test message';
$client->send($stanza);
To sum it up, How can i send message from server in the name of the client via JAXL?
EDIT
I forgot to mention i am using JAXL v3 and thought about appending full code and system configuration would be more helpful.
<?php
define('FACEBOOKBOT_PHP', TRUE);
// Include XMPP Engine 'JAXL'
// Path might be alter in time.
// require_once ROOT_DIR.'/JAXL/jaxl.php';
require_once '/var/www/JAXL/jaxl.php';
require_once '/var/www/JAXL/xmpp/xmpp_msg.php';
function sendMessage($client)
{
// // $stanza = new XMPPMsg(null);
// // $stanza->from = $client->full_jid->to_string();
// // $stanza->to = $to;
// // $stanza->type = 'chat';
// // $stanza->body = 'test message 1';
// // foreach ($stanza->childrens as $value)
// // {
// // $value->ns = 'jabber:client';
// // }
// // $client->send($stanza);
$msg = new XMPPMsg(array('to'=>'example-user-id-and-it-got-to-work-i-checked-on-below-echo-stanza#chat.facebook.com'), 'test message');
$client->send($msg);
_info("test messages sent");
}
$user = 'gokhanbarisaker'; // my user id (www.facebook.com/gokhanbarisaker)
// $user = $argv[1]; // User name or facebook id
$jidSuffix = '#chat.facebook.com'; // Facebook chat account suffix
$appKey = 'example-app-key'; // Taken from developer.facebook.com
// $appKey = $argv[2]; // Facebook app token
$accessToken = 'example-access-token'; // Facebook user token - tried both app token tool on developer.facebook.com and token provided after user login both posses xmpp-login permission
// $accessToken = $argv[3];
$client = new JAXL( array( // (required) credentials
'jid' => $user.$jidSuffix,
'fb_app_key' => $appKey,
'fb_access_token' => $accessToken,
// force tls (facebook require this now)
'force_tls' => true,
// (required) force facebook oauth
'auth_type' => 'X-FACEBOOK-PLATFORM',
// (optional)
//'resource' => 'resource',
'log_level' => JAXL_INFO,
'priv_dir' => '.'
));
$client->add_cb('on_auth_success', function()
{
global $client;
_info("got on_auth_success cb, jid ".$client->full_jid->to_string());
$client->set_status("available!", "dnd", 10);
// Here is the part where i tried to send message. In addition, i tried to call this function wherever i can on the code.
sendMessage($client);
});
$client->add_cb('on_auth_failure', function($reason)
{
global $client;
$client->send_end_stream();
_info("got on_auth_failure cb with reason $reason");
});
$client->add_cb('on_chat_message', function($stanza)
{
global $client;
// echo back incoming message stanza
$stanza->to = $stanza->from;
$stanza->from = $client->full_jid->to_string();
$client->send($stanza);
_info("echo message sent");
sendMessage($client);
});
$client->add_cb('on_disconnect', function()
{
_info("got on_disconnect cb");
});
$client->start();
echo "done\n";
?>
System configuration:
Ubuntu 12.04.01 LTS
Apache 2.2.22
PHP 5.3.10
Terminal command to execute;
> php facebookbot.php
A few things you should try and see if they help you debug this:
Set 'log_level' => JAXL_DEBUG, and check logs to see what exactly Jaxl sends out to facebook. If you can, update the question with outgoing stanza so that we can verify whats really wrong here.
If you are using facebook id's to send out messages, remember you need to send message 'to'=>'-4#chat.facebook.com'. Note the negative sign.
Facebook is quite smart in catching spammers in their network. If you are trying to send out too many similar messages within a short time, facebook servers will reply back with appropriate error to the bot (they can even disable your chat account temporarily). Check the logs to see if you are gettings any such error response back from the facebook servers.
try:
$msg = new XMPPMsg(array('to'=>'example-facebook-id#chat.facebook.com'), 'test message');
$client->send($msg);

Categories