Browse Source

Migrated Mail from native to Sendgrid API

Change-Id: I751c20bdf77bd9612633f97a4ad61c47227def90
smarcet 1 month ago
parent
commit
7408fbb595

+ 2
- 5
.env.example View File

@@ -36,11 +36,8 @@ SESSION_COOKIE_SECURE=false
36 36
 
37 37
 QUEUE_DRIVER=sync
38 38
 
39
-MAIL_DRIVER=smtp
40
-MAIL_HOST=mailtrap.io
41
-MAIL_PORT=2525
42
-MAIL_USERNAME=null
43
-MAIL_PASSWORD=null
39
+MAIL_DRIVER=sendgrid
40
+SENDGRID_API_KEY='YOUR_SENDGRID_API_KEY'
44 41
 
45 42
 CORS_ALLOWED_HEADERS=origin, content-type, accept, authorization, x-requested-with
46 43
 CORS_ALLOWED_METHODS=GET, POST, OPTIONS, PUT, DELETE

+ 188
- 0
app/Http/Utils/Log/LaravelMailerHandler.php View File

@@ -0,0 +1,188 @@
1
+<?php namespace App\Http\Utils\Log;
2
+/**
3
+ * Copyright 2019 OpenStack Foundation
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ * http://www.apache.org/licenses/LICENSE-2.0
8
+ * Unless required by applicable law or agreed to in writing, software
9
+ * distributed under the License is distributed on an "AS IS" BASIS,
10
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11
+ * See the License for the specific language governing permissions and
12
+ * limitations under the License.
13
+ **/
14
+use Illuminate\Mail\Message;
15
+use Monolog\Handler\MailHandler;
16
+use Monolog\Logger;
17
+use Monolog\Formatter\LineFormatter;
18
+use Illuminate\Support\Facades\Mail;
19
+/**
20
+ * Class LaravelMailerHandler
21
+ * @package App\Http\Utils\Logs
22
+ */
23
+final class LaravelMailerHandler extends MailHandler
24
+{
25
+    /**
26
+     * The email addresses to which the message will be sent
27
+     * @var array
28
+     */
29
+    protected $to;
30
+
31
+    /**
32
+     * The subject of the email
33
+     * @var string
34
+     */
35
+    protected $subject;
36
+
37
+    /**
38
+     * Optional headers for the message
39
+     * @var array
40
+     */
41
+    protected $headers = array();
42
+
43
+    /**
44
+     * Optional parameters for the message
45
+     * @var array
46
+     */
47
+    protected $parameters = array();
48
+
49
+    /**
50
+     * The wordwrap length for the message
51
+     * @var int
52
+     */
53
+    protected $maxColumnWidth;
54
+
55
+    /**
56
+     * The Content-type for the message
57
+     * @var string
58
+     */
59
+    protected $contentType = 'text/plain';
60
+
61
+    /**
62
+     * The encoding for the message
63
+     * @var string
64
+     */
65
+    protected $encoding = 'utf-8';
66
+
67
+    protected $from = null;
68
+
69
+    /**
70
+     * @param string|array $to             The receiver of the mail
71
+     * @param string       $subject        The subject of the mail
72
+     * @param string       $from           The sender of the mail
73
+     * @param int          $level          The minimum logging level at which this handler will be triggered
74
+     * @param bool         $bubble         Whether the messages that are handled can bubble up the stack or not
75
+     * @param int          $maxColumnWidth The maximum column width that the message lines will have
76
+     */
77
+    public function __construct($to, $subject, $from, $level = Logger::ERROR, $bubble = true, $maxColumnWidth = 70)
78
+    {
79
+        parent::__construct($level, $bubble);
80
+        $this->from = $from;
81
+        $this->to = is_array($to) ? $to : array($to);
82
+        $this->subject = $subject;
83
+        $this->addHeader(sprintf('From: %s', $from));
84
+        $this->maxColumnWidth = $maxColumnWidth;
85
+    }
86
+
87
+    /**
88
+     * Add headers to the message
89
+     *
90
+     * @param  string|array $headers Custom added headers
91
+     * @return self
92
+     */
93
+    public function addHeader($headers)
94
+    {
95
+        foreach ((array) $headers as $header) {
96
+            if (strpos($header, "\n") !== false || strpos($header, "\r") !== false) {
97
+                throw new \InvalidArgumentException('Headers can not contain newline characters for security reasons');
98
+            }
99
+            $this->headers[] = $header;
100
+        }
101
+
102
+        return $this;
103
+    }
104
+
105
+    /**
106
+     * Add parameters to the message
107
+     *
108
+     * @param  string|array $parameters Custom added parameters
109
+     * @return self
110
+     */
111
+    public function addParameter($parameters)
112
+    {
113
+        $this->parameters = array_merge($this->parameters, (array) $parameters);
114
+
115
+        return $this;
116
+    }
117
+
118
+    /**
119
+     * {@inheritdoc}
120
+     */
121
+    protected function send($content, array $records)
122
+    {
123
+        $content = wordwrap($content, $this->maxColumnWidth);
124
+
125
+        $subject = $this->subject;
126
+        if ($records) {
127
+            $subjectFormatter = new LineFormatter($this->subject);
128
+            $subject = $subjectFormatter->format($this->getHighestRecord($records));
129
+        }
130
+
131
+        foreach ($this->to as $to) {
132
+            Mail::raw($content, function(Message $message) use($to, $subject, $content){
133
+                $message
134
+                    ->to($to)
135
+                    ->subject($subject)
136
+                    ->setBody($content, 'text/html')
137
+                    ->setFrom($this->from);
138
+            });
139
+        }
140
+    }
141
+
142
+    /**
143
+     * @return string $contentType
144
+     */
145
+    public function getContentType()
146
+    {
147
+        return $this->contentType;
148
+    }
149
+
150
+    /**
151
+     * @return string $encoding
152
+     */
153
+    public function getEncoding()
154
+    {
155
+        return $this->encoding;
156
+    }
157
+
158
+    /**
159
+     * @param  string $contentType The content type of the email - Defaults to text/plain. Use text/html for HTML
160
+     *                             messages.
161
+     * @return self
162
+     */
163
+    public function setContentType($contentType)
164
+    {
165
+        if (strpos($contentType, "\n") !== false || strpos($contentType, "\r") !== false) {
166
+            throw new \InvalidArgumentException('The content type can not contain newline characters to prevent email header injection');
167
+        }
168
+
169
+        $this->contentType = $contentType;
170
+
171
+        return $this;
172
+    }
173
+
174
+    /**
175
+     * @param  string $encoding
176
+     * @return self
177
+     */
178
+    public function setEncoding($encoding)
179
+    {
180
+        if (strpos($encoding, "\n") !== false || strpos($encoding, "\r") !== false) {
181
+            throw new \InvalidArgumentException('The encoding can not contain newline characters to prevent email header injection');
182
+        }
183
+
184
+        $this->encoding = $encoding;
185
+
186
+        return $this;
187
+    }
188
+}

+ 3
- 5
app/Providers/AppServiceProvider.php View File

@@ -14,10 +14,9 @@
14 14
 use Illuminate\Support\Facades\Config;
15 15
 use Illuminate\Support\Facades\Log;
16 16
 use Illuminate\Support\ServiceProvider;
17
-use Monolog\Handler\NativeMailerHandler;
18 17
 use Illuminate\Support\Facades\Validator;
19 18
 use Validators\CustomValidator;
20
-
19
+use App\Http\Utils\Log\LaravelMailerHandler;
21 20
 /**
22 21
  * Class AppServiceProvider
23 22
  * @package App\Providers
@@ -43,9 +42,8 @@ class AppServiceProvider extends ServiceProvider
43 42
         $from = Config::get('log.from_email');
44 43
 
45 44
         if (!empty($to) && !empty($from)) {
46
-
47
-            $subject  = 'openstackid error';
48
-            $handler  = new NativeMailerHandler($to, $subject, $from);
45
+            $subject = Config::get('log.email_subject', 'openstackid-resource-server error');
46
+            $handler = new LaravelMailerHandler($to, $subject, $from);
49 47
             $handler->setLevel(Config::get('log.email_level', 'error'));
50 48
             $logger->pushHandler($handler);
51 49
         }

+ 10
- 9
composer.json View File

@@ -13,22 +13,23 @@
13 13
   "type": "project",
14 14
   "require": {
15 15
     "php": "^7.1.3",
16
+    "ext-json": "*",
17
+    "ext-pdo": "*",
16 18
     "fideloper/proxy": "^4.0",
17
-    "laravel/framework": "5.6.*",
18
-    "laravel/tinker": "^1.0",
19
-    "zendframework/zend-crypt": "3.3.0",
20
-    "zendframework/zend-math": "3.1.1",
21
-    "ircmaxell/random-lib": "1.1.*",
19
+    "glenscott/url-normalizer": "1.4.*",
22 20
     "greggilbert/recaptcha": "2.1.*",
23 21
     "guzzlehttp/guzzle": "6.3.3",
24
-    "smarcet/jose4php": "dev-feature/php7.2-migration",
25
-    "glenscott/url-normalizer": "1.4.*",
22
+    "ircmaxell/random-lib": "1.1.*",
26 23
     "jenssegers/agent": "2.3.*",
24
+    "laravel/framework": "5.6.*",
25
+    "laravel/tinker": "^1.0",
27 26
     "laravelcollective/html": "5.6.*",
28 27
     "phpseclib/phpseclib": "2.0.11",
29 28
     "predis/predis": "1.0.*",
30
-    "ext-json":"*",
31
-    "ext-pdo":"*"
29
+    "s-ichikawa/laravel-sendgrid-driver": "^2.0",
30
+    "smarcet/jose4php": "dev-feature/php7.2-migration",
31
+    "zendframework/zend-crypt": "3.3.0",
32
+    "zendframework/zend-math": "3.1.1"
32 33
   },
33 34
   "require-dev": {
34 35
     "filp/whoops": "^2.0",

+ 1
- 0
config/app.php View File

@@ -153,6 +153,7 @@ return [
153 153
         Collective\Html\HtmlServiceProvider::class,
154 154
         \Providers\OAuth2\ClientAuthContextValidatorFactoryProvider::class,
155 155
         Greggilbert\Recaptcha\RecaptchaServiceProvider::class,
156
+        Sichikawa\LaravelSendgridDriver\SendgridTransportServiceProvider::class,
156 157
     ],
157 158
 
158 159
     /*

+ 3
- 2
config/log.php View File

@@ -20,6 +20,7 @@ return array(
20 20
     //The sender of the mail
21 21
     'from_email'  => env('LOG_EMAIL_FROM'),
22 22
     //Log Level (debug, info, notice, warning, error, critical, alert)
23
-    'level'       => env('LOG_LEVEL', 'error'),
24
-    'email_level' => env('LOG_EMAIL_LEVEL', 'error'),
23
+    'level'         => env('LOG_LEVEL', 'error'),
24
+    'email_level'   => env('LOG_EMAIL_LEVEL', 'error'),
25
+    'email_subject' => env('LOG_EMAIL_SUBJECT', ''),
25 26
 );

+ 4
- 0
config/services.php View File

@@ -35,4 +35,8 @@ return [
35 35
         'secret' => env('STRIPE_SECRET'),
36 36
     ],
37 37
 
38
+    'sendgrid' => [
39
+        'api_key' => env('SENDGRID_API_KEY'),
40
+    ],
41
+
38 42
 ];

Loading…
Cancel
Save