symfony send email code example

Example: send email with swiftmailer symfony

<?php
//This is a class throw it in your symfony project 
//and use it to send all your email 
// easy money <3 
namespace App\CostomClass;  // fix your name space or create a folder named CostomClass in your src

use App\Repository\ParametreRepository;
use Symfony\Component\DependencyInjection\ContainerInterface;

Class SendMail{

    function __construct( $Email , $Subject ,  $text )
    {
        $this->Email = $Email ;             //string
        $this->Subject = $Subject ;         //string
        $this->text = $text ;         //string
    }
 
    //SMTP   

    public function sendMessageWithSMTP()
    {

        $transport = (new \Swift_SmtpTransport('smtp.office365.com', 25, 'tls'))
            ->setUsername('[email protected]')
            ->setPassword('YourPassword');
        $transport->setLocalDomain('[127.0.0.1]');
        $mailer = new \Swift_Mailer($transport);

        try {
            $message = (new \Swift_Message($this->Subject))
                ->setFrom(array('[email protected]' => "Subject"))
                ->setTo( $this->Email)
                //->setBcc($client)
                ->setBody($this->text, 'text/html');
            $mailer->send($message);

        } catch (\Exception $e) {
            return $e->getMessage();
        }

        return 1;

    }

// Gmail 

    public function sendMessageWithGmail()
    {

        $transport = (new \Swift_SmtpTransport('smtp.gmail.com', 465, 'ssl'))
            ->setUsername('[email protected]')
            ->setPassword('Password');
        $transport->setLocalDomain('[127.0.0.1]'); // don't really need it
        $mailer = new \Swift_Mailer($transport);

        try {
            $message = (new \Swift_Message($this->Subject))
                ->setFrom(array('[email protected]' => "Subject"))
                ->setTo( $this->Email)
                //->setBcc($client)
                ->setBody($this->text, 'text/html');
            $mailer->send($message);

        } catch (\Exception $e) {
            return $e->getMessage();
        }

        return 1;

    }
  
// how to use anywhere in your project:
// in any controller 
// $sendMail = new SendMail("[email protected]","test","hello world");
// $result = $sendMail->sendMessageWithSMTP( $mailer);
// or
// $result = $sendMail->sendMessageWithGmail( $mailer);
// dump($result);die(); 1 for the win and erreur mesage if something went wrong 

}