this may look stupid but I am wondering how to test the function that sends an email from Gmail, NOT from command line because that thing works fine. I want how to call the function that sends an emails . I have followed this tutorial .
My config/packages/imap.yaml is
imap:
connections:
example_connection:
mailbox: "{imap.gmail.com:993/imap/ssl}INBOX"
username: "kadrad26666#gmail.com"
password: "password"
another_connection:
mailbox: "{localhost:143}INBOX"
username: "username"
password: "password"
attachments_dir: "%kernel.root_dir%/../var/imap/attachments"
server_encoding: "UTF-8"
My Index function in IndexController is
public function index($name, \Swift_Mailer $mailer) {
$message = (new \Swift_Message('Hello Email'))
->setFrom('kadrad26666#gmail.com')
->setTo('kadrad26666#gmail.com')
->setBody(
$this->renderView(
// templates/emails/registration.html.twig
'emails/registration.html.twig',
array('name' => $name)
),
'text/html'
)
;
$mailer->send($message);
return $this->render('registration.html.twig'); }
my twig is as follows
<div class="box box-solid alert-block">
<div class="box-header">
<h3 class="box-title"></h3>
</div>
<div class="box-body">
{{render( controller('App\\Controller\\IndexController::index("hello")') ) }}
</div>
</div>
It is exactly in index($name, \Swift_Mailer $mailer) that I am stuck , what parameters should I give.
I don't think this is the most efficient approach in doing this. Including template fragments works in some cases but I doubt whether this is the correct approach for this particular scenario.
But, if you really want to do this, you can create an Swift_Mailer object and pass on to the twig as a parameter,
// Create the Mailer using your created Transport
$mailer = new Swift_Mailer($transport);
// Create a message
$message = (new Swift_Message('Wonderful Subject'))
->setFrom(['john#doe.com' => 'John Doe'])
->setTo(['receiver#domain.org', 'other#domain.org' => 'A name'])
->setBody('Here is the message itself')
;
// Pass the $mailer to the twig as a parameter.
More :- https://swiftmailer.symfony.com/docs/messages.html
What I would do is create a controller function which calls a services function to send the email and embed that controller call to the twig (Like you are already doing). In that Controller function you do not want to accept parameters. Let the auto-wiring handle the arguments needs for services.
Cheers.
Related
I started a project using symfony 4 and the mailer doesn't work, however it should be easy.
before you ask, if i copy past the login and password from my code i'm able to log into my mail account, also i also tried with a netcourrier mail account, also the 2 way authentification is not active and i allowed less secure app to access the mail account.
Here's my conf:
in my .env:
MAILER_URL=gmail://*******#gmail.com:********#localhost
in my controller:
public function contact( \Swift_Mailer $mailer){
$message = (new \Swift_Message('Hello Email'))
->setFrom('*****#gmail.com')
->setTo('*******#gmail.com')
->setBody(
$this->renderView(
// templates/emails/registration.html.twig
'email/registration.html.twig',
array('url' => $url)
),
'text/html'
);
$mailer->send($message);
return $this->render(
'email/index.html.twig');}
and the error i get doing so is :
Connection could not be established with host smtp.gmail.com [ #0]
The problem is your connection SMTP with google, This is correct:
MAILER_URL=smtp://smtp.gmail.com:587?encryption=tls&username=userGmail&password=PassGmail
I have it defined as a service in App/Services, this is the code
<?php
namespace App\Services;
class Enviomail {
private $mailer;
public function __construct(\Swift_Mailer $mailer)
{
$this->mailer = $mailer;
}
public function sendEmail($to, $subject, $texto) {
$message = (new \Swift_Message($subject))
->setFrom('juanitourquiza#gmail.com')
->setTo($to)
->setBody(($texto),'text/html');
return $this->mailer->send($message);
}
}
And to use it I call it from the controller
use App\Services\Enviomail;
........
public function mailsolucion(Request $request, Enviomail $enviomail) {
if ($request->isMethod('POST')) {
$nombre=$request->get("nombre");
$email=$request->get("email");
$numero=$request->get("numero");
$empresa=$request->get("empresa");
$solucion=$request->get("solucion");
if (($nombre=="")||($email=="")||($numero=="")||($empresa=="")){
$this->addFlash(
'alert alert-danger',
'Toda la informaciĆ³n es obligatoria'
);
return $this->redirectToRoute('registro');
}
$emailreceptor="juanitourquiza#gmail.com";
$asunto="Soluciones gruporadical.com";
$texto=$this->renderView(
'emails/soluciones.html.twig',
array(
'nombre' => $nombre,
'email' => $email,
'numero' => $numero,
'empresa' => $empresa,
'solucion' => $solucion,
)
);
$enviomail->sendEmail($emailreceptor,$asunto, $texto);
$this->addFlash(
'alert alert-success',
'Pronto nos pondremos en contacto.'
);
return $this->redirectToRoute('registro');
}
return $this->render('AppBundle:App:contacto.html.twig');
}
Works perfect on Symfony 4.x
I think this is not an issue with the mailer, but with gmail. I copied your steps to try to connect through the smtp server of gmail, but got the same error. When using a different MAILER_URL (a different smtp-server) in the .env file, everything works like it should.
I have a contact form where someone provides his name and email. I want to send him an email now with Laravel.
I found in the docs
To send a message, use the to method on the Mail facade. The to method
accepts an email address, a user instance, or a collection of users.
and in fact
\Mail::to('example#gmail.com')->send(new \App\Mail\Hello);
works. But is it also possible to provide the name for the email receipt?
I wanted to look that up in the Laravel API for the Mail Facade but to my surprise the facade has no to function?
So how can I find out what the to function really does and if I can pass a name parameter as well?
In laravel 5.6, answer to your question is: use associative array for every recpient with 'email' and 'name' keys, should work with $to, $cc, $bcc
$to = [
[
'email' => $email,
'name' => $name,
]
];
\Mail::to($to)->send(new \App\Mail\Hello);
You can use the Mail::send() function that inject a Message class in the callable. The Message class has a function to($email, $name) with the signature you're searching, i.e.:
Mail::send($view, $data, function($message) use ($email, $name) {
$m->to($email, $name);
$m->from('youremail#example.com', 'Your Name');
$m->subject('Hi there');
})
The $view could be a string (an actual view) or an array like these:
['text'=> 'body here']
['html'=> 'body here']
['raw'=> 'body here']
The $data argument will be passed to the $view.
For Laravel < 5.6 one can use this:
$object = new \stdClass();
$object->email = $email;
$object->name = $user->getName();
\Mail::to($object)->queue($mailclass);
see here
I prefer this solution as more readable (no need to use arrays and static string keys).
\Mail::send((new \App\Mail\Hello)
->to('example#gmail.com', 'John Doe');
You can use Mailable class in Laravel:
https://laravel.com/docs/5.5/mail
php artisan make:mail YouMail
These classes are stored in the app/Mail directory.
In config/mail.php you can configue email settings:
'from' => ['address' => 'example#example.com', 'name' => 'App Name'],
for Laravel 8 is like this:
$user = new User;
$user->email = 'example#example.com';
Mail::to($user)->send(new YourMail);
YourMail is Mailable class created by php artisan make:mail YourMail
I'm trying to create a SwiftMailer message using Symfony 2.8 and the SwiftMailer Bundle 2.5, where I send a PDF with a simple HTML message to an address. I can send emails, however all the example code uses methods such as addPart() and attach() which don't exist in the list of methods given by Swift_Message and I can't find any example that uses anything else.
I create a PDF from a rendered Twig template and then create a message to attach it to
$pdf = $this->get('knp_snappy.pdf')->getOutputFromHtml($response);
$message = \Swift_Message::newInstance()
->setSubject('Hello Email')
->setFrom('send#example.com')
->setTo('recipient#example.com')
->setBody(
$this->renderView(
// app/Resources/views/Emails/registration.html.twig
'Emails/registration.html.twig',
array('name' => "test")
),
'text/html'
);
Attachment:
$attachment = \Swift_Attachment::newInstance($pdf, $pdf_name, 'application/pdf');
Both
$message->addPart($attachment, $contentType = "application/pdf", $charset = null);
and
$message->attach(\Swift_Attachment::fromPath('/path/to/image.jpg')->setFilename('myfilename.jpg'));
methods simply do not exist.
Strangely enough, the highlight message says
Method 'attach' not found in class \Swift_Mime_MimePart less...
Referenced method is not found in subject class.
But I've had no success figuring out where this comes from or how I can call the message class properly given that the Swift_Mime_MimePart class is several layers upward in the class hierarchy and is never called or referenced directly in the code.
Looking at all the individual methods called, they all end in return $this, which returns the instance of the object as the generic type in which the method is located in lowest the hierarchy.
Since there's no generic type loading in PHP, setBody returns Swift_Mime_MimePart while the other methods return Swift_Mime_SimpleMessage, instead of ? extends Swift_Mime_MimePart or ? extends Swift_Mime_SimpleMessage. Because the example sets the message in the same chain and setBodyis the last method called, $message is now a Swift_Mime_MimePart instead of the Swift_Message where the attach() method and others are located.
The solution is therefore pretty simple; put the calls on separate lines so $message stays a Swift_Message
$message = \Swift_Message::newInstance();
$message->setSubject('Hello Email')
$message->setFrom('send#example.com')
$message->setTo('recipient#example.com')
$message->setBody(
$this->renderView(
// app/Resources/views/Emails/registration.html.twig
'Emails/registration.html.twig',
array('name' => "test")
),
'text/html'
);
$attachment = \Swift_Attachment::newInstance($pdf, $pdf_name, 'application/pdf');
$message->attach($attachment);
Framework PHP: Symfony2.6
Problem: I would like to add the following functionality to FosUserBundle:
"The admin can re-send the registration confirmation email to a specific user" (in the admin section of the website).
I've already built the "user details" page where the admin can see all the information entered in the registration form and if the the user is enabled/confirmed. If the user is not enabled I will add a button to re-send the confirmation email.
Another solution is to to display a link to the user, after he tries to login with credentials that are not confirmed. Here is a similar question (that unfortunately has no feedback and it's not very clear to me and only covers the second approach): https://stackoverflow.com/questions/25204877/re-sending-confirmation-email-fosuserbundle
Can you please point me towards the easiest and quickest solution?
I know this an old question but today I came across the same problem and I found a simpler solution. Maybe this also helpful to others:
Simply ask the FOSUserBundle for its mailer and use it to re-send the message:
$mailer = $this->get('fos_user.mailer');
$mailer->sendConfirmationEmailMessage($user);
That's it! This will re-send an exact copy of the confirmation mail, since the same FOSUserBundle code is used. No need to manually re-create the message.
Here is a shot at what it takes. Assumptions:
in config.yml, fos_user.service.mailer: fos_user.mailer.twig_swift
user email is known
Controller
/**
* #Route("/remind")
*
*/
class RemindController extends Controller
{
/**
* #Route("/{email}")
* #Template()
*/
public function remindAction($email)
{
$user = $this->get('fos_user.user_manager')->findUserByEmail($email);
$url = $this->generateUrl('fos_user_registration_confirm', array('token' => $user->getConfirmationToken()), true);
$message = \Swift_Message::newInstance()
->setSubject('Registration confirmation')
->setFrom('admin#acmedemo.com')
->setTo($email)
->setContentType('text/html')
->setBody(
$this->renderView(
"AcmeDemoBundle:Remind:email.html.twig", array(
'user' => $user,
'confirmationUrl' => $url))
)
;
$sent = $this->get('mailer')->send($message);
return ['user' => $user,
'url' => $url,
'success' => $sent ? 'Yes' : 'No'];
}
}
Minimalist AcmeDemoBundle:Remind:remind.html.twig template
{{ user.email }}<br>
{{ url }}<br>
{{ success }}
Minimalist AcmeDemoBundle:Remind:email.html.twig template
Please confirm your registration by visiting this link
When I'm trying to send an email using the swiftmailer in laravel I get the folowing error: "Missing argument 2 for UsersController::{closure}()".
My code is below:
Mail::send('emails.default', array('key' => Config::get('settings.WELCOMEMAIL')), function($message, $mail, $subject = 'Welcome!')
{
$message->to($mail)->subject($subject);
});
It's really weird though. The $mail variable contains a valid email address and I'm not using the UsersController at all in this script.
Thanks in advance
You must pass only the $message to the closure. Any additional variable must be passed down with the use keyword:
Mail::send('emails.default', array('key' => Config::get('settings.WELCOMEMAIL')), function($message) use($mail, $subject)
{
$subject = empty($subject) ? 'Welcome!' : $subject;
$message->to($mail)->subject($subject);
});