PluginProbe
Gmail SMTP / trunk
Gmail SMTP vtrunk
1.2.3.21 1.2.3.20 trunk 1.0.5 1.0.6 1.0.7 1.0.8 1.0.9 1.1.0 1.1.1 1.1.2 1.1.9 1.2.0 1.2.3.14 1.2.3.15 1.2.3.16 1.2.3.18 1.2.3.5
gmail-smtp / main.php

main.php in Gmail SMTP trunk, at main.php

1,175 lines 53.9 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 /*
3 Plugin Name: Gmail SMTP
4 Version: 1.2.3.22
5 Requires at least: 7.0
6 Requires PHP: 8.1
7 Plugin URI: https://wphowto.net/gmail-smtp-plugin-for-wordpress-1341
8 Author: naa986
9 Author URI: https://wphowto.net/
10 Description: Easily send email from your WordPress site via Gmail SMTP server
11 Text Domain: gmail-smtp
12 Domain Path: /languages
13 */
14
15 if (!defined('ABSPATH')){
16 exit;
17 }
18
19 class GMAIL_SMTP {
20
21 var $plugin_version = '1.2.3.22';
22 var $phpmailer_version = '7.0.2';
23 var $google_api_client_version = '2.19.4';
24 var $plugin_url;
25 var $plugin_path;
26
27 function __construct() {
28 define('GMAIL_SMTP_VERSION', $this->plugin_version);
29 define('GMAIL_SMTP_SITE_URL', site_url());
30 define('GMAIL_SMTP_HOME_URL', home_url());
31 define('GMAIL_SMTP_URL', $this->plugin_url());
32 define('GMAIL_SMTP_PATH', $this->plugin_path());
33 $this->plugin_includes();
34 $this->loader_operations();
35 }
36
37 function plugin_includes() {
38 //Google API client library was too big to push to wordpress.org. I had to make it lightweight by keeping only the essential files
39 //Open src/Google/Client.php and check which classes are in use from the /vendor directory.
40 //In addition to the ones in use I had to keep composer and phpseclib as well to avoid a fatal error (and remove everything else).
41 //vendor/google/apiclient-services/src/Google/Service was taking too much space. The plugin only needed to keep the "Gmail.php" file in it.
42 //do a cleanup in both the PHPMailer & Google API Client folders to remove all the git related unnecessary files.
43 /* Only include these scripts when needed to avoid conflicts with other plugins that are using Google API Client
44 include_once('google-api-php-client/vendor/autoload.php');
45 include_once('PHPMailer/PHPMailerAutoload.php');
46 include_once('class.phpmaileroauthgoogle.php');
47 include_once('class.phpmaileroauth.php');
48 */
49 }
50
51 function loader_operations() {
52 if (is_admin()) {
53 include_once('addons/gmail-smtp-addons.php');
54 }
55 add_action('plugins_loaded', array($this, 'plugins_loaded_handler'));
56 add_action('admin_menu', array($this, 'options_menu'));
57 add_action('admin_enqueue_scripts', array($this, 'enqueue_admin_scripts'));
58 add_action('init', array($this, 'plugin_init'));
59 add_action('admin_notices', 'gmail_smtp_admin_notice');
60 if(is_gmail_smtp_configured()){
61 add_filter('pre_wp_mail', 'gmail_smtp_pre_wp_mail', 10, 2);
62 }
63 }
64
65 function enqueue_admin_scripts($hook) {
66 if('settings_page_gmail-smtp-settings' != $hook) {
67 return;
68 }
69 wp_register_style('gmail-smtp-addons-menu', GMAIL_SMTP_URL.'/addons/gmail-smtp-addons.css');
70 wp_enqueue_style('gmail-smtp-addons-menu');
71 }
72
73 function plugins_loaded_handler()
74 {
75 if(is_admin() && current_user_can('manage_options')){
76 add_filter('plugin_action_links', array($this, 'add_plugin_action_links'), 10, 2);
77 }
78 load_plugin_textdomain('gmail-smtp', false, dirname( plugin_basename( __FILE__ ) ) . '/languages/');
79 }
80
81 function plugin_url() {
82 if ($this->plugin_url)
83 return $this->plugin_url;
84 return $this->plugin_url = plugins_url(basename(plugin_dir_path(__FILE__)), basename(__FILE__));
85 }
86
87 function plugin_path() {
88 if ($this->plugin_path)
89 return $this->plugin_path;
90 return $this->plugin_path = untrailingslashit(plugin_dir_path(__FILE__));
91 }
92
93 function add_plugin_action_links($links, $file) {
94 if ($file == plugin_basename(dirname(__FILE__) . '/main.php')) {
95 $links[] = '<a href="options-general.php?page=gmail-smtp-settings">'.__('Settings', 'gmail-smtp').'</a>';
96 }
97 return $links;
98 }
99
100 function options_menu() {
101 add_options_page(__('Gmail SMTP', 'gmail-smtp'), __('Gmail SMTP', 'gmail-smtp'), 'manage_options', 'gmail-smtp-settings', array($this, 'options_page'));
102 }
103
104 function options_page() {
105 $plugin_tabs = array(
106 'gmail-smtp-settings' => __('General', 'gmail-smtp'),
107 'gmail-smtp-settings&action=test-email' => __('Test Email', 'gmail-smtp'),
108 'gmail-smtp-settings&action=revoke-access' => __('Revoke Access', 'gmail-smtp'),
109 'gmail-smtp-settings&action=server-info' => __('Server Info', 'gmail-smtp'),
110 'gmail-smtp-settings&action=addons' => __('Add-ons', 'gmail-smtp'),
111 'gmail-smtp-settings&action=advanced' => __('Advanced', 'gmail-smtp'),
112 );
113 $url = "https://wphowto.net/gmail-smtp-plugin-for-wordpress-1341";
114 $link_text = sprintf(__('Please visit the <a target="_blank" href="%s">Gmail SMTP</a> documentation page for usage instructions.', 'gmail-smtp'), esc_url($url));
115 $allowed_html_tags = array(
116 'a' => array(
117 'href' => array(),
118 'target' => array()
119 )
120 );
121 echo '<div class="wrap"><h2>Gmail SMTP v' . GMAIL_SMTP_VERSION . '</h2>';
122 echo '<div class="update-nag">'.wp_kses($link_text, $allowed_html_tags).'</div>';
123 $current = '';
124 $action = '';
125 if (isset($_GET['page'])) {
126 $current = sanitize_text_field($_GET['page']);
127 if (isset($_GET['action'])) {
128 $action = sanitize_text_field($_GET['action']);
129 $current .= "&action=" . $action;
130 }
131 }
132 $content = '';
133 $content .= '<h2 class="nav-tab-wrapper">';
134 foreach ($plugin_tabs as $location => $tabname) {
135 if ($current == $location) {
136 $class = ' nav-tab-active';
137 } else {
138 $class = '';
139 }
140 $content .= '<a class="nav-tab' . $class . '" href="?page=' . $location . '">' . $tabname . '</a>';
141 }
142 $content .= '</h2>';
143 $allowed_html_tags = array(
144 'a' => array(
145 'href' => array(),
146 'class' => array()
147 ),
148 'h2' => array(
149 'href' => array(),
150 'class' => array()
151 )
152 );
153 echo wp_kses($content, $allowed_html_tags);
154 if(!empty($action))
155 {
156 switch($action)
157 {
158 case 'test-email':
159 $this->test_email_settings();
160 break;
161 case 'revoke-access':
162 $this->revoke_access_settings();
163 break;
164 case 'server-info':
165 $this->server_info_settings();
166 break;
167 case 'addons':
168 gmail_smtp_display_addons();
169 break;
170 case 'advanced':
171 $this->advanced_settings();
172 break;
173 }
174 }
175 else
176 {
177 $this->general_settings();
178 }
179 echo '</div>';
180 }
181
182 function plugin_init(){
183 if(is_admin()){
184 if(isset($_GET['action']) && $_GET['action'] == "oauth_grant"){
185
186 include_once('google-api-php-client/vendor/autoload.php');
187 include_once('class.phpmaileroauthgoogle.php');
188
189 if (isset($_GET['code'])) {
190 $authCode = sanitize_text_field($_GET['code']);
191 $accessToken = GmailXOAuth2::resetCredentials($authCode);
192 if(isset($accessToken) && !empty($accessToken)){
193 //echo __('Access Granted Successfully!', 'gmail-smtp');
194 $_GET['gmail_smtp_access_granted'] = "yes";
195 }
196 else{
197 $_GET['gmail_smtp_access_granted'] = "no";
198 }
199 }
200 else {
201 // If we don't have an authorization code then get one
202 $authUrl_array = GmailXOAuth2::authenticate();
203 if(isset($authUrl_array['authorization_uri'])){
204 $authUrl= $authUrl_array['authorization_uri'];
205 wp_redirect(esc_url_raw($authUrl));
206 exit;
207 }
208 }
209 // Unix timestamp of when the token will expire, and need refreshing
210 // echo $token->expires;
211 }
212 }
213 }
214
215 function test_email_settings(){
216 if(isset($_POST['gmail_smtp_send_test_email'])){
217 $nonce = $_REQUEST['_wpnonce'];
218 if (!wp_verify_nonce($nonce, 'gmail_smtp_test_email')) {
219 wp_die('Error! Nonce Security Check Failed! please send the test email again.');
220 }
221 $to = '';
222 if(isset($_POST['gmail_smtp_to_email']) && !empty($_POST['gmail_smtp_to_email'])){
223 $to = sanitize_email($_POST['gmail_smtp_to_email']);
224 }
225 $subject = '';
226 if(isset($_POST['gmail_smtp_email_subject']) && !empty($_POST['gmail_smtp_email_subject'])){
227 $subject = sanitize_text_field(stripslashes($_POST['gmail_smtp_email_subject']));
228 }
229 $message = '';
230 if(isset($_POST['gmail_smtp_email_body']) && !empty($_POST['gmail_smtp_email_body'])){
231 $message = sanitize_textarea_field(stripslashes($_POST['gmail_smtp_email_body']));
232 }
233
234 wp_mail($to, $subject, $message);
235 }
236 ?>
237 <form method="post" action="">
238 <?php wp_nonce_field('gmail_smtp_test_email'); ?>
239
240 <table class="form-table">
241
242 <tbody>
243
244 <tr valign="top">
245 <th scope="row"><label for="gmail_smtp_to_email"><?php _e('To', 'gmail-smtp');?></label></th>
246 <td><input name="gmail_smtp_to_email" type="text" id="gmail_smtp_to_email" value="" class="regular-text">
247 <p class="description"><?php _e('Email address of the recipient', 'gmail-smtp');?></p></td>
248 </tr>
249
250 <tr valign="top">
251 <th scope="row"><label for="gmail_smtp_email_subject"><?php _e('Subject', 'gmail-smtp');?></label></th>
252 <td><input name="gmail_smtp_email_subject" type="text" id="gmail_smtp_email_subject" value="" class="regular-text">
253 <p class="description"><?php _e('Subject of the email', 'gmail-smtp');?></p></td>
254 </tr>
255
256 <tr valign="top">
257 <th scope="row"><label for="gmail_smtp_email_body"><?php _e('Message', 'gmail-smtp');?></label></th>
258 <td><textarea name="gmail_smtp_email_body" id="gmail_smtp_email_body" rows="6"></textarea>
259 <p class="description"><?php _e('Email body', 'gmail-smtp');?></p></td>
260 </tr>
261
262 </tbody>
263
264 </table>
265
266 <p class="submit"><input type="submit" name="gmail_smtp_send_test_email" id="gmail_smtp_send_test_email" class="button button-primary" value="<?php _e('Send Email', 'gmail-smtp');?>"></p>
267 </form>
268
269 <?php
270 }
271
272 function revoke_access_settings()
273 {
274 if (isset($_POST['gmail_smtp_delete_access_key'])) {
275 $nonce = $_REQUEST['_wpnonce'];
276 if (!wp_verify_nonce($nonce, 'gmail_smtp_delete_accesskey')) {
277 wp_die('Error! Nonce Security Check Failed! please click on the button again.');
278 }
279 $options = array();
280 $options['oauth_access_token'] = '';
281 gmail_smtp_update_option($options);
282 echo '<div id="message" class="updated fade"><p><strong>';
283 echo __('Access Key Successfully Deleted!', 'gmail-smtp');
284 echo '</strong></p></div>';
285 }
286 $url = "https://security.google.com/settings/security/permissions";
287 $link_text = sprintf(wp_kses(__('Revoke access by visiting <a target="_blank" href="%s">account settings</a>.', 'gmail-smtp'), array('a' => array('href' => array(), 'target' => array()))), esc_url($url));
288 ?>
289
290 <div class="update-nag">
291 <?php _e('Generally you do not need to do anything on this page. However, for some reason if you wish to revoke access from your application please follow these steps:', 'gmail-smtp');?>
292 <ol>
293 <li><?php echo $link_text;?></li>
294 <li><?php _e('Delete your existing access key by clicking on the "Delete Access Key" button.', 'gmail-smtp');?></li>
295 </ol>
296 </div>
297
298 <form method="post" action="<?php echo $_SERVER["REQUEST_URI"]; ?>">
299 <?php wp_nonce_field('gmail_smtp_delete_accesskey'); ?>
300
301 <p class="submit"><input type="submit" name="gmail_smtp_delete_access_key" id="gmail_smtp_delete_access_key" class="button button-primary" value="Delete Access Key"></p>
302 </form>
303
304 <?php
305 }
306
307 function server_info_settings()
308 {
309 $server_info = '';
310 $server_info .= sprintf('OS: %s%s', php_uname(), PHP_EOL);
311 $version = '';
312 if(version_compare(PHP_VERSION, '5.4', '<')) {
313 $version = ' (PHPMailer requires PHP 5.4 or later in order to send email)';
314 }
315 $server_info .= sprintf('PHP version: %s%s%s', PHP_VERSION, $version, PHP_EOL);
316 $server_info .= sprintf('WordPress version: %s%s', get_bloginfo('version'), PHP_EOL);
317 $server_info .= sprintf('WordPress multisite: %s%s', (is_multisite() ? 'Yes' : 'No'), PHP_EOL);
318 $openssl_status = 'Available';
319 $openssl_text = '';
320 if(!extension_loaded('openssl') && !defined('OPENSSL_ALGO_SHA1')){
321 $openssl_status = 'Not available';
322 $openssl_text = ' (openssl extension is required in order to use any kind of encryption like TLS or SSL. Gmail SMTP server does not allow you to send email without an encrypted connection)';
323 }
324 $server_info .= sprintf('openssl: %s%s%s', $openssl_status, $openssl_text, PHP_EOL);
325 $server_info .= sprintf('allow_url_fopen: %s%s', (ini_get('allow_url_fopen') ? 'Enabled' : 'Disabled'), PHP_EOL);
326 $stream_socket_client_status = 'Not Available';
327 $fsockopen_status = 'Not Available';
328 $socket_enabled = false;
329 if(function_exists('stream_socket_client')){
330 $stream_socket_client_status = 'Available';
331 $socket_enabled = true;
332 }
333 if(function_exists('fsockopen')){
334 $fsockopen_status = 'Available';
335 $socket_enabled = true;
336 }
337 $socket_text = '';
338 if(!$socket_enabled){
339 $socket_text = ' (In order to make a SMTP connection your server needs to have either stream_socket_client or fsockopen)';
340 }
341 $server_info .= sprintf('stream_socket_client: %s%s', $stream_socket_client_status, PHP_EOL);
342 $server_info .= sprintf('fsockopen: %s%s%s', $fsockopen_status, $socket_text, PHP_EOL);
343 $cURL_status = 'Not Available. In order to make a SMTP connection your server needs to have cURL enabled';
344 if(function_exists('curl_init')){
345 $cURL_status = 'Available';
346 }
347 $server_info .= sprintf('cURL: %s%s', $cURL_status, PHP_EOL);
348 if(function_exists('curl_version')){
349 $curl_version = curl_version();
350 $server_info .= sprintf('cURL Version: %s, %s%s', $curl_version['version'], $curl_version['ssl_version'], PHP_EOL);
351 }
352 ?>
353 <textarea rows="10" cols="50" class="large-text code"><?php echo esc_textarea($server_info);?></textarea>
354 <?php
355 }
356
357 function general_settings() {
358
359 if (isset($_POST['gmail_smtp_update_settings'])) {
360 $nonce = $_REQUEST['_wpnonce'];
361 if (!wp_verify_nonce($nonce, 'gmail_smtp_general_settings')) {
362 wp_die('Error! Nonce Security Check Failed! please save the settings again.');
363 }
364 $client_id = '';
365 if(isset($_POST['oauth_client_id']) && !empty($_POST['oauth_client_id'])){
366 $client_id = sanitize_text_field($_POST['oauth_client_id']);
367 }
368 $client_secret = '';
369 if(isset($_POST['oauth_client_secret']) && !empty($_POST['oauth_client_secret'])){
370 $client_secret = sanitize_text_field($_POST['oauth_client_secret']);
371 }
372 $oauth_user_email = '';
373 if(isset($_POST['oauth_user_email']) && !empty($_POST['oauth_user_email'])){
374 $oauth_user_email = sanitize_email($_POST['oauth_user_email']);
375 }
376 $from_email = '';
377 if(isset($_POST['from_email']) && !empty($_POST['from_email'])){
378 $from_email = sanitize_email($_POST['from_email']);
379 }
380 $from_name = '';
381 if(isset($_POST['from_name']) && !empty($_POST['from_name'])){
382 $from_name = sanitize_text_field(stripslashes($_POST['from_name']));
383 }
384 $type_of_encryption = '';
385 if(isset($_POST['type_of_encryption']) && !empty($_POST['type_of_encryption'])){
386 $type_of_encryption = sanitize_text_field($_POST['type_of_encryption']);
387 }
388 $smtp_port = '';
389 if(isset($_POST['smtp_port']) && !empty($_POST['smtp_port'])){
390 $smtp_port = sanitize_text_field($_POST['smtp_port']);
391 }
392 $disable_ssl_verification = '';
393 if(isset($_POST['disable_ssl_verification']) && !empty($_POST['disable_ssl_verification'])){
394 $disable_ssl_verification = sanitize_text_field($_POST['disable_ssl_verification']);
395 }
396 $options = array();
397 $options['oauth_client_id'] = $client_id;
398 $options['oauth_client_secret'] = $client_secret;
399 $options['oauth_user_email'] = $oauth_user_email;
400 $options['from_email'] = $from_email;
401 $options['from_name'] = $from_name;
402 $options['type_of_encryption'] = $type_of_encryption;
403 $options['smtp_port'] = $smtp_port;
404 $options['disable_ssl_verification'] = $disable_ssl_verification;
405 gmail_smtp_update_option($options);
406 echo '<div id="message" class="updated fade"><p><strong>';
407 echo __('Settings Saved!', 'gmail-smtp');
408 echo '</strong></p></div>';
409 }
410
411 if (isset($_GET['gmail_smtp_access_granted'])) {
412 if($_GET['gmail_smtp_access_granted']=="yes"){
413 echo '<div id="message" class="updated fade"><p><strong>';
414 echo __('Access Granted Successfully!', 'gmail-smtp');
415 echo '</strong></p></div>';
416 }
417 else{
418 echo '<div id="message" class="error"><p><strong>';
419 echo __('Access could not be granted', 'gmail-smtp');
420 echo '</strong></p></div>';
421 }
422 }
423
424 $options = gmail_smtp_get_option();
425 if(!is_array($options)){
426 $options = array();
427 $options['oauth_client_id'] = '';
428 $options['oauth_client_secret'] = '';
429 $options['oauth_user_email'] = '';
430 $options['from_email'] = '';
431 $options['from_name'] = '';
432 $options['type_of_encryption'] = '';
433 $options['smtp_port'] = '';
434 $options['disable_ssl_verification'] = '';
435 }
436 // Avoid warning notice since this option was added later
437 if(!isset($options['disable_ssl_verification'])){
438 $options['disable_ssl_verification'] = '';
439 }
440 ?>
441 <form method="post" action="">
442 <?php wp_nonce_field('gmail_smtp_general_settings'); ?>
443
444 <table class="form-table">
445
446 <tbody>
447
448 <tr valign="top">
449 <th scope="row"><label><?php _e('SMTP Status', 'gmail-smtp');?></label></th>
450 <?php if(isset($options['oauth_access_token']) && !empty($options['oauth_access_token'])){ ?>
451 <td><img src="<?php echo esc_attr(GMAIL_SMTP_URL.'/images/connected.png');?>" style="height: 30px;">
452 <p class="description"><?php _e('Connected', 'gmail-smtp');?></p></td>
453 <?php }
454 else{ ?>
455 <td><img src="<?php echo esc_attr(GMAIL_SMTP_URL.'/images/not-connected.png');?>" style="height: 30px;">
456 <p class="description"><?php _e('Not Connected', 'gmail-smtp');?></p></td>
457 <?php } ?>
458 </tr>
459
460 <tr valign="top">
461 <th scope="row"><label for="oauth_redirect_uri"><?php _e('Authorized Redirect URI', 'gmail-smtp');?></label></th>
462 <td><input name="oauth_redirect_uri" type="text" id="oauth_redirect_uri" value="<?php echo esc_url(admin_url("options-general.php?page=gmail-smtp-settings&action=oauth_grant")); ?>" readonly class="regular-text code">
463 <p class="description"><?php _e('Copy this URL into your web application', 'gmail-smtp');?></p></td>
464 </tr>
465
466 <tr valign="top">
467 <th scope="row"><label for="oauth_client_id"><?php _e('Client ID', 'gmail-smtp');?></label></th>
468 <td><input name="oauth_client_id" type="text" id="oauth_client_id" value="<?php echo esc_attr($options['oauth_client_id']); ?>" class="regular-text code">
469 <p class="description"><?php _e('The client ID of your web application', 'gmail-smtp');?></p></td>
470 </tr>
471
472 <tr valign="top">
473 <th scope="row"><label for="oauth_client_secret"><?php _e('Client Secret', 'gmail-smtp');?></label></th>
474 <td><input name="oauth_client_secret" type="text" id="oauth_client_secret" value="<?php echo esc_attr($options['oauth_client_secret']); ?>" class="regular-text code">
475 <p class="description"><?php _e('The client secret of your web application', 'gmail-smtp');?></p></td>
476 </tr>
477
478 <tr valign="top">
479 <th scope="row"><label for="oauth_user_email"><?php _e('OAuth Email Address', 'gmail-smtp');?></label></th>
480 <td><input name="oauth_user_email" type="text" id="oauth_user_email" value="<?php echo esc_attr($options['oauth_user_email']); ?>" class="regular-text code">
481 <p class="description"><?php _e('The email address that you will use for SMTP authentication. This should be the same email used in the Google Developers Console.', 'gmail-smtp');?></p></td>
482 </tr>
483
484 <tr valign="top">
485 <th scope="row"><label for="from_email"><?php _e('From Email Address', 'gmail-smtp');?></label></th>
486 <td><input name="from_email" type="text" id="from_email" value="<?php echo esc_attr($options['from_email']); ?>" class="regular-text code">
487 <p class="description"><?php _e('The email address which will be used as the From Address when sending an email. Gmail currently ignores this value if it is different from the OAuth Email Address.', 'gmail-smtp');?></p></td>
488 </tr>
489
490 <tr valign="top">
491 <th scope="row"><label for="from_name"><?php _e('From Name', 'gmail-smtp');?></label></th>
492 <td><input name="from_name" type="text" id="from_name" value="<?php echo esc_attr($options['from_name']); ?>" class="regular-text code">
493 <p class="description"><?php _e('The name which will be used as the From Name when sending an email.', 'gmail-smtp');?></p></td>
494 </tr>
495
496 <tr>
497 <th scope="row"><label for="type_of_encryption"><?php _e('Type of Encryption', 'gmail-smtp');?></label></th>
498 <td>
499 <select name="type_of_encryption" id="type_of_encryption">
500 <option value="tls" <?php echo selected( $options['type_of_encryption'], 'tls', false );?>><?php _e('TLS', 'gmail-smtp');?></option>
501 <option value="ssl" <?php echo selected( $options['type_of_encryption'], 'ssl', false );?>><?php _e('SSL', 'gmail-smtp');?></option>
502 </select>
503 <p class="description"><?php _e('The encryption which will be used when sending an email (TLS is recommended).', 'gmail-smtp');?></p>
504 </td>
505 </tr>
506
507 <tr valign="top">
508 <th scope="row"><label for="smtp_port"><?php _e('SMTP Port', 'gmail-smtp');?></label></th>
509 <td><input name="smtp_port" type="text" id="smtp_port" value="<?php echo esc_attr($options['smtp_port']); ?>" class="regular-text code">
510 <p class="description"><?php _e('The port which will be used when sending an email. If you choose TLS it should be set to 587. For SSL use port 465 instead.', 'gmail-smtp');?></p></td>
511 </tr>
512
513 <tr valign="top">
514 <th scope="row"><label for="disable_ssl_verification"><?php _e('Disable SSL Certificate Verification', 'gmail-smtp');?></label></th>
515 <td><input name="disable_ssl_verification" type="checkbox" id="disable_ssl_verification" <?php checked($options['disable_ssl_verification'], 1); ?> value="1">
516 <p class="description"><?php _e('As of PHP 5.6 you will get a warning/error if the SSL certificate on the server is not properly configured. You can check this option to disable that default behaviour. Please note that PHP 5.6 made this change for a good reason. So you should get your host to fix the SSL configurations instead of bypassing it', 'gmail-smtp');?></p></td>
517 </tr>
518
519 </tbody>
520
521 </table>
522
523 <p class="submit"><input type="submit" name="gmail_smtp_update_settings" id="gmail_smtp_update_settings" class="button button-primary" value="<?php _e('Save Changes', 'gmail-smtp');?>"></p>
524 </form>
525
526 <?php
527 if($this->can_grant_permission()){
528 ?>
529 <a class="button button-primary" href="<?php echo $_SERVER["REQUEST_URI"].'&action=oauth_grant'; ?>"><?php _e('Grant Permission', 'gmail-smtp');?></a>
530 <?php
531 }
532 }
533
534 function advanced_settings() {
535 ?>
536 <div class="update-nag"><?php _e('Settings from add-ons will appear here.', 'gmail-smtp');?></div>
537 <?php
538 if (isset($_POST['gmail_smtp_update_advanced_settings'])) {
539 $nonce = $_REQUEST['_wpnonce'];
540 if (!wp_verify_nonce($nonce, 'gmail_smtp_advanced_settings')) {
541 wp_die('Error! Nonce Security Check Failed! please save the settings again.');
542 }
543 $post = $_POST;
544 do_action('gmail_smtp_advanced_settings_submitted', $post);
545 echo '<div id="message" class="updated fade"><p><strong>';
546 echo __('Settings Saved!', 'gmail-smtp');
547 echo '</strong></p></div>';
548 }
549 $settings_fields = '';
550 $settings_fields = apply_filters('gmail_smtp_advanced_settings_fields', $settings_fields);
551 if(empty($settings_fields)){
552 return;
553 }
554 ?>
555 <form method="post" action="">
556 <?php wp_nonce_field('gmail_smtp_advanced_settings'); ?>
557
558 <table class="form-table">
559 <tbody>
560 <?php
561 if(!empty($settings_fields)){
562 echo $settings_fields;
563 }
564 ?>
565 </tbody>
566
567 </table>
568
569 <p class="submit"><input type="submit" name="gmail_smtp_update_advanced_settings" id="gmail_smtp_update_advanced_settings" class="button button-primary" value="<?php _e('Save Changes', 'gmail-smtp');?>"></p>
570 </form>
571 <?php
572 }
573
574 function can_grant_permission(){
575 $options = gmail_smtp_get_option();
576 $grant_permission = true;
577 if(!isset($options['oauth_client_id']) || empty($options['oauth_client_id'])){
578 $grant_permission = false;
579 }
580 if(!isset($options['oauth_client_secret']) || empty($options['oauth_client_secret'])){
581 $grant_permission = false;
582 }
583 if(isset($options['oauth_access_token']) && !empty($options['oauth_access_token'])){
584 $grant_permission = false;
585 }
586 return $grant_permission;
587 }
588
589 }
590
591 function gmail_smtp_get_option(){
592 $options = get_option('gmail_smtp_options');
593 return $options;
594 }
595
596 function gmail_smtp_update_option($new_options){
597 $empty_options = gmail_smtp_get_empty_options_array();
598 $options = gmail_smtp_get_option();
599 if(is_array($options)){
600 $current_options = array_merge($empty_options, $options);
601 $updated_options = array_merge($current_options, $new_options);
602 update_option('gmail_smtp_options', $updated_options);
603 }
604 else{
605 $updated_options = array_merge($empty_options, $new_options);
606 update_option('gmail_smtp_options', $updated_options);
607 }
608 }
609
610 function gmail_smtp_get_empty_options_array(){
611 $options = array();
612 $options['oauth_client_id'] = '';
613 $options['oauth_client_secret'] = '';
614 $options['oauth_access_token'] = '';
615 $options['oauth_user_email'] = '';
616 $options['from_email'] = '';
617 $options['from_name'] = '';
618 $options['type_of_encryption'] = '';
619 $options['smtp_port'] = '';
620 $options['disable_ssl_verification'] = '';
621 return $options;
622 }
623
624 function gmail_smtp_admin_notice() {
625 if(!is_gmail_smtp_configured()){
626 ?>
627 <div class="error">
628 <p><?php _e('Gmail SMTP plugin cannot send email until you enter your credentials in the settings and grant access to your web application.', 'gmail-smtp'); ?></p>
629 </div>
630 <?php
631 }
632 if(version_compare(PHP_VERSION, '5.6', '<')){
633 ?>
634 <div class="error">
635 <p><?php _e('Gmail SMTP plugin requires PHP 5.6 or higher. Please contact your web host to update your PHP version.', 'gmail-smtp'); ?></p>
636 </div>
637 <?php
638 }
639 }
640
641 function is_gmail_smtp_configured() {
642 $options = gmail_smtp_get_option();
643 $smtp_configured = true;
644 if(!isset($options['oauth_client_id']) || empty($options['oauth_client_id'])){
645 $smtp_configured = false;
646 }
647 if(!isset($options['oauth_client_secret']) || empty($options['oauth_client_secret'])){
648 $smtp_configured = false;
649 }
650 if(!isset($options['oauth_access_token']) || empty($options['oauth_access_token'])){
651 $smtp_configured = false;
652 }
653 if(!isset($options['oauth_user_email']) || empty($options['oauth_user_email'])){
654 $smtp_configured = false;
655 }
656 if(!isset($options['from_email']) || empty($options['from_email'])){
657 $smtp_configured = false;
658 }
659 if(!isset($options['from_name']) || empty($options['from_name'])){
660 $smtp_configured = false;
661 }
662 if(!isset($options['type_of_encryption']) || empty($options['type_of_encryption'])){
663 $smtp_configured = false;
664 }
665 if(!isset($options['smtp_port']) || empty($options['smtp_port'])){
666 $smtp_configured = false;
667 }
668 return $smtp_configured;
669 }
670
671 $GLOBALS['gmail-smtp'] = new GMAIL_SMTP();
672
673 function gmail_smtp_pre_wp_mail($null, $atts)
674 {
675 if ( isset( $atts['to'] ) ) {
676 $to = $atts['to'];
677 }
678
679 if ( ! is_array( $to ) ) {
680 $to = explode( ',', $to );
681 }
682
683 if ( isset( $atts['subject'] ) ) {
684 $subject = $atts['subject'];
685 }
686
687 if ( isset( $atts['message'] ) ) {
688 $message = $atts['message'];
689 }
690
691 if ( isset( $atts['headers'] ) ) {
692 $headers = $atts['headers'];
693 }
694
695 if ( isset( $atts['attachments'] ) ) {
696 $attachments = $atts['attachments'];
697 if ( ! is_array( $attachments ) ) {
698 $attachments = explode( "\n", str_replace( "\r\n", "\n", $attachments ) );
699 }
700 }
701
702 if ( isset( $atts['embeds'] ) ) {
703 $embeds = $atts['embeds'];
704 if ( ! is_array( $embeds ) ) {
705 $embeds = explode( "\n", str_replace( "\r\n", "\n", $embeds ) );
706 }
707 }
708
709 require_once ABSPATH . WPINC . '/PHPMailer/PHPMailer.php';
710 require_once ABSPATH . WPINC . '/PHPMailer/SMTP.php';
711 require_once ABSPATH . WPINC . '/PHPMailer/Exception.php';
712 include_once('google-api-php-client/vendor/autoload.php');
713 include_once('class.phpmaileroauthgoogle.php');
714 include_once('class.phpmaileroauth.php');
715
716 $options = gmail_smtp_get_option();
717
718 $phpmailer = new PHPMailerOAuth( true ); /* this must be the custom class we created */
719
720 // Tell PHPMailer to use SMTP
721 $phpmailer->isSMTP();
722
723 // Set AuthType
724 $phpmailer->AuthType = 'XOAUTH2';
725
726 // Whether to use SMTP authentication
727 $phpmailer->SMTPAuth = true;
728
729 // Set the encryption system to use - ssl (deprecated) or tls
730 $phpmailer->SMTPSecure = $options['type_of_encryption'];
731
732 // Set the hostname of the mail server
733 $phpmailer->Host = 'smtp.gmail.com';
734
735 // Set the SMTP port number - 587 for authenticated TLS, a.k.a. RFC4409 SMTP submission
736 $phpmailer->Port = $options['smtp_port'];
737
738 $phpmailer->SMTPAutoTLS = false;
739
740 //enable debug when sending a test mail
741 if(isset($_POST['gmail_smtp_send_test_email'])){
742 if(is_admin() && current_user_can('manage_options')){
743 $phpmailer->SMTPDebug = 4;
744 // Ask for HTML-friendly debug output
745 $phpmailer->Debugoutput = 'html';
746 }
747 }
748
749 //disable ssl certificate verification if checked
750 if(isset($options['disable_ssl_verification']) && !empty($options['disable_ssl_verification'])){
751 $phpmailer->SMTPOptions = array(
752 'ssl' => array(
753 'verify_peer' => false,
754 'verify_peer_name' => false,
755 'allow_self_signed' => true
756 )
757 );
758 }
759 // User Email to use for SMTP authentication - Use the same Email used in Google Developer Console
760 $phpmailer->oauthUserEmail = $options['oauth_user_email'];
761
762 //Obtained From Google Developer Console
763 $phpmailer->oauthClientId = $options['oauth_client_id'];
764
765 //Obtained From Google Developer Console
766 $phpmailer->oauthClientSecret = $options['oauth_client_secret'];
767
768 $gmail_token = json_decode($options['oauth_access_token'], true);
769
770 //Obtained By running get_oauth_token.php after setting up APP in Google Developer Console.
771 //Set Redirect URI in Developer Console as [https/http]://<yourdomain>/<folder>/get_oauth_token.php
772 // eg: http://localhost/phpmail/get_oauth_token.php
773 $phpmailer->oauthRefreshToken = $gmail_token['refresh_token'];
774
775 // Headers.
776 $cc = array();
777 $bcc = array();
778 $reply_to = array();
779
780 if ( empty( $headers ) ) {
781 $headers = array();
782 } else {
783 if ( ! is_array( $headers ) ) {
784 /*
785 * Explode the headers out, so this function can take
786 * both string headers and an array of headers.
787 */
788 $tempheaders = explode( "\n", str_replace( "\r\n", "\n", $headers ) );
789 } else {
790 $tempheaders = $headers;
791 }
792 $headers = array();
793
794 // If it's actually got contents.
795 if ( ! empty( $tempheaders ) ) {
796 // Iterate through the raw headers.
797 foreach ( (array) $tempheaders as $header ) {
798 if ( ! str_contains( $header, ':' ) ) {
799 if ( false !== stripos( $header, 'boundary=' ) ) {
800 $parts = preg_split( '/boundary=/i', trim( $header ) );
801 $boundary = trim( str_replace( array( "'", '"' ), '', $parts[1] ) );
802 }
803 continue;
804 }
805 // Explode them out.
806 list( $name, $content ) = explode( ':', trim( $header ), 2 );
807
808 // Cleanup crew.
809 $name = trim( $name );
810 $content = trim( $content );
811
812 switch ( strtolower( $name ) ) {
813 // Mainly for legacy -- process a "From:" header if it's there.
814 case 'from':
815 $bracket_pos = strpos( $content, '<' );
816 if ( false !== $bracket_pos ) {
817 // Text before the bracketed email is the "From" name.
818 if ( $bracket_pos > 0 ) {
819 $from_name = substr( $content, 0, $bracket_pos );
820 $from_name = str_replace( '"', '', $from_name );
821 $from_name = trim( $from_name );
822 }
823
824 $from_email = substr( $content, $bracket_pos + 1 );
825 $from_email = str_replace( '>', '', $from_email );
826 $from_email = trim( $from_email );
827
828 // Avoid setting an empty $from_email.
829 } elseif ( '' !== trim( $content ) ) {
830 $from_email = trim( $content );
831 }
832 break;
833 case 'content-type':
834 if ( str_contains( $content, ';' ) ) {
835 list( $type, $charset_content ) = explode( ';', $content );
836 $content_type = trim( $type );
837 if ( false !== stripos( $charset_content, 'charset=' ) ) {
838 $charset = trim( str_replace( array( 'charset=', '"' ), '', $charset_content ) );
839 } elseif ( false !== stripos( $charset_content, 'boundary=' ) ) {
840 $boundary = trim( str_replace( array( 'BOUNDARY=', 'boundary=', '"' ), '', $charset_content ) );
841 $charset = '';
842 if ( preg_match( '~^multipart/(\S+)~', $content_type, $matches ) ) {
843 $content_type = 'multipart/' . strtolower( $matches[1] ) . '; boundary="' . $boundary . '"';
844 }
845 }
846
847 // Avoid setting an empty $content_type.
848 } elseif ( '' !== trim( $content ) ) {
849 $content_type = trim( $content );
850 }
851 break;
852 case 'cc':
853 $cc = array_merge( (array) $cc, explode( ',', $content ) );
854 break;
855 case 'bcc':
856 $bcc = array_merge( (array) $bcc, explode( ',', $content ) );
857 break;
858 case 'reply-to':
859 $reply_to = array_merge( (array) $reply_to, explode( ',', $content ) );
860 break;
861 default:
862 // Add it to our grand headers array.
863 $headers[ trim( $name ) ] = trim( $content );
864 break;
865 }
866 }
867 }
868 }
869
870 // Empty out the values that may be set.
871 $phpmailer->clearAllRecipients();
872 $phpmailer->clearAttachments();
873 $phpmailer->clearCustomHeaders();
874 $phpmailer->clearReplyTos();
875 $phpmailer->Body = '';
876 $phpmailer->AltBody = '';
877
878 /*
879 * Reset encoding to 8-bit, as it may have been automatically downgraded
880 * to 7-bit by PHPMailer (based on the body contents) in a previous call
881 * to wp_mail().
882 *
883 * See https://core.trac.wordpress.org/ticket/33972
884 */
885 $phpmailer->Encoding = PHPMailer\PHPMailer\PHPMailer::ENCODING_8BIT;
886
887 // Set "From" name and email.
888
889 // If we don't have a name from the input headers.
890 if ( ! isset( $from_name ) ) {
891 $from_name = $options['from_name'];//'WordPress';
892 }
893
894 /*
895 * If we don't have an email from the input headers, default to wordpress@$sitename
896 * Some hosts will block outgoing mail from this address if it doesn't exist,
897 * but there's no easy alternative. Defaulting to admin_email might appear to be
898 * another option, but some hosts may refuse to relay mail from an unknown domain.
899 * See https://core.trac.wordpress.org/ticket/5007.
900 */
901 if ( ! isset( $from_email ) ) {
902 // Get the site domain and get rid of www.
903 $sitename = wp_parse_url( network_home_url(), PHP_URL_HOST );
904 $from_email = 'wordpress@';
905
906 if ( null !== $sitename ) {
907 if ( str_starts_with( $sitename, 'www.' ) ) {
908 $sitename = substr( $sitename, 4 );
909 }
910
911 $from_email .= $sitename;
912 }
913 $from_email = $options['from_email'];//'wordpress@' . $sitename;
914 }
915
916 /**
917 * Filters the email address to send from.
918 *
919 * @since 2.2.0
920 *
921 * @param string $from_email Email address to send from.
922 */
923 $from_email = apply_filters( 'wp_mail_from', $from_email );
924
925 /**
926 * Filters the name to associate with the "from" email address.
927 *
928 * @since 2.3.0
929 *
930 * @param string $from_name Name associated with the "from" email address.
931 */
932 $from_name = apply_filters( 'wp_mail_from_name', $from_name );
933
934 try {
935 $phpmailer->setFrom( $from_email, $from_name );
936 } catch ( PHPMailer\PHPMailer\Exception $e ) {
937 $mail_error_data = compact( 'to', 'subject', 'message', 'headers', 'attachments' );
938 $mail_error_data['phpmailer_exception_code'] = $e->getCode();
939
940 /** This filter is documented in wp-includes/pluggable.php */
941 do_action( 'wp_mail_failed', new WP_Error( 'wp_mail_failed', $e->getMessage(), $mail_error_data ) );
942
943 return false;
944 }
945 /*reply_to code */
946 $gmailsmtp_reply_to = '';
947 $gmailsmtp_reply_to = apply_filters('gmailsmtp_reply_to', $gmailsmtp_reply_to);
948 if(isset($gmailsmtp_reply_to) && !empty($gmailsmtp_reply_to)){
949 $temp_reply_to_addresses = explode(",", $gmailsmtp_reply_to);
950 $reply_to = array();
951 foreach($temp_reply_to_addresses as $temp_reply_to_address){
952 $reply_to_address = trim($temp_reply_to_address);
953 $reply_to[] = $reply_to_address;
954 }
955 }
956 /*end of reply_to code */
957 /*cc code */
958 $gmailsmtp_cc = '';
959 $gmailsmtp_cc = apply_filters('gmailsmtp_cc', $gmailsmtp_cc);
960 if(isset($gmailsmtp_cc) && !empty($gmailsmtp_cc)){
961 $temp_cc_recipients = explode(",", $gmailsmtp_cc);
962 $cc = array();
963 foreach($temp_cc_recipients as $temp_cc_recipient){
964 $cc_recipient = trim($temp_cc_recipient);
965 $cc[] = $cc_recipient;
966 }
967 }
968 /*end of cc code */
969 // Set mail's subject and body.
970 $phpmailer->Subject = $subject;
971 $phpmailer->Body = $message;
972
973 // Set destination addresses, using appropriate methods for handling addresses.
974 $address_headers = compact( 'to', 'cc', 'bcc', 'reply_to' );
975
976 foreach ( $address_headers as $address_header => $addresses ) {
977 if ( empty( $addresses ) ) {
978 continue;
979 }
980
981 foreach ( (array) $addresses as $address ) {
982 try {
983 // Break $recipient into name and address parts if in the format "Foo <bar@baz.com>".
984 $recipient_name = '';
985
986 if ( preg_match( '/(.*)<(.+)>/', $address, $matches ) ) {
987 if ( count( $matches ) === 3 ) {
988 $recipient_name = $matches[1];
989 $address = $matches[2];
990 }
991 }
992
993 switch ( $address_header ) {
994 case 'to':
995 $phpmailer->addAddress( $address, $recipient_name );
996 break;
997 case 'cc':
998 $phpmailer->addCC( $address, $recipient_name );
999 break;
1000 case 'bcc':
1001 $phpmailer->addBCC( $address, $recipient_name );
1002 break;
1003 case 'reply_to':
1004 $phpmailer->addReplyTo( $address, $recipient_name );
1005 break;
1006 }
1007 } catch ( PHPMailer\PHPMailer\Exception $e ) {
1008 continue;
1009 }
1010 }
1011 }
1012
1013 // Set Content-Type and charset.
1014
1015 // If we don't have a Content-Type from the input headers.
1016 if ( ! isset( $content_type ) ) {
1017 $content_type = 'text/plain';
1018 }
1019
1020 /**
1021 * Filters the wp_mail() content type.
1022 *
1023 * @since 2.3.0
1024 *
1025 * @param string $content_type Default wp_mail() content type.
1026 */
1027 $content_type = apply_filters( 'wp_mail_content_type', $content_type );
1028
1029 $phpmailer->ContentType = $content_type;
1030
1031 // Set whether it's plaintext, depending on $content_type.
1032 if ( 'text/html' === $content_type ) {
1033 $phpmailer->isHTML( true );
1034 }
1035
1036 // If we don't have a charset from the input headers.
1037 if ( ! isset( $charset ) ) {
1038 $charset = get_bloginfo( 'charset' );
1039 }
1040
1041 /**
1042 * Filters the default wp_mail() charset.
1043 *
1044 * @since 2.3.0
1045 *
1046 * @param string $charset Default email charset.
1047 */
1048 $phpmailer->CharSet = apply_filters( 'wp_mail_charset', $charset );
1049
1050 // Set custom headers.
1051 if ( ! empty( $headers ) ) {
1052 foreach ( (array) $headers as $name => $content ) {
1053 // Only add custom headers not added automatically by PHPMailer.
1054 if ( ! in_array( $name, array( 'MIME-Version', 'X-Mailer' ), true ) ) {
1055 try {
1056 $phpmailer->addCustomHeader( sprintf( '%1$s: %2$s', $name, $content ) );
1057 } catch ( PHPMailer\PHPMailer\Exception $e ) {
1058 continue;
1059 }
1060 }
1061 }
1062 }
1063
1064 if ( isset( $attachments ) && ! empty( $attachments ) ) {
1065 foreach ( $attachments as $filename => $attachment ) {
1066 $filename = is_string( $filename ) ? $filename : '';
1067
1068 try {
1069 $phpmailer->addAttachment( $attachment, $filename );
1070 } catch ( PHPMailer\PHPMailer\Exception $e ) {
1071 continue;
1072 }
1073 }
1074 }
1075
1076 if ( isset( $embeds ) && ! empty( $embeds ) ) {
1077 foreach ( $embeds as $key => $embed_path ) {
1078 /**
1079 * Filters the arguments for PHPMailer's addEmbeddedImage() method.
1080 *
1081 * @since 6.9.0
1082 *
1083 * @param array $args {
1084 * An array of arguments for PHPMailer's addEmbeddedImage() method.
1085 *
1086 * @type string $path The path to the file.
1087 * @type string $cid The Content-ID of the image. Default: The key in the embeds array.
1088 * @type string $name The filename of the image.
1089 * @type string $encoding The encoding of the image. Default: 'base64'.
1090 * @type string $type The MIME type of the image. Default: empty string, which lets PHPMailer auto-detect.
1091 * @type string $disposition The disposition of the image. Default: 'inline'.
1092 * }
1093 */
1094 $embed_args = apply_filters(
1095 'wp_mail_embed_args',
1096 array(
1097 'path' => $embed_path,
1098 'cid' => (string) $key,
1099 'name' => basename( $embed_path ),
1100 'encoding' => 'base64',
1101 'type' => '',
1102 'disposition' => 'inline',
1103 )
1104 );
1105
1106 try {
1107 $phpmailer->addEmbeddedImage(
1108 $embed_args['path'],
1109 $embed_args['cid'],
1110 $embed_args['name'],
1111 $embed_args['encoding'],
1112 $embed_args['type'],
1113 $embed_args['disposition']
1114 );
1115 } catch ( PHPMailer\PHPMailer\Exception $e ) {
1116 continue;
1117 }
1118 }
1119 }
1120
1121 /**
1122 * Fires after PHPMailer is initialized.
1123 *
1124 * @since 2.2.0
1125 *
1126 * @param PHPMailer $phpmailer The PHPMailer instance (passed by reference).
1127 */
1128 do_action_ref_array( 'phpmailer_init', array( &$phpmailer ) );
1129
1130 $mail_data = compact( 'to', 'subject', 'message', 'headers', 'attachments', 'embeds' );
1131
1132 // Send!
1133 try {
1134 $send = $phpmailer->send();
1135
1136 /**
1137 * Fires after PHPMailer has successfully sent an email.
1138 *
1139 * The firing of this action does not necessarily mean that the recipient(s) received the
1140 * email successfully. It only means that the `send` method above was able to
1141 * process the request without any errors.
1142 *
1143 * @since 5.9.0
1144 *
1145 * @param array $mail_data {
1146 * An array containing the email recipient(s), subject, message, headers, attachments, and embeds.
1147 *
1148 * @type string[] $to Email addresses to send message.
1149 * @type string $subject Email subject.
1150 * @type string $message Message contents.
1151 * @type string[] $headers Additional headers.
1152 * @type string[] $attachments Paths to files to attach.
1153 * @type string[] $embeds Paths to files to embed.
1154 * }
1155 */
1156 do_action( 'wp_mail_succeeded', $mail_data );
1157
1158 return $send;
1159 } catch ( PHPMailer\PHPMailer\Exception $e ) {
1160 $mail_data['phpmailer_exception_code'] = $e->getCode();
1161
1162 /**
1163 * Fires after a PHPMailer exception is caught.
1164 *
1165 * @since 4.4.0
1166 *
1167 * @param WP_Error $error A WP_Error object with the PHPMailer\PHPMailer\Exception message, and an array
1168 * containing the mail recipient, subject, message, headers, attachments, and embeds.
1169 */
1170 do_action( 'wp_mail_failed', new WP_Error( 'wp_mail_failed', $e->getMessage(), $mail_data ) );
1171
1172 return false;
1173 }
1174 }
1175