send email with swiftmailer symfony

Solutions on MaxInterview for send email with swiftmailer symfony by the best coders in the world

showing results for - "send email with swiftmailer symfony"
Yanis
05 Jun 2017
1<?php
2//This is a class throw it in your symfony project 
3//and use it to send all your email 
4// easy money <3 
5namespace App\CostomClass;  // fix your name space or create a folder named CostomClass in your src
6
7use App\Repository\ParametreRepository;
8use Symfony\Component\DependencyInjection\ContainerInterface;
9
10Class SendMail{
11
12    function __construct( $Email , $Subject ,  $text )
13    {
14        $this->Email = $Email ;             //string
15        $this->Subject = $Subject ;         //string
16        $this->text = $text ;         //string
17    }
18 
19    //SMTP   
20
21    public function sendMessageWithSMTP()
22    {
23
24        $transport = (new \Swift_SmtpTransport('smtp.office365.com', 25, 'tls'))
25            ->setUsername('youremail@yourhost.xx')
26            ->setPassword('YourPassword');
27        $transport->setLocalDomain('[127.0.0.1]');
28        $mailer = new \Swift_Mailer($transport);
29
30        try {
31            $message = (new \Swift_Message($this->Subject))
32                ->setFrom(array('youremail@yourhost.xx' => "Subject"))
33                ->setTo( $this->Email)
34                //->setBcc($client)
35                ->setBody($this->text, 'text/html');
36            $mailer->send($message);
37
38        } catch (\Exception $e) {
39            return $e->getMessage();
40        }
41
42        return 1;
43
44    }
45
46// Gmail 
47
48    public function sendMessageWithGmail()
49    {
50
51        $transport = (new \Swift_SmtpTransport('smtp.gmail.com', 465, 'ssl'))
52            ->setUsername('mail@gmail.com')
53            ->setPassword('Password');
54        $transport->setLocalDomain('[127.0.0.1]'); // don't really need it
55        $mailer = new \Swift_Mailer($transport);
56
57        try {
58            $message = (new \Swift_Message($this->Subject))
59                ->setFrom(array('mail@gmail.com' => "Subject"))
60                ->setTo( $this->Email)
61                //->setBcc($client)
62                ->setBody($this->text, 'text/html');
63            $mailer->send($message);
64
65        } catch (\Exception $e) {
66            return $e->getMessage();
67        }
68
69        return 1;
70
71    }
72  
73// how to use anywhere in your project:
74// in any controller 
75// $sendMail = new SendMail("youremail@gmail.com","test","hello world");
76// $result = $sendMail->sendMessageWithSMTP( $mailer);
77// or
78// $result = $sendMail->sendMessageWithGmail( $mailer);
79// dump($result);die(); 1 for the win and erreur mesage if something went wrong 
80
81}